// -------- Base64 encoding un decoding funkcijas --------
var END_OF_INPUT = -1;

var base64Chars = new Array(
    'A','B','C','D','E','F','G','H',
    'I','J','K','L','M','N','O','P',
    'Q','R','S','T','U','V','W','X',
    'Y','Z','a','b','c','d','e','f',
    'g','h','i','j','k','l','m','n',
    'o','p','q','r','s','t','u','v',
    'w','x','y','z','0','1','2','3',
    '4','5','6','7','8','9','+','/'
);

var reverseBase64Chars = new Array();
for (var i=0; i < base64Chars.length; i++) {
    reverseBase64Chars[base64Chars[i]] = i;
}

// gjeneree random stringu
function randomString(len) {
    var chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    var rs = "";
    for (var i=0; i<len; i++) {
	var rnum = Math.floor(Math.random() * chars.length);
	rs += chars.substring(rnum, rnum+1);
    }
    return rs;
}

var base64Str;
var base64Count;
function setBase64Str(str) {
    base64Str = str;
    base64Count = 0;
}
function readBase64() {
    if (!base64Str) return END_OF_INPUT;
    if (base64Count >= base64Str.length) return END_OF_INPUT;
    var c = base64Str.charCodeAt(base64Count) & 0xff;
    base64Count++;
    return c;
}
function encodeBase64(str) {
    setBase64Str(str);
    var result = '';
    var inBuffer = new Array(3);
    var lineCount = 0;
    var done = false;
    while (!done && (inBuffer[0] = readBase64()) != END_OF_INPUT) {
        inBuffer[1] = readBase64();
        inBuffer[2] = readBase64();
        result += (base64Chars[ inBuffer[0] >> 2 ]);
        if (inBuffer[1] != END_OF_INPUT) {
            result += (base64Chars [(( inBuffer[0] << 4 ) & 0x30) | (inBuffer[1] >> 4) ]);
            if (inBuffer[2] != END_OF_INPUT) {
                result += (base64Chars [((inBuffer[1] << 2) & 0x3c) | (inBuffer[2] >> 6) ]);
                result += (base64Chars [inBuffer[2] & 0x3F]);
            } else {
                result += (base64Chars [((inBuffer[1] << 2) & 0x3c)]);
                result += ('=');
                done = true;
            }
        } else {
            result += (base64Chars [(( inBuffer[0] << 4 ) & 0x30)]);
            result += ('=');
            result += ('=');
            done = true;
        }
        lineCount += 4;
        if (lineCount >= 76) {
            result += ('\n');
            lineCount = 0;
        }
    }
    return result;
}
function readReverseBase64() {
    if (!base64Str) return END_OF_INPUT;
    while (true){      
        if (base64Count >= base64Str.length) return END_OF_INPUT;
        var nextCharacter = base64Str.charAt(base64Count);
        base64Count++;
        if (reverseBase64Chars[nextCharacter]) {
            return reverseBase64Chars[nextCharacter];
        }
        if (nextCharacter == 'A') return 0;
    }
    return END_OF_INPUT;
}

function ntos(n) {
    n=n.toString(16);
    if (n.length == 1) n="0"+n;
    n="%"+n;
    return unescape(n);
}

function decodeBase64(str) {
    setBase64Str(str);
    var result = "";
    var inBuffer = new Array(4);
    var done = false;
    while (!done && (inBuffer[0] = readReverseBase64()) != END_OF_INPUT
        && (inBuffer[1] = readReverseBase64()) != END_OF_INPUT) {
        inBuffer[2] = readReverseBase64();
        inBuffer[3] = readReverseBase64();
        result += ntos((((inBuffer[0] << 2) & 0xff)| inBuffer[1] >> 4));
        if (inBuffer[2] != END_OF_INPUT) {
            result +=  ntos((((inBuffer[1] << 4) & 0xff)| inBuffer[2] >> 2));
            if (inBuffer[3] != END_OF_INPUT) {
                result +=  ntos((((inBuffer[2] << 6)  & 0xff) | inBuffer[3]));
            } else {
                done = true;
            }
        } else {
            done = true;
        }
    }
    return result;
}


// sakodee taa, lai var normaali likt linkaa utf-8 stringus.
encodeUTF8String = function(s) {
    var res = "";
    for (var i = 0; i < s.length; ++i) {
        var c = s.charCodeAt(i);
        if (c < 128) {
            res += String.fromCharCode(c);
        }
        else if ((c > 127) && (c < 2048)) {
            res += String.fromCharCode((c >> 6) | 192);
            res += String.fromCharCode((c & 63) | 128);
        }
        else {
            res += String.fromCharCode((c >> 12) | 224);
            res += String.fromCharCode(((c >> 6) & 63) | 128);
            res += String.fromCharCode((c & 63) | 128);
        }
    }
    return res;
}

// iecentree html objektu (padots platums w un augstums h)
function centerObj(obj, w, h) {
    var winW;
    var winH;
    if (window.XMLHttpRequest) { 
        // normaals browseris
        scrollY = window.pageYOffset;
        scrollX = window.pageXOffset;
        winW = window.innerWidth;
        winH = window.innerHeight;
    } else if (window.ActiveXObject) { 
        // Ja ir IE = SX
        scrollY = document.body.scrollTop;
        scrollX = document.body.scrollLeft;
        winW = document.body.offsetWidth;
        winH = document.body.offsetHeight;
    }

    var l = scrollX + winW / 2 - w / 2;
    if (l < 0) l = 0;
    var t = scrollY + winH / 2 - h / 2;
    if (t < 0) t = 0;
    obj.style.left = l;
    obj.style.top = t;
}

// Debug f-jas
function dumpObjToDiv(obj, divid, maxdepth) {
    var div = document.getElementById(divid);
    if (!div) return false;
    var d = dumpObjToDiv_process(obj, 0, maxdepth);
    div.innerHTML = "<pre>\n" + d + "\n</pre>\n" + div.innerHTML;
    return true;
}

function dumpObjToDiv_process(obj, depth, maxdepth) {
    var buf = "";
    if (depth == 0) buf = "---=== Recursive object dump v0.2 ===---\n";
    var atrval = new String();
    if (obj) {
        var indent = "";
        for (var i = 0; i < depth; i++) {
            indent += "    ";
        }
        var empty = true;
        for (var prop in obj) {
            // DIRTY HACK - crasho uz dazhiem atribuutiem un dazhiem 
            // tizliem browseriem, kam nosaukumaa ir IE
            if (window.ActiveXObject 
                || prop == "selectionStart" || prop == "selectionEnd") {
                atrval = "!! UNKNOWN !!";
            } else {
                atrval = String(obj[prop]);
                //if (atrval.length > 50) atrval = atrval.substr(0, 47) + "...";
                atrval = atrval.replace(/\n/g, "\n");
                atrval = atrval.replace(/</g, "[");
                atrval = atrval.replace(/>/g, "]");
            }
            var type = typeof(obj[prop]);
            // haks lai datu dumposhana neietekmeetu kopeejo lapu
            buf += indent + prop + " == " + atrval + "\n";
            if (type == "object" && depth < maxdepth -1) {
                // recursiivais solis
                buf += dumpObjToDiv_process(obj[prop], depth + 1, maxdepth);
            }
            empty = false;
        }
        if (empty) buf += indent + " EMTPY!\n";
    } else {
        buf += "Object not found!";
    }
    return buf;
}

/*
NARIX(v_1.00) request reader
*/

/* namespacing object */
var net = new Object();

net.READY_STATE_UNINITIALIZED=0;
net.READY_STATE_LOADING=1;
net.READY_STATE_LOADED=2;
net.READY_STATE_INTERACTIVE=3;
net.READY_STATE_COMPLETE=4;

// iesleedzam debugoshanu
net.DEBUG = 0;

/*--- content loader object for cross-browser requests ---*/
net.hospital = function() {
    this.req = null;
}

net.hospital.prototype.decodeUTF8String = function(utftext) {  
         var string = "";  
         var i = 0;  
         var c = c1 = c2 = 0;  
   
         while ( i < utftext.length ) {  
   
             c = utftext.charCodeAt(i);  
   
             if (c < 128) {
                 string += String.fromCharCode(c);
                 i++;  
             }  
             else if((c > 191) && (c < 224)) {  
                 c2 = utftext.charCodeAt(i+1);  
                 string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));  
                 i += 2;  
             }  
             else {  
                 c2 = utftext.charCodeAt(i+1);  
                 c3 = utftext.charCodeAt(i+2);  
                 string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));  
                 i += 3;  
             }  
   
         }  
   
         return string;  
     }  

net.hospital.prototype.parseResponse = function() {
    // notiek kaut kaada paarseeshana
    var response = this.req.responseText;
    var message = response.split( "JSON_v1.00" );
    var error;


    for (var x=0;x<message.length;x++) {
        // ja kaads strings ir mazaaks vai vienaads par 1, tad ignoreejam to...
	if (message[x].length<=1) {
           continue;
        }

        // ja atrasts strings pirms protokola vaarda, tad uzskatam to par erroru
        if (x==0 && message[x].length > 1) {
            error = message[x];
        }

        // iemetam error divaa iekshaa error mesaagi
        if (error) {
           if (net.DEBUG) {
             if (document.getElementById("error_box")) {
                var obj = document.getElementById("error_box");
                obj.innerHTML += error+"<br/>";
             }
           }
           error = null;
        } else {
           // galvenais masiivs, kuraa glabaasies visa sanjemtaa datu struktuura
	   var pack = new Object();
        
           // uztaisam sanjemoto JSON mesaagi par valiigu JS masiivu
   	   pack = eval("(" + message[x] + ")");

           // te izsaucas Dealer handleris
           handlePack( pack );
        }
    }
}

net.hospital.prototype.loadXMLDoc = function(url, method, module, params) {
    // defaultaa metode=GET
    if (!method) {
	method="GET";
    }
    params = "action="+module+"&request_data="+encodeBase64( encodeUTF8String( params ) ).replace(/\+/gm, "%2B");

    var contentType = "";

    // ja nav noraadiits kontent-taips un ir POST metode, tad piedefineejam
    if (!contentType && method=="POST") {
	contentType = "application/x-www-form-urlencoded";
    }

    if (window.XMLHttpRequest) { // Moziilla utt
	this.req = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // SX
	this.req = new ActiveXObject("Microsoft.XMLHTTP");
    }

    if (this.req){
	try {
	    var loader = this;
	    this.req.onreadystatechange = function() {
		net.hospital.onReadyState.call(loader);
	    }
	    this.req.open(method,url,true);
	    if (contentType) {
		this.req.setRequestHeader("Content-Type", contentType);
	    }
	    this.req.send(params);

        var b = document.getElementById("loading_box");
        if (b) {
//            centerObj(b, 80, 30);
            b.style.display = "block";
        }

	} catch (err) {
	    this.defaultError.call(this);
	}
    }
}

// funkcija, kas izsaucaas, kad sanjem atbildi
net.hospital.onReadyState = function() {
    var req=this.req;
    var ready=req.readyState;
    if (ready==net.READY_STATE_COMPLETE) {
        var b = document.getElementById("loading_box");
        if (b) b.style.display = "none";
        this.parseResponse.call(this);
    }
}

net.hospital.prototype.defaultError = function() {
    alert("error fetching data!");
}

/* NARIX v_1.00 multirequest library */
function MRequests() {
    this.defaultMethod = "POST";
    this.actionFile = "/kravad/rma/engine.php";
    this.storage = new Array();
}

// iesaak transakciju un atgriezj attieciigo id
MRequests.prototype.start = function() {
    // uzgjeneree stringu, peec kura atradiis objektu 
    // masiivaa attieciigo requestu
    var rand_string = randomString(10);
    
    // uztaisam jaunu objektu
    var new_object = new net.hospital();
    
    // izveidojam jaunu apakshmasiivu prieksh objekta un kveves
    this.storage[rand_string] = new Array();
    this.storage[rand_string]["obj_name"] = new_object;

    this.storage[rand_string]["queue"] = "";

    return rand_string;
}

// noselektee visus formas mainiigos un nosuuta ar GETu
MRequests.prototype.addForm = function(formname, trans_id, module, variables, submit_button) {
    var getstr = "";
    var form = eval("document."+formname);
    var value;

    if ( form ) {
      for (i=0; i<form.length; i++) {
	var elem = form.elements[i];
        value = elem.value;

        // aizstaajam & ar kaut ko vairaak
	while (value.indexOf('&')>=0) {
           if ( value.indexOf('&')>=0) {
               value = value.replace('&', '%26');
           }
        }

	switch (elem.tagName) {
	case "INPUT" : {
	    switch (elem.type) {
	    case "file":
	    case "text" : 
	    case "password" :
	    case "hidden" : {
		getstr += elem.name + "=" + value + "&";
		break;
	    }
	    case "checkbox" : {
		if (elem.checked) {
		    getstr += elem.name + "=" + value + "&";
		} else {
		    getstr += elem.name + "=&";
		}
		break;
	    }
	    case "radio" : {
		if (elem.checked) 
		    getstr += elem.name + "=" + value + "&";		 
		break;
	    }
	    }
	    break;
	}
	    
	case "SELECT" : {
            value = elem.options[elem.selectedIndex].value;

            // aizstaajam & ar kaut ko vairaak
    	    
            while (value.indexOf('&')>=0) {
               if ( value.indexOf('&')>=0) {
                  value = value.replace('&', '%26');
               }
            }

            if (elem.selectedIndex>=0) {
	        getstr += elem.name + "=" + value + "&";
            }
	    break;
	}
	    
	case "TEXTAREA" : {
	    getstr += elem.name + "=" + value + "&";
	    break;
	}
	}
      }
    
      // ja ir padota poga, ar kuru submitee formu - piemet klaat GETaa
      if (submit_button) {
        getstr += submit_button + "=" + eval("form." + submit_button + ".value");
      }
    }

    // ja ir padota poga, ar kuru submitee formu - piemet klaat GETaa
    if (variables) {
	getstr = variables + "&" + getstr;
    }

    getstr += "_|*_|"; // beidzas mainiigie

    this.storage[trans_id]["queue"] += getstr;
    this.storage[trans_id]["module"] = module;
 }

MRequests.prototype.addUrl = function(url, trans_id, module) {
    var getstr = "";
    this.storage[trans_id]["module"] = module;

    // ja ir noraadiits urlis
    if (url) {
        getstr = url;
    }

    getstr += "_|*_|"; // beidzas mainiigie
    this.storage[trans_id]["queue"] += getstr;
}

MRequests.prototype.commit = function(trans_id) {
    var obj = this.storage[trans_id]["obj_name"];
    var queue = this.storage[trans_id]["queue"];
    var module = this.storage[trans_id]["module"];
    var url = this.actionFile;

    obj.loadXMLDoc(url, this.defaultMethod, module, queue);

    delete obj;
}

var multireq = new MRequests();
var loguMasivs = Array();

// te ir visu message apstraadaataajs
function handlePack(pack) {
    var obj = document.getElementById("error_box");
    if (obj) {
        dumpObjToDiv(pack, "error_box", 123);
    }

    if (pack.act) {
        switch (pack.act) {
          case "add":
            var o = document.getElementById(pack.target);
            if (o) {
                o.innerHTML += pack.data;
            }
            break;
          case "set":
            var o = document.getElementById(pack.target);
            if (o) {
                o.innerHTML = pack.data;
            }
            break;
          case "show":
            var o = document.getElementById(pack.target);
            if (o) {
                o.style.display = "block";
            }
            break;
          case "hide":
            var o = document.getElementById(pack.target);
            if (o) {
                o.style.display = "none";
            }
            break;
          case "position":
            var o = document.getElementById(pack.target);
            if (o) {
                o.style.top = pack.top;
                o.style.left = pack.left;
            }
            break;
          case "error":
            var obj = document.getElementById("error_box");
            if (obj) {
                obj.style.display = "block";
                obj.innerHTML = "<div style='color: red;'>" + pack.data + "</div>" + obj.innerHTML;
            }
            break;
          case "js":
            eval(pack.data);
            break;
          case "wupdateform":
            document.getElementById(pack.target + "ramis").innerHTML = pack.data + '<div id="' + pack.target + '" class="logscontent">' + document.getElementById(pack.target).innerHTML + '</div></form>';
            break;
          case "wrefreshform":
            var oi=multireq.start();
            multireq.addForm(pack.target + "form", oi, pack.action, pack.params, '');
            multireq.commit(oi);
            break;
          case "wcreate":
            if ( loguMasivs[ pack.name ] && loguMasivs[ pack.name ] > 0 ) {
                closeWindow( loguMasivs[ pack.name ] );
                loguMasivs[ pack.name ] = 0;
            }
            var jlogs_id = createNewWindow(pack.name, pack.refresh, pack.close, pack.title, pack.data, pack.width, pack.height, pack.left, pack.top);
            loguMasivs[pack.name] = jlogs_id;
            break;
          case "wdestroy":
            closeWindow( loguMasivs[ pack.target ] );
            loguMasivs[ pack.target ] = 0;
            break;
        }
    }
}


/*
 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
 * Digest Algorithm, as defined in RFC 1321.
 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for more info.
 */

/*
 * Configurable variables. You may need to tweak these to be compatible with
 * the server-side, but the defaults work in most cases.
 */
var hexcase = 0;  /* hex output format. 0 - lowercase; 1 - uppercase        */
var b64pad  = ""; /* base-64 pad character. "=" for strict RFC compliance   */
var chrsz   = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */

/*
 * These are the functions you'll usually want to call
 * They take string arguments and return either hex or base-64 encoded strings
 */
function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));}
function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }

/*
 * Perform a simple self-test to see if the VM is working
 */
function md5_vm_test()
{
  return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}

/*
 * Calculate the MD5 of an array of little-endian words, and a bit length
 */
function core_md5(x, len)
{
  /* append padding */
  x[len >> 5] |= 0x80 << ((len) % 32);
  x[(((len + 64) >>> 9) << 4) + 14] = len;

  var a =  1732584193;
  var b = -271733879;
  var c = -1732584194;
  var d =  271733878;

  for(var i = 0; i < x.length; i += 16)
  {
    var olda = a;
    var oldb = b;
    var oldc = c;
    var oldd = d;

    a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
    d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
    c = md5_ff(c, d, a, b, x[i+ 2], 17,  606105819);
    b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
    a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
    d = md5_ff(d, a, b, c, x[i+ 5], 12,  1200080426);
    c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
    b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
    a = md5_ff(a, b, c, d, x[i+ 8], 7 ,  1770035416);
    d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
    c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
    b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
    a = md5_ff(a, b, c, d, x[i+12], 7 ,  1804603682);
    d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
    c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
    b = md5_ff(b, c, d, a, x[i+15], 22,  1236535329);

    a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
    d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
    c = md5_gg(c, d, a, b, x[i+11], 14,  643717713);
    b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
    a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
    d = md5_gg(d, a, b, c, x[i+10], 9 ,  38016083);
    c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
    b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
    a = md5_gg(a, b, c, d, x[i+ 9], 5 ,  568446438);
    d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
    c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
    b = md5_gg(b, c, d, a, x[i+ 8], 20,  1163531501);
    a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
    d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
    c = md5_gg(c, d, a, b, x[i+ 7], 14,  1735328473);
    b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);

    a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
    d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
    c = md5_hh(c, d, a, b, x[i+11], 16,  1839030562);
    b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
    a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
    d = md5_hh(d, a, b, c, x[i+ 4], 11,  1272893353);
    c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
    b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
    a = md5_hh(a, b, c, d, x[i+13], 4 ,  681279174);
    d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
    c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
    b = md5_hh(b, c, d, a, x[i+ 6], 23,  76029189);
    a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
    d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
    c = md5_hh(c, d, a, b, x[i+15], 16,  530742520);
    b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);

    a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
    d = md5_ii(d, a, b, c, x[i+ 7], 10,  1126891415);
    c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
    b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
    a = md5_ii(a, b, c, d, x[i+12], 6 ,  1700485571);
    d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
    c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
    b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
    a = md5_ii(a, b, c, d, x[i+ 8], 6 ,  1873313359);
    d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
    c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
    b = md5_ii(b, c, d, a, x[i+13], 21,  1309151649);
    a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
    d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
    c = md5_ii(c, d, a, b, x[i+ 2], 15,  718787259);
    b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);

    a = safe_add(a, olda);
    b = safe_add(b, oldb);
    c = safe_add(c, oldc);
    d = safe_add(d, oldd);
  }
  return Array(a, b, c, d);

}

/*
 * These functions implement the four basic operations the algorithm uses.
 */
function md5_cmn(q, a, b, x, s, t)
{
  return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
  return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
  return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
  return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
  return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}

/*
 * Calculate the HMAC-MD5, of a key and some data
 */
function core_hmac_md5(key, data)
{
  var bkey = str2binl(key);
  if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);

  var ipad = Array(16), opad = Array(16);
  for(var i = 0; i < 16; i++)
  {
    ipad[i] = bkey[i] ^ 0x36363636;
    opad[i] = bkey[i] ^ 0x5C5C5C5C;
  }

  var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
  return core_md5(opad.concat(hash), 512 + 128);
}

/*
 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
 * to work around bugs in some JS interpreters.
 */
function safe_add(x, y)
{
  var lsw = (x & 0xFFFF) + (y & 0xFFFF);
  var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
  return (msw << 16) | (lsw & 0xFFFF);
}

/*
 * Bitwise rotate a 32-bit number to the left.
 */
function bit_rol(num, cnt)
{
  return (num << cnt) | (num >>> (32 - cnt));
}

/*
 * Convert a string to an array of little-endian words
 * If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
 */
function str2binl(str)
{
  var bin = Array();
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < str.length * chrsz; i += chrsz)
    bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
  return bin;
}

/*
 * Convert an array of little-endian words to a string
 */
function binl2str(bin)
{
  var str = "";
  var mask = (1 << chrsz) - 1;
  for(var i = 0; i < bin.length * 32; i += chrsz)
    str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
  return str;
}

/*
 * Convert an array of little-endian words to a hex string.
 */
function binl2hex(binarray)
{
  var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i++)
  {
    str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
           hex_tab.charAt((binarray[i>>2] >> ((i%4)*8  )) & 0xF);
  }
  return str;
}

/*
 * Convert an array of little-endian words to a base-64 string
 */
function binl2b64(binarray)
{
  var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var str = "";
  for(var i = 0; i < binarray.length * 4; i += 3)
  {
    var triplet = (((binarray[i   >> 2] >> 8 * ( i   %4)) & 0xFF) << 16)
                | (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
                |  ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
    for(var j = 0; j < 4; j++)
    {
      if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
      else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
    }
  }
  return str;
}

/* f-ja, kas shifree krepu, lai lameri nevar nofetchod datus */
function taisaKodu( md5var, passvar, real_pass ) {
    var uni_id = document.getElementById( md5var );
    var passwd = document.getElementById( passvar );
    var realpass = document.getElementById( real_pass );

    if (uni_id) {
		if (passwd) {
		    normalstring = uni_id.value + passwd.value;
	    	hashstring = hex_md5(normalstring);
	    	realpass.value = hashstring;
	    	passwd.value = '';
	    	return true;
		} else {
	    	alert("Enter password!");
	    	return false;
		}
    } else {
		alert("System failed!");
		return false;
    }
}

/* f-ja, kas ielaadee file upload formu prieksh kreisajaam klientu invoiceem*/

function getUploadForm() {
	$('#file_upload').hide();
	$('#file_upload').show(150);
}

//function openAskOfWarranty() {
//    $('#areyousure_of_warranty').ready(function(){
//        $('#areyousure_of_warranty').dialog({
//            modal:true,
//            height:200,
//            width:600,
//            buttons: {
//                'Yes, I agree' : function() {
//                   $('#kv_addpart').append('<input type=\"hidden\" name=\"agree_of_warranty\" value=1>');
//                   $('#kv_addpart').submit();
//                   $(this).dialog('close');
//                },
//                'No, thank you' : function() {
//                    $(this).dialog('close');
//                    return false;
//                }
//            }
//        })
//    });
//    return false;
//}

function openNonEuShipmentInfo(text) {
	$('#eushipmentinfodialog').ready(function(){
		$('#eushipmentinfodialog').html(text);
		$('#eushipmentinfodialog').show();
	    $('#eushipmentinfodialog').dialog({
	    	modal:true,
            height:300,
            width:600,
            buttons : {
            	'I have read and agree' : function () {
            		$('#allunitlst').append('<input type="hidden" name="rm_doSave" value="1" />');
            		$('#allunitlst').submit();
            		$(this).dialog('close');
            	},
            	'Cancel' : function () {
            		$(this).dialog('close');
            		
            	} 
            }
	    })
	});
	return false;
}

function openAreyousureCompensateThis(text) {
	if($('input[name^="kv_comp_req_"]:checked').length>0) {
		$('#areyousurecompensatethis').ready(function(){
			$('#areyousurecompensatethis').html(text);
			$('#areyousurecompensatethis').show();
			$('#areyousurecompensatethis').dialog({
				modal : true,
				height:300,
	            width:600,
	            buttons : {
	            	'Continue' : function() {
	            		$('#kv_partlist').append('<input type="hidden" name="doSaveChanges" value="1">');
	            		$('#kv_partlist').append('<input type="hidden" name="confirmed_compensate_this" value="1">');
	            		blockScreen();
	            		$('#kv_partlist').submit();
	            	}, 
	            	'Cancel' : function () {
	            		$(this).dialog('close');
	            	}
	            }
			});
		});
		return false;
	}
    return true;
}

function blockScreen() {
	$("#blocker").dialog({modal:true, draggable:false, resizable:false, beforeClose: function(event, ui) { return false; } });
	$("#blocker .ui-dialog-titlebar-close").hide();
}
function markAddedFile(elem){$(elem).addClass("uploadThis");}
function submitAddedFiles(){$("input:file").each(function(){if($(this).hasClass("uploadThis")){}else{$(this).remove();}});}

