﻿/// <reference path="jquery-1.4.2.js" />
/// <reference path="jquery.validate.modified.js" />
/// <reference path="validation.js" />

var swfobject = function() { var b = "undefined", Q = "object", n = "Shockwave Flash", p = "ShockwaveFlash.ShockwaveFlash", P = "application/x-shockwave-flash", m = "SWFObjectExprInst", j = window, K = document, T = navigator, o = [], N = [], i = [], d = [], J, Z = null, M = null, l = null, e = false, A = false; var h = function() { var v = typeof K.getElementById != b && typeof K.getElementsByTagName != b && typeof K.createElement != b, AC = [0, 0, 0], x = null; if (typeof T.plugins != b && typeof T.plugins[n] == Q) { x = T.plugins[n].description; if (x && !(typeof T.mimeTypes != b && T.mimeTypes[P] && !T.mimeTypes[P].enabledPlugin)) { x = x.replace(/^.*\s+(\S+\s+\S+$)/, "$1"); AC[0] = parseInt(x.replace(/^(.*)\..*$/, "$1"), 10); AC[1] = parseInt(x.replace(/^.*\.(.*)\s.*$/, "$1"), 10); AC[2] = /r/.test(x) ? parseInt(x.replace(/^.*r(.*)$/, "$1"), 10) : 0 } } else { if (typeof j.ActiveXObject != b) { var y = null, AB = false; try { y = new ActiveXObject(p + ".7") } catch (t) { try { y = new ActiveXObject(p + ".6"); AC = [6, 0, 21]; y.AllowScriptAccess = "always" } catch (t) { if (AC[0] == 6) { AB = true } } if (!AB) { try { y = new ActiveXObject(p) } catch (t) { } } } if (!AB && y) { try { x = y.GetVariable("$version"); if (x) { x = x.split(" ")[1].split(","); AC = [parseInt(x[0], 10), parseInt(x[1], 10), parseInt(x[2], 10)] } } catch (t) { } } } } var AD = T.userAgent.toLowerCase(), r = T.platform.toLowerCase(), AA = /webkit/.test(AD) ? parseFloat(AD.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, q = false, z = r ? /win/.test(r) : /win/.test(AD), w = r ? /mac/.test(r) : /mac/.test(AD); /*@cc_onq = true; @if(@_win32)z = true; @elif(@_mac)w=true;@end@*/return { w3cdom: v, pv: AC, webkit: AA, ie: q, win: z, mac: w} } (); var L = function() { if (!h.w3cdom) { return } f(H); if (h.ie && h.win) { try { K.write("<script id=__ie_ondomload defer=true src=//:><\/script>"); J = C("__ie_ondomload"); if (J) { I(J, "onreadystatechange", S) } } catch (q) { } } if (h.webkit && typeof K.readyState != b) { Z = setInterval(function() { if (/loaded|complete/.test(K.readyState)) { E() } }, 10) } if (typeof K.addEventListener != b) { K.addEventListener("DOMContentLoaded", E, null) } R(E) } (); function S() { if (J.readyState == "complete") { J.parentNode.removeChild(J); E() } } function E() { if (e) { return } if (h.ie && h.win) { var v = a("span"); try { var u = K.getElementsByTagName("body")[0].appendChild(v); u.parentNode.removeChild(u) } catch (w) { return } } e = true; if (Z) { clearInterval(Z); Z = null } var q = o.length; for (var r = 0; r < q; r++) { o[r]() } } function f(q) { if (e) { q() } else { o[o.length] = q } } function R(r) { if (typeof j.addEventListener != b) { j.addEventListener("load", r, false) } else { if (typeof K.addEventListener != b) { K.addEventListener("load", r, false) } else { if (typeof j.attachEvent != b) { I(j, "onload", r) } else { if (typeof j.onload == "function") { var q = j.onload; j.onload = function() { q(); r() } } else { j.onload = r } } } } } function H() { var t = N.length; for (var q = 0; q < t; q++) { var u = N[q].id; if (h.pv[0] > 0) { var r = C(u); if (r) { N[q].width = r.getAttribute("width") ? r.getAttribute("width") : "0"; N[q].height = r.getAttribute("height") ? r.getAttribute("height") : "0"; if (c(N[q].swfVersion)) { if (h.webkit && h.webkit < 312) { Y(r) } W(u, true) } else { if (N[q].expressInstall && !A && c("6.0.65") && (h.win || h.mac)) { k(N[q]) } else { O(r) } } } } else { W(u, true) } } } function Y(t) { var q = t.getElementsByTagName(Q)[0]; if (q) { var w = a("embed"), y = q.attributes; if (y) { var v = y.length; for (var u = 0; u < v; u++) { if (y[u].nodeName == "DATA") { w.setAttribute("src", y[u].nodeValue) } else { w.setAttribute(y[u].nodeName, y[u].nodeValue) } } } var x = q.childNodes; if (x) { var z = x.length; for (var r = 0; r < z; r++) { if (x[r].nodeType == 1 && x[r].nodeName == "PARAM") { w.setAttribute(x[r].getAttribute("name"), x[r].getAttribute("value")) } } } t.parentNode.replaceChild(w, t) } } function k(w) { A = true; var u = C(w.id); if (u) { if (w.altContentId) { var y = C(w.altContentId); if (y) { M = y; l = w.altContentId } } else { M = G(u) } if (!(/%$/.test(w.width)) && parseInt(w.width, 10) < 310) { w.width = "310" } if (!(/%$/.test(w.height)) && parseInt(w.height, 10) < 137) { w.height = "137" } K.title = K.title.slice(0, 47) + " - Flash Player Installation"; var z = h.ie && h.win ? "ActiveX" : "PlugIn", q = K.title, r = "MMredirectURL=" + j.location + "&MMplayerType=" + z + "&MMdoctitle=" + q, x = w.id; if (h.ie && h.win && u.readyState != 4) { var t = a("div"); x += "SWFObjectNew"; t.setAttribute("id", x); u.parentNode.insertBefore(t, u); u.style.display = "none"; var v = function() { u.parentNode.removeChild(u) }; I(j, "onload", v) } U({ data: w.expressInstall, id: m, width: w.width, height: w.height }, { flashvars: r }, x) } } function O(t) { if (h.ie && h.win && t.readyState != 4) { var r = a("div"); t.parentNode.insertBefore(r, t); r.parentNode.replaceChild(G(t), r); t.style.display = "none"; var q = function() { t.parentNode.removeChild(t) }; I(j, "onload", q) } else { t.parentNode.replaceChild(G(t), t) } } function G(v) { var u = a("div"); if (h.win && h.ie) { u.innerHTML = v.innerHTML } else { var r = v.getElementsByTagName(Q)[0]; if (r) { var w = r.childNodes; if (w) { var q = w.length; for (var t = 0; t < q; t++) { if (!(w[t].nodeType == 1 && w[t].nodeName == "PARAM") && !(w[t].nodeType == 8)) { u.appendChild(w[t].cloneNode(true)) } } } } } return u } function U(AG, AE, t) { var q, v = C(t); if (v) { if (typeof AG.id == b) { AG.id = t } if (h.ie && h.win) { var AF = ""; for (var AB in AG) { if (AG[AB] != Object.prototype[AB]) { if (AB.toLowerCase() == "data") { AE.movie = AG[AB] } else { if (AB.toLowerCase() == "styleclass") { AF += ' class="' + AG[AB] + '"' } else { if (AB.toLowerCase() != "classid") { AF += " " + AB + '="' + AG[AB] + '"' } } } } } var AD = ""; for (var AA in AE) { if (AE[AA] != Object.prototype[AA]) { AD += '<param name="' + AA + '" value="' + AE[AA] + '" />' } } v.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + AF + ">" + AD + "</object>"; i[i.length] = AG.id; q = C(AG.id) } else { if (h.webkit && h.webkit < 312) { var AC = a("embed"); AC.setAttribute("type", P); for (var z in AG) { if (AG[z] != Object.prototype[z]) { if (z.toLowerCase() == "data") { AC.setAttribute("src", AG[z]) } else { if (z.toLowerCase() == "styleclass") { AC.setAttribute("class", AG[z]) } else { if (z.toLowerCase() != "classid") { AC.setAttribute(z, AG[z]) } } } } } for (var y in AE) { if (AE[y] != Object.prototype[y]) { if (y.toLowerCase() != "movie") { AC.setAttribute(y, AE[y]) } } } v.parentNode.replaceChild(AC, v); q = AC } else { var u = a(Q); u.setAttribute("type", P); for (var x in AG) { if (AG[x] != Object.prototype[x]) { if (x.toLowerCase() == "styleclass") { u.setAttribute("class", AG[x]) } else { if (x.toLowerCase() != "classid") { u.setAttribute(x, AG[x]) } } } } for (var w in AE) { if (AE[w] != Object.prototype[w] && w.toLowerCase() != "movie") { F(u, w, AE[w]) } } v.parentNode.replaceChild(u, v); q = u } } } return q } function F(t, q, r) { var u = a("param"); u.setAttribute("name", q); u.setAttribute("value", r); t.appendChild(u) } function X(r) { var q = C(r); if (q && (q.nodeName == "OBJECT" || q.nodeName == "EMBED")) { if (h.ie && h.win) { if (q.readyState == 4) { B(r) } else { j.attachEvent("onload", function() { B(r) }) } } else { q.parentNode.removeChild(q) } } } function B(t) { var r = C(t); if (r) { for (var q in r) { if (typeof r[q] == "function") { r[q] = null } } r.parentNode.removeChild(r) } } function C(t) { var q = null; try { q = K.getElementById(t) } catch (r) { } return q } function a(q) { return K.createElement(q) } function I(t, q, r) { t.attachEvent(q, r); d[d.length] = [t, q, r] } function c(t) { var r = h.pv, q = t.split("."); q[0] = parseInt(q[0], 10); q[1] = parseInt(q[1], 10) || 0; q[2] = parseInt(q[2], 10) || 0; return (r[0] > q[0] || (r[0] == q[0] && r[1] > q[1]) || (r[0] == q[0] && r[1] == q[1] && r[2] >= q[2])) ? true : false } function V(v, r) { if (h.ie && h.mac) { return } var u = K.getElementsByTagName("head")[0], t = a("style"); t.setAttribute("type", "text/css"); t.setAttribute("media", "screen"); if (!(h.ie && h.win) && typeof K.createTextNode != b) { t.appendChild(K.createTextNode(v + " {" + r + "}")) } u.appendChild(t); if (h.ie && h.win && typeof K.styleSheets != b && K.styleSheets.length > 0) { var q = K.styleSheets[K.styleSheets.length - 1]; if (typeof q.addRule == Q) { q.addRule(v, r) } } } function W(t, q) { var r = q ? "visible" : "hidden"; if (e && C(t)) { C(t).style.visibility = r } else { V("#" + t, "visibility:" + r) } } function g(s) { var r = /[\\\"<>\.;]/; var q = r.exec(s) != null; return q ? encodeURIComponent(s) : s } var D = function() { if (h.ie && h.win) { window.attachEvent("onunload", function() { var w = d.length; for (var v = 0; v < w; v++) { d[v][0].detachEvent(d[v][1], d[v][2]) } var t = i.length; for (var u = 0; u < t; u++) { X(i[u]) } for (var r in h) { h[r] = null } h = null; for (var q in swfobject) { swfobject[q] = null } swfobject = null }) } } (); return { registerObject: function(u, q, t) { if (!h.w3cdom || !u || !q) { return } var r = {}; r.id = u; r.swfVersion = q; r.expressInstall = t ? t : false; N[N.length] = r; W(u, false) }, getObjectById: function(v) { var q = null; if (h.w3cdom) { var t = C(v); if (t) { var u = t.getElementsByTagName(Q)[0]; if (!u || (u && typeof t.SetVariable != b)) { q = t } else { if (typeof u.SetVariable != b) { q = u } } } } return q }, embedSWF: function(x, AE, AB, AD, q, w, r, z, AC) { if (!h.w3cdom || !x || !AE || !AB || !AD || !q) { return } AB += ""; AD += ""; if (c(q)) { W(AE, false); var AA = {}; if (AC && typeof AC === Q) { for (var v in AC) { if (AC[v] != Object.prototype[v]) { AA[v] = AC[v] } } } AA.data = x; AA.width = AB; AA.height = AD; var y = {}; if (z && typeof z === Q) { for (var u in z) { if (z[u] != Object.prototype[u]) { y[u] = z[u] } } } if (r && typeof r === Q) { for (var t in r) { if (r[t] != Object.prototype[t]) { if (typeof y.flashvars != b) { y.flashvars += "&" + t + "=" + r[t] } else { y.flashvars = t + "=" + r[t] } } } } f(function() { U(AA, y, AE); if (AA.id == AE) { W(AE, true) } }) } else { if (w && !A && c("6.0.65") && (h.win || h.mac)) { A = true; W(AE, false); f(function() { var AF = {}; AF.id = AF.altContentId = AE; AF.width = AB; AF.height = AD; AF.expressInstall = w; k(AF) }) } } }, getFlashPlayerVersion: function() { return { major: h.pv[0], minor: h.pv[1], release: h.pv[2]} }, hasFlashPlayerVersion: c, createSWF: function(t, r, q) { if (h.w3cdom) { return U(t, r, q) } else { return undefined } }, removeSWF: function(q) { if (h.w3cdom) { X(q) } }, createCSS: function(r, q) { if (h.w3cdom) { V(r, q) } }, addDomLoadEvent: f, addLoadEvent: R, getQueryParamValue: function(v) { var u = K.location.search || K.location.hash; if (v == null) { return g(u) } if (u) { var t = u.substring(1).split("&"); for (var r = 0; r < t.length; r++) { if (t[r].substring(0, t[r].indexOf("=")) == v) { return g(t[r].substring((t[r].indexOf("=") + 1))) } } } return "" }, expressInstallCallback: function() { if (A && M) { var q = C(m); if (q) { q.parentNode.replaceChild(M, q); if (l) { W(l, true); if (h.ie && h.win) { M.style.display = "block" } } M = null; l = null; A = false } } } } } ();
var fbs = '';

(function($) {
    $.fn.announce = function(url, settings) {
        var me = this;
        var lastmsg = new Date();

        settings = $.extend({
            initdelay: 15,
            delay: 60,
            showfor: null,
            idledelay: 600
        }, settings);
        var timeout;

        function ajaxok(data) {
            if (data) {
                $(me).find('span.sender').text(data.Sender);
                $(me).find('div.italic').text(data.Content);
                $(me).show();
                $(me).animate({ opacity: 1 }, 500);
                if (settings.showfor !== null) {
                    timeout = window.setTimeout(hide, settings.showfor * 1000);
                }
                ibsms.ibxreread();
                lastmsg = new Date();
            }
            else {
                hide();
            }
        }

        function hide() {
            if (timeout) {
                window.clearTimeout(timeout);
                timeout = null;
            }
            $(me).animate({ opacity: 0 }, 500, null, function() { $(me).hide(); });
            var now = new Date();
            var interval = settings.delay * 1000;
            if (Math.ceil((now.getTime() - lastmsg.getTime()) / (60 * 1000)) > 30)
                interval = settings.idledelay * 1000;
            timeout = window.setTimeout(check, interval);
        }

        function check() {
            if (timeout) {
                window.clearTimeout(timeout);
                timeout = null;
            }
            var ajaxSettings = {
                dataType: 'json',
                url: url,
                error: function() { timeout = window.setTimeout(function() { check() }, settings.delay * 1000); },
                success: ajaxok
            };
            $.ajax(ajaxSettings);
        }
        return this.each(function() {
            var close = $(me).find('a.close');
            close.click(function() { hide(); return false; });
            timeout = window.setTimeout(check, settings.initdelay * 1000);
        });
    };

})(jQuery);

function closure(messages) {
    var liczba_znakow = 0; var smsy = 0; var ads = null;
    var SM_data = '', S_data = ''; var sms_len = 160; var sms_max = sms_len * 4;
    //cookie names
    var inboxid = 'inboxid';
    var lastIbxReread = 0;
    var brt; var ccphone = messages.ccphoneCookieName; var ccemail = messages.ccemailCookieName;
    var inbox = $('div#inbox');
    //var text_not_defined = "<%# resMan.GetString(text_not_defined)%>";


    var ibxinprogress = false;
    var ibxreread = function() {
        if (ibxinprogress)
            return;
        ibxinprogress = true;
        inbox.html('<div class="inboxMsgLoader"></div>');
        inbox.load('inbox.aspx?recv=yes', null, function() {
            //alert('done');
            ibxinprogress = false;
        });
        /*var zachwile = $('#div_za_chwile');
        var currDate = new Date();
        if ((currDate - lastIbxReread) < 5000) {
        zachwile.show();
        }
        else {
        zachwile.hide();
        lastIbxReread = currDate;
            
        }*/
    }
    this.ibxreread = ibxreread;

    var runnanno = function(url, settings) {
        if (GetCookie(inboxid) || GetCookie(fbs))
            $('#newmessage').announce(url, settings);
    }
    this.runnanno = runnanno;

    function getRespInfo(respinfo) {
        return '*' + respinfo + '*';
    }

    var ldbody = function(ext_ads) {
        ads = ext_ads; brt = ads[0];
    }
    this.ldbody = ldbody;

    /*function pulse(el, again) {
    if (el.p) {
    window.clearTimeout(el.p);
    el.p = null;
    };
    el.animate({ opacity: 0.1 }, 100, function() {
    $(this).animate({ opacity: 1.0 }, 100);
    });
    if (again) {
    el.p = window.setTimeout(function() { pulse(el) }, 200);
    };
    };*/

    var podgl = function () {
        if (ads == null)
            return;

        var msg = $('#SHORT_MESSAGE');
        var SM = msg.val();
        var S = $('#SENDER').val();

        var alltext, allen, writetext
        alltext = messages.from_header_js + S + ads[0] + ':';
        var tot_ads_space = alltext.length; //spoiler space
        var cnt;
        for (cnt = 1; cnt < 4; cnt++)
            tot_ads_space += ads[cnt].length + 7;
        writetext = SM; //to mamy podzielic alltext + 

        allen = writetext.length;

        if ((alltext.length + SM.length) <= sms_len)
            alltext = alltext + SM;
        else {
            var onemsg, i = 0, cutout = 0, steps = 0, ad = "";
            while ((i < allen) && (steps < 4)) {
                if (steps > 0) {
                    ad = ads[steps]
                    cutout = ad.length + 7;
                    onemsg = '\rSMS(' + (steps + 1) + '):' + writetext.substr(i, sms_len - cutout) + ad;
                }
                else {
                    cutout = alltext.length;
                    onemsg = alltext + writetext.substr(i, sms_len - cutout);
                    alltext = '';
                }
                steps = steps + 1;
                i = i + sms_len - cutout;
                alltext = alltext + onemsg;
            }
        }
        liczba_znakow = alltext.length - (steps > 0 ? steps : 1) + 1; //remove /r
        var maxlen = sms_max - tot_ads_space;
        var wiadstr;
        if ((liczba_znakow > sms_max) || (i < allen)) {
            //pulse(msg);
            msg.val(
                msg.val().substr(0, maxlen)
            );
            wiadstr = jQuery.format(messages.fsmessages, maxlen, maxlen, 4);
        }
        if (liczba_znakow <= sms_max) {            //warning = 0;
            smsy = Math.floor((liczba_znakow - 1) / sms_len) + 1;
            if (smsy == 1)
                wiadstr = jQuery.format(messages.fsmessage, msg.val().length, maxlen, smsy);
            else
                wiadstr = jQuery.format(messages.fsmessages, msg.val().length, maxlen, smsy);
        }
        $('#CHAR_COUNTER').val(wiadstr);
        SM_data = SM;
        S_data = S;
        alltext = alltext.replace(/[\[\{]/gi, '('); alltext = alltext.replace(/[\]\}]/gi, ')');
        alltext = alltext.replace(/[\\\~|\^]/gi, '.');
        $('#MESSAGE_PREV').val(alltext);

    }
    this.podgl = podgl;


    var rchecked = function() {
        var respInfo = $('#RESPINFO option:selected');
        if ($('#CHK_RESP').is(':checked')) {
            ads[0] = getRespInfo(respInfo.text());
            podgl();
        } else {
            ads[0] = brt; //restore advert
            podgl();
        }
    }
    this.rchecked = rchecked;

    function getCookieVal(offset) {
        var endstr = document.cookie.indexOf(";", offset);
        if (endstr == -1)
            endstr = document.cookie.length;
        return unescape(document.cookie.substring(offset, endstr));
    }

    var GetCookie = function(name) {
        var arg = name + "=";
        var alen = arg.length;
        var clen = document.cookie.length;
        var i = 0;
        while (i < clen) {
            var j = i + alen;
            if (document.cookie.substring(i, j) == arg)
                return getCookieVal(j);
            i = document.cookie.indexOf(" ", i) + 1;
            if (i == 0) break;
        }
        return "";
    }
    this.GetCookie = GetCookie;

    /*var setcookie = function(name, val, persist) {
    if (persist) {
    date = new Date();
    date.setFullYear(2030);
    document.cookie = name + '=' + val + '; expires=' + date.toGMTString();
    } else
    document.cookie = name + '=' + val;
    }
    this.setcookie = setcookie;*/

    var delinbox = function () {
        if (!this.isActive()) {
            window.location.href = 'default.aspx';
            return;
        }
        if (window.confirm(messages.msg_inbox_deletition_confirm)) {
            window.location.href = 'default.aspx?a=delinbox';
        }
    }
    this.delinbox = delinbox;

    var delinboxmini = function () {
        var inbox;
        inbox = GetCookie(inboxid);

        if (inbox.length == 0) {
            window.location.href = 'minisms.aspx';
            return;
        }

        if (window.confirm(messages.msg_mini_deletition_confirm)) {
            window.location.href = 'minisms.aspx?a=delinbox';
        }
    }
    this.delinboxmini = delinboxmini;

    var delinboxmini2 = function () {
        var inbox;
        inbox = GetCookie(inboxid);

        if (inbox.length == 0) {
            window.location.href = 'minisms2.aspx';
            return;
        }
        if (window.confirm(messages.msg_mini_deletition_confirm)) {
            window.location.href = 'minisms2.aspx?a=delinbox2';
        }
    }
    this.delinboxmini2 = delinboxmini2;

    function launchwnd(l_wnd, href, w, h) {
        if (l_wnd !== undefined && l_wnd !== null)
            if (!l_wnd.closed)
            l_wnd.close();

        return window.open(href + '.aspx', href, 'scrollbars=yes,status=no,toolbar=no,width=' + w + ',height=' + h);
    }

    var setsender = function(text, value, type) {
        $('#RECIPIENT').val(text.innerHTML);
        $('#RecipientValue').val(value);
        $('#RecipientType').val(type);
    }
    this.setsender = setsender;

    function newMsg(sender, content) {
        var str = sender + ':' + content;
        $('#NEWMSG_TEXT').html(str);
        $('#NEWMSG_TEXT').show('slow');

        //no popup windows
    }

    this.isActive = function() {
        return GetCookie(inboxid).length != 0;
    };
}

var ibsms = null;
function initdefault(messages, adverts) {
    ibsms = new closure(messages);
    ibsms.ldbody(adverts);
    ibsms.page = 'default';
    //install validators

    var onRecipientTypeChanged = function() {
        var val = parseInt($(this).val());

        recipient.rules('remove');
        recipient.rules('add', 'required');
        recipient.trigger('typeChanged', val);
    }

    var showerror = function(rule, el) {
        var jel = $(el);
        var errname = jel.attr('id') + rule.method;
        var msg = messages[errname];
        if (msg === undefined)
            return 'no message for ' + errname;
        else
            return jQuery.format(msg, jel.val());
    }
    var validator = null;
    $.validator.setDefaults({ messages: { catchall: showerror} });

    var sender = $('#SENDER');
    sender.attachValidator({ defaulterrmsg: messages['SENDERhelper'], container: '<div class="fleft" id="vf_{2}"><div class="fleft"></div><div class="fleft vficon {1}"></div><div class="fleft vfmsg txtSmaller txtGray singleLine {0}"></div></div>' });
    var recipient = $('#RECIPIENT');
    recipient.attachValidator({ defaulterrmsg: messages['RECIPIENThelper'] });
    var recipientType = $('#RecipientType');
    var msg = $('#SHORT_MESSAGE');
    //msg.attachValidator();
    var pass = $('#pass');
    if (pass.length > 0) {
        //pass.attachValidator({ defaulterrmsg: messages['passhelper'], container: '<div class="fright" id="vf_{2}"><div></div><div class="txtGray txtSmaller vfmsg {0}"></div>' });
        pass.attachValidator({ defaulterrmsg: messages['passhelper'], container: '' });
    }

    validator = installValidator('komunikat', null, {
        errorClass: 'jvalerror',
        errorElement: 'div',
        debug: true,
        ignore: '.valignore',
        focusInvalid: true,
        rules: {
            'RECIPIENT': {
                required: true,
                minlength: 9,
                phone: true
            },
            'SENDER':
            {
                required: true,
                nicknamerx: true
            },
            'SHORT_MESSAGE': {
                required: true
            },
            'pass': {
                required: true
            }
        },
        errorPlacement: function (error, element) {
            if (typeof element[0].jValSettings === 'undefined') {
                if (element.attr('name') == 'SHORT_MESSAGE') {
                    var msg = error.text();
                    if (msg) {
                        $('#ShortMessageTitle').hide();
                        $('#ShortMessageError').show();
                        $('#ShortMessageError').text(msg);
                    }
                    else {
                        $('#ShortMessageTitle').show();
                        $('#ShortMessageError').hide();
                    }
                }
            }
            else {
                var msg = error.text();
                if (msg)
                    element.validatedError(msg);
                else
                    element.validatedOk();
            }
        },
        success: function (label) {
        },
        submitHandler: function (form) {
            var type = parseInt(recipientType.val())
            if (type == 0 || isNaN(type)) {
                $('#RecipientValue').val(recipient.val());
            }

            form.submit();
        }
    }, null);

    recipient.live('typeChanged', function (event, value) {
        if (value == 0) {
            recipient.rules('add', {
                minlength: 9,
                phone: true
            });
        }
    });

    recipientType.change(onRecipientTypeChanged);

    //attach charcount
    msg
				.bind("keyup", ibsms.rchecked)
				.bind("focus", ibsms.rchecked)
				.bind("paste", function() {
				    setTimeout(ibsms.rchecked, 10);
				});
    if (msg[0].addEventListener) {
        msg[0].addEventListener('input', ibsms.rchecked, false);
    };
    sender
				.bind("keyup", ibsms.rchecked)
				.bind("focus", ibsms.rchecked)
				.bind("paste", function() {
				    setTimeout(ibsms.rchecked, 10);
				});
    if (msg[0].addEventListener) {
        msg[0].addEventListener('input', ibsms.rchecked, false);
    };
    ibsms.rchecked();
    $('#CHK_RESP').click(ibsms.rchecked);
    $('#RESPINFO').change(ibsms.rchecked);
    //swap preview and
    var prev = $('#MESSAGE_PREV');
    var hover = $('div.charCounter div.preview a');
    hover.mouseover(function() {
        var len = prev.val().length;
        var pcks = Math.floor(len / 160) + 1;
        if (len > 610)
            pcks + 1;
        prev.css('font-size', (13 - pcks) + 'px');
        prev.show();
        msg.hide();
    });
    hover.mouseout(function() { prev.hide(); msg.show(); });
    //msg.blur(function() { prev.show(); msg.hide(); });
    //msg.focus(function() { prev.hide(); msg.show(); });
    //prev.click(function() { prev.hide(); msg.show(); msg.focus(); });
    //validate if data exists
    if (sender.val())
        validator.element(sender);
    if (recipient.val())
    validator.element(recipient);
    if (msg.val())
        validator.element(msg);
    //recipient.filterInput(/^[\d]+$/, false);
    //recipient.focus();
    msg.filterInput(/^[^\r]*$/, false);
    //hijack cclinks
    var hijacklink = function () {
        $.cookie('SENDER', sender.val());
        $.cookie('RECIPIENT', $('#RecipientValue').val());
        $.cookie('SHORT_MESSAGE', msg.val());
        $.cookie('RecipientType', recipientType.val());
    }
    $('#ccemaila').click(hijacklink);
    $('#ccsmsa').click(hijacklink);

    $('#Send').insertAfter(pass);
}

function initsendsms(messages) {
    ibsms = new closure(messages);
    //install validators
    var showerror = function(rule, el) {
        var jel = $(el);
        var errname = jel.attr('id') + rule.method;
        var msg = messages[errname];
        if (msg === undefined)
            return 'no message for ' + errname;
        else
            return jQuery.format(msg, jel.val());
    }
    var validator = null;
    $.validator.setDefaults({ messages: { catchall: showerror} });

    var ccsms = $('#ctl00_C_ccSmsInput');
    ccsms.attachValidator({ defaulterrmsg: messages['ctl00_C_ccSmsInputhelper'], container: '<div class="fleft" id="vf_{2}"><div class="fleft"></div><div class="fleft vficon {1}"></div><div class="clearBoth vfmsg txtSmaller txtGray {0} under"></div></div>' });
    var ccemail = $('#ctl00_C_ccEmailInput');
    ccemail.attachValidator({ defaulterrmsg: messages['ctl00_C_ccEmailInputhelper'], container: '<div class="fleft" id="vf_{2}"><div class="fleft"></div><div class="fleft vficon {1}"></div><div class="clearBoth vfmsg txtSmaller txtGray {0} under"></div></div>' });

    validator = installValidator('aspnetForm', ['ctl00$C$Zapisz'], {
        errorClass: 'jvalerror',
        errorElement: 'div',
        debug: true,
        ignore: '.valignore',
        focusInvalid: true,
        rules: {
            'ctl00$C$ccEmailInput': {
                email: true
            },
            'ctl00$C$ccSmsInput':
            {
                minlength: 9,
                phone: true
            }
        },
        errorPlacement: function (error, element) {
            if (typeof element[0].jValSettings === 'undefined') {                
                    return;
            }

            var msg = error.text();
            if (msg)
                element.validatedError(msg);
            else
                element.validatedOk();
        },
        success: function (label) {
        }
    }
    );

    //validate if data exists
    /*if (ccsms.val())
    validator.element(ccsms);
    if (ccemail.val())
    validator.element(ccemail);*/
    var ccChange = $('#ctl00_C_ccChange');
    if (ccChange.length > 0) {
        ccChange = ccChange.val();
        if (ccChange == 's') {
            ccsms.select();
            ccsms.focus();
        }
        else if (ccChange == 'e') {
            ccemail.select();
            ccemail.focus();
        }
        else {
            ccemail.focus();
        }
    }
    else {
        ccemail.focus();
    }

    ccsms.filterInput(/^\d+$/, false);
}

function initinbox(messages) {
    ibsms = new closure(messages);
}

function initpossibilities(messages) {
    ibsms = new closure(messages);
}

function initminisms(messages, adverts) {
    ibsms = new closure(messages);
    ibsms.ldbody(adverts);
    //install validators
    var showerror = function(rule, el) {
        var jel = $(el);
        var errname = jel.attr('id') + rule.method;
        var msg = messages[errname];
        if (msg === undefined)
            return 'no message for ' + errname;
        else
            return jQuery.format(msg, jel.val());
    }
    var validator = null;
    $.validator.setDefaults({ messages: { catchall: showerror} });

    var sender = $('#SENDER');
    sender.attachValidator({ defaulterrmsg: messages['SENDERhelper'], container: '<div id="vf_{2}"><div></div><div class="vfmsg txtSmaller txtGray singleLine {0}"></div></div>' });
    var recipient = $('#RECIPIENT');
    recipient.attachValidator({ defaulterrmsg: messages['RECIPIENThelper'], container: '<div id="vf_{2}"><div style="padding: 0;"></div><div class="vfmsg txtSmaller txtGray singleLine {0}"></div></div>' });
    var msg = $('#SHORT_MESSAGE');
    //msg.attachValidator();
    var pass = $('#pass');
    pass.attachValidator({ defaulterrmsg: messages['passhelper'], container: '<div class="fright" id="vf_{2}"><div class="fright"></div><div class="txtGray fleft fullWidth txtSmaller vfmsg {0}"></div>' });

    var ccsms = $('#CCMSISDN');
    ccsms.attachValidator({ defaulterrmsg: messages['CCMSISDNhelper'], container: '<div class="autoOverflow" id="vf_{2}"><div ></div><div class="clearBoth vfmsg txtSmaller txtGray {0} under"></div></div>' });
    var ccemail = $('#CCEMAIL');
    ccemail.attachValidator({ defaulterrmsg: messages['CCEMAILhelper'], container: '<div class="autoOverflow" id="vf_{2}"><div ></div><div class="clearBoth vfmsg txtSmaller txtGray {0} under"></div></div>' });

    var ccsms2 = $('#CCMSISDN2');
    ccsms2.attachValidator({ defaulterrmsg: messages['CCMSISDNhelper'], container: '<div class="autoOverflow" id="vf_{2}"><div ></div><div class="clearBoth vfmsg txtSmaller txtGray {0} under"></div></div>' });
    var ccemail2 = $('#CCEMAIL2');
    ccemail2.attachValidator({ defaulterrmsg: messages['CCEMAILhelper'], container: '<div class="autoOverflow" id="vf_{2}"><div ></div><div class="clearBoth vfmsg txtSmaller txtGray {0} under"></div></div>' });
    var cc = $('#hfCC');
    cc.attachValidator({
        customvalidator: function (me, val, params) {
            if (recipient.valid() == 1 && sender.valid() == 1 && msg.valid() == 1 && pass.valid() == 1) {
                var respoption = $('#RESPOPTION');
                var ccv = $('#hfCC').val().length > 0;
                var r = (!ccv && (respoption.val() == '2' && ccsms.val().length > 0) || (respoption.val() == '1' && ccemail.val().length > 0));
                if (window.splashDisplayed == true) {
                    return true;
                }
                else if (!r) {
                    $('#splashBg').show();
                    $('#splash').show();
                    $('#splashFrame').show();
                    return false;
                }
                else {
                    return (respoption.val() == '2' && ccsms.length > 0 && ccsms.valid() == 1) || (respoption.val() == '1' && ccemail.length > 0 && ccemail.valid() == 1);
                }
            }
            else {
                return true;
            }
        }
    });
    var cc2 = $('#hfCC2');
    cc2.attachValidator({
        customvalidator: function(me, val, params) {
            var respoption2 = $('#RESPOPTION2');
            var r = (respoption2.val() == '2' && ccsms2.val().length > 0) || (respoption2.val() == '1' && ccemail2.val().length > 0);
            if (r) {
                $('#vf_CCMSISDN2 .vfmsg').show();
                $('#vf_CCEMAIL2 .vfmsg').show();
            }
            else {
                $('#vf_CCMSISDN2 .vfmsg').hide();
                $('#vf_CCEMAIL2 .vfmsg').hide();
            }
            return r;
        },
        container: '<div class="autoOverflow" id="vf_{2}"><div ></div><div class="clearBoth vfmsg txtSmaller txtGray {0} under"></div></div>'
    });

    validator = installValidator('miniSms_Form', null, {
        errorClass: 'jvalerror',
        errorElement: 'div',
        debug: true,
        ignore: '.valignore',
        focusInvalid: true,
        rules: {
            'RECIPIENT': {
                required: true,
                minlength: 9,
                phone: true
            },
            'SENDER':
            {
                required: true,
                nicknamerx: true
            },
            'SHORT_MESSAGE': {
                required: true
            },
            'pass': {
                required: true
            },
            'CCEMAIL': {
                email: true
            },
            'CCMSISDN':
            {
                minlength: 9,
                phone: true
            },
            'hfCC':
            {
                custom: true
            }
        },
        errorPlacement: function(error, element) {
            if (typeof element[0].jValSettings === 'undefined') {
                if (element.attr('name') == 'SHORT_MESSAGE') {
                    var msg = error.text();
                    if (msg) {
                        $('#ShortMessageTitle').hide();
                        $('#ShortMessageError').show();
                        $('#ShortMessageError').text(msg);
                    }
                    else {
                        $('#ShortMessageTitle').show();
                        $('#ShortMessageError').hide();
                    }
                }
            }
            else {
                var msg = error.text();
                if (msg)
                    element.validatedError(msg);
                else
                    element.validatedOk();
            }
        },
        success: function(label) {
        },
        submitHandler: function(form) {
            form.submit();
        }
    },
        null
    );

    validator = installValidator('miniSmsSplash_Form', null, {
        errorClass: 'jvalerror',
        errorElement: 'div',
        debug: true,
        ignore: '.valignore',
        focusInvalid: true,
        rules: {
            'CCMSISDN2':
            {
                minlength: 9,
                phone: true
            },
            'CCEMAIL2': {
                email: true
            },
            'hfCC2':
            {
                custom: true
            }
        },
        errorPlacement: function(error, element) {
            if (typeof element[0].jValSettings === 'undefined')
                return;

            var msg = error.text();
            if (msg)
                element.validatedError(msg);
            else
                element.validatedOk();
        },
        success: function(label) {

        },
        submitHandler: function(form) {
            $('#RESPOPTION').val($('#RESPOPTION2').val());
            $('#CCMSISDN').val($('#CCMSISDN2').val());
            $('#CCEMAIL').val($('#CCEMAIL2').val());
            ChangeReplyCC();
            closeSplash();
        }
    },
        null
    );

    //attach charcount
    msg
				.bind("keyup", ibsms.rchecked)
				.bind("focus", ibsms.rchecked)
				.bind("paste", function() {
				    setTimeout(ibsms.rchecked, 10);
				});
    if (msg[0].addEventListener) {
        msg[0].addEventListener('input', ibsms.rchecked, false);
    };
    sender
				.bind("keyup", ibsms.rchecked)
				.bind("focus", ibsms.rchecked)
				.bind("paste", function() {
				    setTimeout(ibsms.rchecked, 10);
				});

    ccsms
				.bind("keyup", ibsms.rchecked)
				.bind("focus", ibsms.rchecked)
				.bind("paste", function() {
				    setTimeout(ibsms.rchecked, 10);
				});

    if (msg[0].addEventListener) {
        msg[0].addEventListener('input', ibsms.rchecked, false);
    };
    ibsms.rchecked();
    $('#CHK_RESP').click(ibsms.rchecked);
    $('#RESPINFO').change(ibsms.rchecked);


    //validate if data exists
    if (sender.val())
        validator.element(sender);
    if (recipient.val())
        validator.element(recipient);
    if (msg.val())
        validator.element(msg);
    recipient.filterInput(/^[\d]+$/, false);
    msg.filterInput(/^[^\r^\n]*$/, false);
    ccsms.filterInput(/^[\d]+$/, false);
    //hijack cclinks
    var hijacklink = function() {
        $.cookie('SENDER', sender.val());
        $.cookie('RECIPIENT', $('#RecipientValue').val());
        $.cookie('SHORT_MESSAGE', msg.val());
        $.cookie('RecipientType', recipientType.val());
    }

    var respoption = $('#RESPOPTION');
    if (respoption) {
        respoption.val($('#hfDefCC').val());
        ChangeReplyCC();
        respoption.change(ChangeReplyCC);
    }

    var respoption2 = $('#RESPOPTION2');
    if (respoption2) {
        respoption2.val($('#hfDefCC2').val());
        ChangeReplyCC2();
        respoption2.change(ChangeReplyCC2);
    }

    var vf_pass = $('#vf_pass');
    $('#tokentext').prependTo(vf_pass);
    $('#tokenBox').prependTo(vf_pass);
    //$('#vf_CCEMAIL .vfmsg').insertAfter(vf_hfCC);
    //$('#vf_CCMSISDN .vfmsg').insertAfter(vf_hfCC);
}

function clickButton(e, buttonid) {
    var evt = e ? e : window.event;
    var bt = $('#' + buttonid);
    if (evt.keyCode == 13) {
        if (bt && bt.length > 0) {
            eval(bt[0].href.replace(/%20/g, " "));
            return false;
        }
    }
}


function ChangeReplyCC() {
    var respoption = $('#RESPOPTION');
    if (respoption) {
        var ccSelect = $('#RESPOPTION');
        var vf_CCEMAIL = $('#vf_CCEMAIL');
        var vf_CCMSISDN = $('#vf_CCMSISDN');
        var CCMSISDN = $('#CCMSISDN');
        var CCEMAIL = $('#CCEMAIL');

        if (!respoption.val()) {
            respoption.val('1');
        }

        if (respoption.val() == '1') {
            ccSelect.insertBefore($('#CCEMAIL'));
            vf_CCEMAIL.show();
            vf_CCMSISDN.hide();
        }
        else {
            ccSelect.insertBefore($('#CCMSISDN'));
            vf_CCEMAIL.hide();
            vf_CCMSISDN.show();
        }
    }
}

function ChangeReplyCC2() {
    var respoption2 = $('#RESPOPTION2');
    if (respoption2) {
        var ccSelect = $('#RESPOPTION2');
        var vf_CCEMAIL2 = $('#vf_CCEMAIL2');
        var vf_CCMSISDN2 = $('#vf_CCMSISDN2');
        var CCMSISDN2 = $('#CCMSISDN2');
        var CCEMAIL2 = $('#CCEMAIL2');

        if (!respoption2.val()) {
            respoption2.val('1');
        }

        if (respoption2.val() == '1') {
            ccSelect.insertBefore($('#CCEMAIL2'));
            vf_CCEMAIL2.show();
            vf_CCMSISDN2.hide();
            if (vf_CCMSISDN2.find('.errmsg').length > 0) {
                CCMSISDN2.val('');
            }
        }
        else {
            ccSelect.insertBefore($('#CCMSISDN2'));
            vf_CCEMAIL2.hide();
            vf_CCMSISDN2.show();
            if (vf_CCEMAIL2.find('.errmsg').length > 0) {
                CCEMAIL2.val('');
            }
        }
    }
}

function initminismssuccess(messages) {
    ibsms = new closure(messages);
}

function closeSplash() {
    $('#hfCC').val('1');
    $('#splash').hide();
    $('#splashBg').hide();
    $('#splashFrame').hide();
    window.splashDisplayed = true;
}

function closeFbHelp() {
    $('.fb-help').fadeOut('slow');
    $.cookie('fbhelp', null, { path: '/' });
}

function init() {
    if (typeof pageinit !== 'undefined') {
        pageinit();
    }

    if (ibsms)
        ibsms.runnanno('Gateway/GetLastResponse');

    $('.hover').bind("mouseenter", function() { $(this).addClass("highlight"); });
    $('.hover').bind("mouseleave", function() { $(this).removeClass("highlight"); });

    var statusMessage = $('div.statusMessageBody div.message');
    var statusIcon = $('div.statusMessageBody div.icon');
    if (statusMessage.length > 0 && statusIcon.length > 0) {
        if (statusMessage.height() > statusIcon.height()) {
            statusIcon.css('margin', (statusMessage.height() - 24) / 2 + 'px 0 0 0');
        }
        else {
            statusMessage.css('height', statusIcon.height() + 'px').css('line-height', statusIcon.height() + 'px');
        }
    }

    initStatistics();
}

function initStatistics() {
    $.getScript('http://pro.hit.gemius.pl/hmapxy.js');
    $.getScript('http://www.orange.pl/binaries/map/js/gemiusTraffic.js');

    var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
    $.getScript(gaJsHost + 'google-analytics.com/ga.js', function() {
        try {
            var dcsTracker = _gat._getTracker("UA-5559002-4");
            dcsTracker._trackPageview();

            var orangeTracker = _gat._getTracker("UA-16854473-1");
            orangeTracker._trackPageview();
        }
        catch (err) {
            err = err;
        }
    });

    $.getScript("http://gapl.hit.gemius.pl/xgemius.js");
}

jQuery.cookie = function (name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

$(document).ready(init);

