(function(window){if(!ts.paymentgateway)
ts.paymentgateway={};ts.paymentgateway={payPalExpress:null,modalId:0,filterChargeDefinitionsUrl:"/SetupFinance/PaymentGateway/FilterChargeDefinitions/{0}",init:function(){var noScreens=parseInt($('#numberScreens').val());var screenItemW=parseInt(100/(noScreens+1));var screenW=parseInt(100/noScreens);$('.noScreens').width((screenItemW-1).toString()+'%');$('.noScreensC').width((noScreens*screenItemW).toString()+'%');$('.screenC').width(screenW.toString()+'%');},initGatewaySettings:function(){ts.paymentgateway.modalId=ts.win.modal({url:'/SetupFinance/PaymentGateway/GatewaySettings',title:'Gateway Settings',binder:function(){ts.paymentgateway.payPalExpress=$('input[name*="cbPayPal"]:checked').length>0;ts.paymentgateway.initInfoForm('#merchantForm','Merchant','#activateMerchant');ts.paymentgateway.initInfoForm('#payPalForm','Pay Pal','#activatePayPal');ts.paymentgateway.activateGateway('#activateMerchant','#activatePayPal','#merchantForm','#payPalForm','Merchant','Pay Pal');ts.paymentgateway.activateGateway('#activatePayPal','#activateMerchant','#payPalForm','#merchantForm','Pay Pal','Merchant');ts.paymentgateway.addConvenienceFeeValidationRules('#merchantForm',ts.paymentgateway.labels.MesGateway);ts.paymentgateway.addConvenienceFeeValidationRules('#payPalForm',ts.paymentgateway.labels.PayPalGateway);ts.paymentgateway.initChargeDefinitionsFilter(ts.paymentgateway.labels.MesGateway);ts.paymentgateway.initChargeDefinitionsFilter(ts.paymentgateway.labels.PayPalGateway);ts.paymentgateway.toggleConvenienceFee(ts.paymentgateway.labels.MesGateway);ts.paymentgateway.toggleConvenienceFee(ts.paymentgateway.labels.PayPalGateway);}});},initInfoForm:function(gatewayForm,gatewayFilter,activateLink){if($('#IsActive',$(gatewayForm)).val()=='True'){$(activateLink).hide();$('.sideNavScrollingPanelSetItem').filter(':contains("'+gatewayFilter+'")').each(function(index,panel){var panelO=$(panel);panelO.append('Active Credit Card Gateway');ts.panel.sideNavScrolling.gotoBySeq('sideNavScrollingPanelSetGatewayConnectionPanels',panelO.attr('tsid'));});}},activateGateway:function(activateLink,nonActivateLink,activateForm,nonActivateForm,activateFilter,nonActivateFilter){var scope=this;$(activateLink).click(function(e){ts.msg.sendInfo('Activating '+activateFilter+'...');$('#IsActive',$(activateForm)).val('True');$('#IsActive',$(nonActivateForm)).val('False');(activateFilter=='Merchant')?scope.validateMerchantForm():scope.validatePayPalForm();if($(activateForm).valid()){ts.ajax.send({url:'/SetupFinance/PaymentGateway/ActivateGateway',data:{type:$('#PaymentGatewayType',$(activateForm)).val()},type:'POST',successHandler:function(result){ts.ajax.handleResult(result);$('.sideNavScrollingPanelSetItem').filter(':contains("'+nonActivateFilter+'")').find('span').remove();$('.sideNavScrollingPanelSetItem').filter(':contains("'+activateFilter+'")').append('Active Credit Card Gateway');$(nonActivateLink).show();$(activateLink).hide();if(result.HtmlResult!=null)
$('#gatewayInfo').html(result.HtmlResult);},errorHandler:function(result){$('#IsActive',$(activateForm)).val('False');$('#IsActive',$(nonActivateForm)).val('True');ts.msg.sendError('An error occurred while saving payment methods.');ts.msg.sendMsg('sysWarning','unknown error ts.paymentgatewa.savePaymentMethods ajax: '+result.responseText);}});}
else{$('#IsActive',$(activateForm)).val('False');$('#IsActive',$(nonActivateForm)).val('True');ts.msg.sendInfo(String.format('Required fields must be set for {0}.',activateFilter));}});},savePaymentMethods:function(){var serializedData=ts.paymentgateway.paymentMethodsSerialize();var postData={'__RequestVerificationToken':$('input[name=__RequestVerificationToken]').val(),'GatewayPreference':serializedData};var url='/SetupFinance/PaymentGateway/PaymentMethods/Edit';ts.ajax.send({url:url,data:postData,type:'POST',successHandler:function(result){ts.ajax.handleResult(result);},errorHandler:function(result){ts.msg.sendError('An error occurred while saving payment methods.');ts.msg.sendMsg('sysWarning','unknown error ts.paymentgatewa.savePaymentMethods ajax: '+result.responseText);}});},savePayPal:function(){ts.paymentgateway.validatePayPalForm();ts.paymentgateway.saveGatewaySetting($('#payPalForm'),'PayPal');},saveMerchant:function(){ts.paymentgateway.validateMerchantForm();ts.paymentgateway.saveGatewaySetting($('#merchantForm'),'Merchant');},saveGatewaySetting:function(gatewayForm,gatewayName){if(gatewayForm.valid()){var data=gatewayForm.serialize();var url=String.format('/SetupFinance/PaymentGateway/{0}/Edit',gatewayName);ts.ajax.send({url:url,data:data,type:'POST',successHandler:function(result){ts.ajax.handleResult(result);if(result.HtmlResult!=null)
$('#gatewayInfo').html(result.HtmlResult);},errorHandler:function(result){ts.msg.sendError('An error occurred while saving '+gatewayName+' settings.');ts.msg.sendMsg('sysWarning','unknown error ts.paymentgatewa.saveGatewaySetting ajax: '+result.responseText);}});}},paymentMethodsSerialize:function(){var results=new Array();$.each($('.preference'),function(index,element){var id=$(element).attr('ts-id');var cbCreditCard=$(element).find('[name='+'cbCredit_'+id+'][type=checkbox]').is(':checked');var cbPayPal=$(element).find('[name='+'cbPayPal_'+id+'][type=checkbox]').is(':checked');var o={GatewayPreferenceId:parseInt(id),ScreenName:$('#screenName'+id,element).val(),Description:$('.screensHeader label',element).text(),AcceptCreditCard:cbCreditCard,AcceptPayPalExpress:cbPayPal};results.push(o);});return results;},validateMerchantForm:function(){$('#merchantForm').validate({});var gatewayForm=$('#merchantForm');var isActive=$('#IsActive',$('#merchantForm')).val()=='True';var isInSandbox=$('#IsInSandbox',gatewayForm).first().is(':checked');if(isActive){if(isInSandbox){$('#SandboxProfileId,#SandboxProfileKey',gatewayForm).addClass('required');$('#ProfileId,#ProfileKey',gatewayForm).removeClass('required');}
else{$('#ProfileId,#ProfileKey',gatewayForm).addClass('required');$('#SandboxProfileId,#SandboxProfileKey',gatewayForm).removeClass('required');}}
else{$('#ProfileId,#ProfileKey',gatewayForm).removeClass('required');$('#SandboxProfileId,#SandboxProfileKey',gatewayForm).removeClass('required');}},validatePayPalForm:function(){$('#payPalForm').validate({});var gatewayForm=$('#payPalForm');var isActive=$('#IsActive',gatewayForm).val()=='True';var isInSandbox=$('#IsInSandbox',gatewayForm).first().is(':checked');if(isActive||ts.paymentgateway.payPalExpress){if(isInSandbox){$('#SandboxUsername,#SandboxPassword,#SandboxProfileKey',gatewayForm).addClass('required');$('#Username,#Password,#Signature',gatewayForm).removeClass('required');}
else{$('#Username,#Password,#Signature',gatewayForm).addClass('required');$('#SandboxUsername,#SandboxPassword,#SandboxProfileKey',gatewayForm).removeClass('required');}}
else{$('#Username,#Password,#Signature',gatewayForm).removeClass('required');$('#SandboxUsername,#SandboxPassword,#SandboxProfileKey',gatewayForm).removeClass('required');}},filterChargeDefinitions:function(searchField,valueField){var $this=this;$(searchField).autocomplete({source:function(request,response){var url=String.format($this.filterChargeDefinitionsUrl,request.term);ts.ajax.send({url:url,successHandler:function(result){response($.map(result,function(item){return{label:item.Value,value:item.Key};}));}});},minLength:2,select:function(event,ui){$(searchField).val(ui.item.label);$(valueField).val(ui.item.value);return false;},change:function(event,ui){if(ui.item==null){$(valueField).val('');}
return false;},focus:function(event,ui){event.preventDefault();$(this).val(ui.item.label);$(valueField).val(ui.item.value);return false;}});},initChargeDefinitionsFilter:function(gateway){var chargeDefinitionNameControlId=String.format('#{0}_ConvenienceFeeChargeDefinitionName',gateway);var chargeDefinitionIdControlId=String.format('#{0}_ConvenienceFeeChargeDefinitionId',gateway);ts.paymentgateway.filterChargeDefinitions(chargeDefinitionNameControlId,chargeDefinitionIdControlId);},addConvenienceFeeValidationRules:function(form,gateway){var $this=this;var convinienceFeeControlId=String.format('#{0}_ConvenienceFeePercentage',gateway);var chargeDefinitionIdControlId=String.format('#{0}_ConvenienceFeeChargeDefinitionId',gateway);var chargeDefinitionNameControlId=String.format('#{0}_ConvenienceFeeChargeDefinitionName',gateway);var isConvenienceFeeEnabledId=String.format('#{0}_IsConvenienceFeeEnabled',gateway);$.validator.addMethod("twoDecimals",function(value,element){return this.optional(element)||/^\d+(\.\d{0,2})?$/.test(value);});$(form).validate({});$(convinienceFeeControlId).rules("add",{number:true,range:[0,100],twoDecimals:true,required:function(){var isRequired=$(isConvenienceFeeEnabledId).val()&&$(chargeDefinitionIdControlId).val()?true:false;return isRequired;},messages:{number:$this.labels.OnlyDecimalsAreAllowed,twoDecimals:$this.labels.MustBeLessThan100WithTwoDecimalPlaces,range:$this.labels.ConvenienceFeeOutOfRange,required:$this.labels.EnterConvenienceFeePercentage}});$(chargeDefinitionNameControlId).rules("add",{required:function(){var isRequired=$(isConvenienceFeeEnabledId).val()&&$(convinienceFeeControlId).val()?true:false;return isRequired;},messages:{required:$this.labels.EnterConvenienceFeeChargeDefintion}});},toggleConvenienceFee:function(gateway){var convinienceFeeControlId=String.format('#{0}_ConvenienceFeePercentage',gateway);var chargeDefinitionNameControlId=String.format('#{0}_ConvenienceFeeChargeDefinitionName',gateway);var isConvenienceFeeEnabledId=String.format('#{0}_IsConvenienceFeeEnabled',gateway);$(isConvenienceFeeEnabledId).change(function(){$(convinienceFeeControlId).toggleReadOnly();$(chargeDefinitionNameControlId).toggleReadOnly();});},labels:{MesGateway:window.mesGateway||'MeS',PayPalGateway:window.payPalGateway||'PayPal',ConvenienceFeeOutOfRange:window.convenienceFeeOutOfRange||'Must be in range 0..100.',EnterConvenienceFeeChargeDefintion:window.enterConvenienceFeeChargeDefintion||'Please enter Charge Definition.',EnterConvenienceFeePercentage:window.enterConvenienceFeePercentage||'Please enter Convenience Fee.',MustBeLessThan100WithTwoDecimalPlaces:window.convenienceFeeMustBeLessThan100WithTwoDecimalPlaces||'Must be less than 100 with two decimal places.',OnlyDecimalsAreAllowed:window.convenienceFeeOnlyDecimalsAreAllowed||'Only Decimals are Allowed.'}};$.fn.toggleReadOnly=function(){return this.each(function(){if($(this).is('[readonly]')){$(this).removeAttr('readonly');$(this).removeClass('readonly');}else{$(this).attr('readonly','readonly');$(this).addClass('readonly');}});};$(document).ready(function(){ts.paymentgateway.init();});})(window);