/**
 * @copyright 3 Line d.o.o.
 * @author Goran Dodig (goran.dodig@kitio.com)
 * @id $Id: w2m.js 11736 2011-04-18 10:16:02Z gorand $
 */

var defaultLanguage = "sl_SI";
//var locationHost = 'w2m.kitio.com';
//var locationHost = 'w2m.gorand.devel.3line.si';
//var locationHost = 'w2m.borutk.devel.3line.si';
var locationHost = 'w2m.ispace-current.local';

/**********************************************
 * no user serviceable parts below this line :)
 **********************************************/
//safe firebug console
var safeLog = function(msg) {
    if (window.console && typeof console.log == "function") {
      console.log(msg);
    }
};

function loadHeadFile(filename, filetype){
    if (filetype=="js"){ //if filename is a external JavaScript file
        var fileref=document.createElement('script');
        fileref.setAttribute("type","text/javascript");
        fileref.setAttribute("src", filename);
    }
    else if (filetype=="css"){ //if filename is an external CSS file
        var fileref=document.createElement("link");
        fileref.setAttribute("rel", "stylesheet");
        fileref.setAttribute("type", "text/css");
        fileref.setAttribute("href", filename);
    }
    else if (filetype=="gettext"){ //if filename is an external CSS file
        var fileref=document.createElement("link");
        fileref.setAttribute("rel", "gettext");
        fileref.setAttribute("type", "application/json");
        fileref.setAttribute("href", filename);
    }

    if (typeof fileref!="undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref);
}


function removeHeadFile(filename, filetype){
    var targetelement=(filetype=="js")? "script" : (filetype=="css" || filetype=="gettext")? "link" : "none";
    var targetattr=(filetype=="js")? "src" : (filetype=="css" || filetype=="gettext")? "href" : "none";
    var allsuspects=document.getElementsByTagName(targetelement);
    for (var i=allsuspects.length; i>=0; i--){
        if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1)
            allsuspects[i].parentNode.removeChild(allsuspects[i]);
    }
}

//safe firebug console
function safeLog(msg) {
    if (window.console && typeof console.log == "function") {
      console.log(msg);
    }
}

// include json2 lib (for browsers <= IE7)
// http://www.JSON.org/json2.js ver: 2011-02-23
var JSON;if(!JSON){JSON={}}(function(){function f(n){return n<10?"0"+n:n}if(typeof Date.prototype.toJSON!=="function"){Date.prototype.toJSON=function(key){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf()}}var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==="string"?c:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+string+'"'}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==="object"&&typeof value.toJSON==="function"){value=value.toJSON(key)}if(typeof rep==="function"){value=rep.call(holder,key,value)}switch(typeof value){case"string":return quote(value);case"number":return isFinite(value)?String(value):"null";case"boolean":case"null":return String(value);case"object":if(!value){return"null"}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==="[object Array]"){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||"null"}v=partial.length===0?"[]":gap?"[\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"]":"["+partial.join(",")+"]";gap=mind;return v}if(rep&&typeof rep==="object"){length=rep.length;for(i=0;i<length;i+=1){if(typeof rep[i]==="string"){k=rep[i];v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}else{for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}v=partial.length===0?"{}":gap?"{\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"}":"{"+partial.join(",")+"}";gap=mind;return v}}if(typeof JSON.stringify!=="function"){JSON.stringify=function(value,replacer,space){var i;gap="";indent="";if(typeof space==="number"){for(i=0;i<space;i+=1){indent+=" "}}else{if(typeof space==="string"){indent=space}}rep=replacer;if(replacer&&typeof replacer!=="function"&&(typeof replacer!=="object"||typeof replacer.length!=="number")){throw new Error("JSON.stringify")}return str("",{"":value})}}if(typeof JSON.parse!=="function"){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==="object"){for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v}else{delete value[k]}}}}return reviver.call(holder,key,value)}text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){j=eval("("+text+")");return typeof reviver==="function"?walk({"":j},""):j}throw new SyntaxError("JSON.parse")}}}());

// Gettext library
/*********** Gettext ************/
{
    Gettext = function (args) {
        this.domain         = 'messages';
        // locale_data will be populated from <link...> if not specified in args
        this.locale_data    = undefined;

        // set options
        var options = [ "domain", "locale_data" ];
        if (this.isValidObject(args)) {
            for (var i in args) {
                for (var j=0; j<options.length; j++) {
                    if (i == options[j]) {
                        // don't set it if it's null or undefined
                        if (this.isValidObject(args[i]))
                            this[i] = args[i];
                    }
                }
            }
        }


        // try to load the lang file from somewhere
        this.try_load_lang();

        return this;
    }

    Gettext.context_glue = "\004";
    Gettext._locale_data = {};

    Gettext.prototype.try_load_lang = function() {
        // check to see if language is statically included
        if (typeof(this.locale_data) != 'undefined') {
            // we're going to reformat it, and overwrite the variable
            var locale_copy = this.locale_data;
            this.locale_data = undefined;
            this.parse_locale_data(locale_copy);

            if (typeof(Gettext._locale_data[this.domain]) == 'undefined') {
                throw new Error("Error: Gettext 'locale_data' does not contain the domain '"+this.domain+"'");
            }
        }


        // try loading from JSON
        // get lang links
        var lang_link = this.get_lang_refs();

        if (typeof(lang_link) == 'object' && lang_link.length > 0) {
            // NOTE: there will be a delay here, as this is async.
            // So, any i18n calls made right after page load may not
            // get translated.
            // XXX: we may want to see if we can "fix" this behavior
            for (var i=0; i<lang_link.length; i++) {
                var link = lang_link[i];
                if (link.type == 'application/json') {
                    if (! this.try_load_lang_json(link.href) ) {
                        throw new Error("Error: Gettext 'try_load_lang_json' failed. Unable to exec xmlhttprequest for link ["+link.href+"]");
                    }
                } else if (link.type == 'application/x-po') {
                    if (! this.try_load_lang_po(link.href) ) {
                        throw new Error("Error: Gettext 'try_load_lang_po' failed. Unable to exec xmlhttprequest for link ["+link.href+"]");
                    }
                } else {
                    // TODO: implement the other types (.mo)
                    throw new Error("TODO: link type ["+link.type+"] found, and support is planned, but not implemented at this time.");
                }
            }
        }
    };

    Gettext.prototype.parse_locale_data = function(locale_data) {
        if (typeof(Gettext._locale_data) == 'undefined') {
            Gettext._locale_data = { };
        }

        // suck in every domain defined in the supplied data
        for (var domain in locale_data) {
            // skip empty specs (flexibly)
            if ((! locale_data.hasOwnProperty(domain)) || (! this.isValidObject(locale_data[domain])))
                continue;
            // skip if it has no msgid's
            var has_msgids = false;
            for (var msgid in locale_data[domain]) {
                has_msgids = true;
                break;
            }
            if (! has_msgids) continue;

            // grab shortcut to data
            var data = locale_data[domain];

            // if they specifcy a blank domain, default to "messages"
            if (domain == "") domain = "messages";
            // init the data structure
            if (! this.isValidObject(Gettext._locale_data[domain]) )
                Gettext._locale_data[domain] = { };
            if (! this.isValidObject(Gettext._locale_data[domain].head) )
                Gettext._locale_data[domain].head = { };
            if (! this.isValidObject(Gettext._locale_data[domain].msgs) )
                Gettext._locale_data[domain].msgs = { };

            for (var key in data) {
                if (key == "") {
                    var header = data[key];
                    for (var head in header) {
                        var h = head.toLowerCase();
                        Gettext._locale_data[domain].head[h] = header[head];
                    }
                } else {
                    Gettext._locale_data[domain].msgs[key] = data[key];
                }
            }
        }

        // build the plural forms function
        for (var domain in Gettext._locale_data) {
            if (this.isValidObject(Gettext._locale_data[domain].head['plural-forms']) &&
                typeof(Gettext._locale_data[domain].head.plural_func) == 'undefined') {
                // untaint data
                var plural_forms = Gettext._locale_data[domain].head['plural-forms'];
                var pf_re = new RegExp('^(\\s*nplurals\\s*=\\s*[0-9]+\\s*;\\s*plural\\s*=\\s*(?:\\s|[-\\?\\|&=!<>+*/%:;a-zA-Z0-9_\(\)])+)', 'm');
                if (pf_re.test(plural_forms)) {
                    //ex english: "Plural-Forms: nplurals=2; plural=(n != 1);\n"
                    //pf = "nplurals=2; plural=(n != 1);";
                    //ex russian: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10< =4 && (n%100<10 or n%100>=20) ? 1 : 2)
                    //pf = "nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2)";

                    var pf = Gettext._locale_data[domain].head['plural-forms'];
                    if (! /;\s*$/.test(pf)) pf = pf.concat(';');
                    /* We used to use eval, but it seems IE has issues with it.
                     * We now use "new Function", though it carries a slightly
                     * bigger performance hit.
                    var code = 'function (n) { var plural; var nplurals; '+pf+' return { "nplural" : nplurals, "plural" : (plural === true ? 1 : plural ? plural : 0) }; };';
                    Gettext._locale_data[domain].head.plural_func = eval("("+code+")");
                    */
                    var code = 'var plural; var nplurals; '+pf+' return { "nplural" : nplurals, "plural" : (plural === true ? 1 : plural ? plural : 0) };';
                    Gettext._locale_data[domain].head.plural_func = new Function("n", code);
                } else {
                    throw new Error("Syntax error in language file. Plural-Forms header is invalid ["+plural_forms+"]");
                }

            // default to english plural form
            } else if (typeof(Gettext._locale_data[domain].head.plural_func) == 'undefined') {
                Gettext._locale_data[domain].head.plural_func = function (n) {
                    var p = (n != 1) ? 1 : 0;
                    return {'nplural' : 2, 'plural' : p};
                    };
            } // else, plural_func already created
        }

        return;
    };


    // try_load_lang_po : do an ajaxy call to load in the .po lang defs
    Gettext.prototype.try_load_lang_po = function(uri) {
        var data = this.sjax(uri);
        if (! data) return;

        var domain = this.uri_basename(uri);
        var parsed = this.parse_po(data);

        var rv = {};
        // munge domain into/outof header
        if (parsed) {
            if (! parsed[""]) parsed[""] = {};
            if (! parsed[""]["domain"]) parsed[""]["domain"] = domain;
            domain = parsed[""]["domain"];
            rv[domain] = parsed;

            this.parse_locale_data(rv);
        }

        return 1;
    };

    Gettext.prototype.uri_basename = function(uri) {
        var rv;
        if (rv = uri.match(/^(.*\/)?(.*)/)) {
            var ext_strip;
            if (ext_strip = rv[2].match(/^(.*)\..+$/))
                return ext_strip[1];
            else
                return rv[2];
        } else {
            return "";
        }
    };

    Gettext.prototype.parse_po = function(data) {
        var rv = {};
        var buffer = {};
        var lastbuffer = "";
        var errors = [];
        var lines = data.split("\n");
        for (var i=0; i<lines.length; i++) {
            // chomp
            lines[i] = lines[i].replace(/(\n|\r)+$/, '');

            var match;

            // Empty line / End of an entry.
            if (/^$/.test(lines[i])) {
                if (typeof(buffer['msgid']) != 'undefined') {
                    var msg_ctxt_id = (typeof(buffer['msgctxt']) != 'undefined' &&
                                       buffer['msgctxt'].length) ?
                                      buffer['msgctxt']+Gettext.context_glue+buffer['msgid'] :
                                      buffer['msgid'];
                    var msgid_plural = (typeof(buffer['msgid_plural']) != 'undefined' &&
                                        buffer['msgid_plural'].length) ?
                                       buffer['msgid_plural'] :
                                       null;

                    // find msgstr_* translations and push them on
                    var trans = [];
                    for (var str in buffer) {
                        var match;
                        if (match = str.match(/^msgstr_(\d+)/))
                            trans[parseInt(match[1])] = buffer[str];
                    }
                    trans.unshift(msgid_plural);

                    // only add it if we've got a translation
                    // NOTE: this doesn't conform to msgfmt specs
                    if (trans.length > 1) rv[msg_ctxt_id] = trans;

                    buffer = {};
                    lastbuffer = "";
                }

            // comments
            } else if (/^#/.test(lines[i])) {
                continue;

            // msgctxt
            } else if (match = lines[i].match(/^msgctxt\s+(.*)/)) {
                lastbuffer = 'msgctxt';
                buffer[lastbuffer] = this.parse_po_dequote(match[1]);

            // msgid
            } else if (match = lines[i].match(/^msgid\s+(.*)/)) {
                lastbuffer = 'msgid';
                buffer[lastbuffer] = this.parse_po_dequote(match[1]);

            // msgid_plural
            } else if (match = lines[i].match(/^msgid_plural\s+(.*)/)) {
                lastbuffer = 'msgid_plural';
                buffer[lastbuffer] = this.parse_po_dequote(match[1]);

            // msgstr
            } else if (match = lines[i].match(/^msgstr\s+(.*)/)) {
                lastbuffer = 'msgstr_0';
                buffer[lastbuffer] = this.parse_po_dequote(match[1]);

            // msgstr[0] (treak like msgstr)
            } else if (match = lines[i].match(/^msgstr\[0\]\s+(.*)/)) {
                lastbuffer = 'msgstr_0';
                buffer[lastbuffer] = this.parse_po_dequote(match[1]);

            // msgstr[n]
            } else if (match = lines[i].match(/^msgstr\[(\d+)\]\s+(.*)/)) {
                lastbuffer = 'msgstr_'+match[1];
                buffer[lastbuffer] = this.parse_po_dequote(match[2]);

            // continued string
            } else if (/^"/.test(lines[i])) {
                buffer[lastbuffer] += this.parse_po_dequote(lines[i]);

            // something strange
            } else {
                errors.push("Strange line ["+i+"] : "+lines[i]);
            }
        }


        // handle the final entry
        if (typeof(buffer['msgid']) != 'undefined') {
            var msg_ctxt_id = (typeof(buffer['msgctxt']) != 'undefined' &&
                               buffer['msgctxt'].length) ?
                              buffer['msgctxt']+Gettext.context_glue+buffer['msgid'] :
                              buffer['msgid'];
            var msgid_plural = (typeof(buffer['msgid_plural']) != 'undefined' &&
                                buffer['msgid_plural'].length) ?
                               buffer['msgid_plural'] :
                               null;

            // find msgstr_* translations and push them on
            var trans = [];
            for (var str in buffer) {
                var match;
                if (match = str.match(/^msgstr_(\d+)/))
                    trans[parseInt(match[1])] = buffer[str];
            }
            trans.unshift(msgid_plural);

            // only add it if we've got a translation
            // NOTE: this doesn't conform to msgfmt specs
            if (trans.length > 1) rv[msg_ctxt_id] = trans;

            buffer = {};
            lastbuffer = "";
        }


        // parse out the header
        if (rv[""] && rv[""][1]) {
            var cur = {};
            var hlines = rv[""][1].split(/\\n/);
            for (var i=0; i<hlines.length; i++) {
                if (! hlines.length) continue;

                var pos = hlines[i].indexOf(':', 0);
                if (pos != -1) {
                    var key = hlines[i].substring(0, pos);
                    var val = hlines[i].substring(pos +1);
                    var keylow = key.toLowerCase();

                    if (cur[keylow] && cur[keylow].length) {
                        errors.push("SKIPPING DUPLICATE HEADER LINE: "+hlines[i]);
                    } else if (/#-#-#-#-#/.test(keylow)) {
                        errors.push("SKIPPING ERROR MARKER IN HEADER: "+hlines[i]);
                    } else {
                        // remove begining spaces if any
                        val = val.replace(/^\s+/, '');
                        cur[keylow] = val;
                    }

                } else {
                    errors.push("PROBLEM LINE IN HEADER: "+hlines[i]);
                    cur[hlines[i]] = '';
                }
            }

            // replace header string with assoc array
            rv[""] = cur;
        } else {
            rv[""] = {};
        }

        // TODO: XXX: if there are errors parsing, what do we want to do?
        // GNU Gettext silently ignores errors. So will we.
        // alert( "Errors parsing po file:\n" + errors.join("\n") );

        return rv;
    };


    Gettext.prototype.parse_po_dequote = function(str) {
        var match;
        if (match = str.match(/^"(.*)"/)) {
            str = match[1];
        }
        str = str.replace(/\\"/, "");
        return str;
    };


    // try_load_lang_json : do an ajaxy call to load in the lang defs
    Gettext.prototype.try_load_lang_json = function(uri) {
        var data = this.sjax(uri);
        if (! data) return;

        var rv = this.JSON(data);
        this.parse_locale_data(rv);

        return 1;
    };

    // this finds all <link> tags, filters out ones that match our
    // specs, and returns a list of hashes of those
    Gettext.prototype.get_lang_refs = function() {
        var langs = new Array();
        var links = document.getElementsByTagName("link");
        // find all <link> tags in dom; filter ours
        for (var i=0; i<links.length; i++) {
            if (links[i].rel == 'gettext' && links[i].href) {
                if (typeof(links[i].type) == 'undefined' ||
                    links[i].type == '') {
                    if (/\.json$/i.test(links[i].href)) {
                        links[i].type = 'application/json';
                    } else if (/\.js$/i.test(links[i].href)) {
                        links[i].type = 'application/json';
                    } else if (/\.po$/i.test(links[i].href)) {
                        links[i].type = 'application/x-po';
                    } else if (/\.mo$/i.test(links[i].href)) {
                        links[i].type = 'application/x-mo';
                    } else {
                        throw new Error("LINK tag with rel=gettext found, but the type and extension are unrecognized.");
                    }
                }

                links[i].type = links[i].type.toLowerCase();
                if (links[i].type == 'application/json') {
                    links[i].type = 'application/json';
                } else if (links[i].type == 'text/javascript') {
                    links[i].type = 'application/json';
                } else if (links[i].type == 'application/x-po') {
                    links[i].type = 'application/x-po';
                } else if (links[i].type == 'application/x-mo') {
                    links[i].type = 'application/x-mo';
                } else {
                    throw new Error("LINK tag with rel=gettext found, but the type attribute ["+links[i].type+"] is unrecognized.");
                }

                langs.push(links[i]);
            }
        }
        return langs;
    };


    Gettext.prototype.textdomain = function (domain) {
        if (domain && domain.length) this.domain = domain;
        return this.domain;
    }

    // gettext
    Gettext.prototype.gettext = function (msgid) {
        var msgctxt;
        var msgid_plural;
        var n;
        var category;
        return this.dcnpgettext(null, msgctxt, msgid, msgid_plural, n, category);
    };

    Gettext.prototype.dgettext = function (domain, msgid) {
        var msgctxt;
        var msgid_plural;
        var n;
        var category;
        return this.dcnpgettext(domain, msgctxt, msgid, msgid_plural, n, category);
    };

    Gettext.prototype.dcgettext = function (domain, msgid, category) {
        var msgctxt;
        var msgid_plural;
        var n;
        return this.dcnpgettext(domain, msgctxt, msgid, msgid_plural, n, category);
    };

    // ngettext
    Gettext.prototype.ngettext = function (msgid, msgid_plural, n) {
        var msgctxt;
        var category;
        return this.dcnpgettext(null, msgctxt, msgid, msgid_plural, n, category);
    };

    Gettext.prototype.dngettext = function (domain, msgid, msgid_plural, n) {
        var msgctxt;
        var category;
        return this.dcnpgettext(domain, msgctxt, msgid, msgid_plural, n, category);
    };

    Gettext.prototype.dcngettext = function (domain, msgid, msgid_plural, n, category) {
        var msgctxt;
        return this.dcnpgettext(domain, msgctxt, msgid, msgid_plural, n, category, category);
    };

    // pgettext
    Gettext.prototype.pgettext = function (msgctxt, msgid) {
        var msgid_plural;
        var n;
        var category;
        return this.dcnpgettext(null, msgctxt, msgid, msgid_plural, n, category);
    };

    Gettext.prototype.dpgettext = function (domain, msgctxt, msgid) {
        var msgid_plural;
        var n;
        var category;
        return this.dcnpgettext(domain, msgctxt, msgid, msgid_plural, n, category);
    };

    Gettext.prototype.dcpgettext = function (domain, msgctxt, msgid, category) {
        var msgid_plural;
        var n;
        return this.dcnpgettext(domain, msgctxt, msgid, msgid_plural, n, category);
    };

    // npgettext
    Gettext.prototype.npgettext = function (msgctxt, msgid, msgid_plural, n) {
        var category;
        return this.dcnpgettext(null, msgctxt, msgid, msgid_plural, n, category);
    };

    Gettext.prototype.dnpgettext = function (domain, msgctxt, msgid, msgid_plural, n) {
        var category;
        return this.dcnpgettext(domain, msgctxt, msgid, msgid_plural, n, category);
    };

    // this has all the options, so we use it for all of them.
    Gettext.prototype.dcnpgettext = function (domain, msgctxt, msgid, msgid_plural, n, category) {
        if (! this.isValidObject(msgid)) return '';

        var plural = this.isValidObject(msgid_plural);
        var msg_ctxt_id = this.isValidObject(msgctxt) ? msgctxt+Gettext.context_glue+msgid : msgid;

        var domainname = this.isValidObject(domain)      ? domain :
                         this.isValidObject(this.domain) ? this.domain :
                                                           'messages';

        // category is always LC_MESSAGES. We ignore all else
        var category_name = 'LC_MESSAGES';
        var category = 5;

        var locale_data = new Array();
        if (typeof(Gettext._locale_data) != 'undefined' &&
            this.isValidObject(Gettext._locale_data[domainname])) {
            locale_data.push( Gettext._locale_data[domainname] );

        } else if (typeof(Gettext._locale_data) != 'undefined') {
            // didn't find domain we're looking for. Search all of them.
            for (var dom in Gettext._locale_data) {
                locale_data.push( Gettext._locale_data[dom] );
            }
        }

        var trans = [];
        var found = false;
        var domain_used; // so we can find plural-forms if needed
        if (locale_data.length) {
            for (var i=0; i<locale_data.length; i++) {
                var locale = locale_data[i];
                if (this.isValidObject(locale.msgs[msg_ctxt_id])) {
                    // make copy of that array (cause we'll be destructive)
                    for (var j=0; j<locale.msgs[msg_ctxt_id].length; j++) {
                        trans[j] = locale.msgs[msg_ctxt_id][j];
                    }
                    trans.shift(); // throw away the msgid_plural
                    domain_used = locale;
                    found = true;
                    // only break if found translation actually has a translation.
                    if ( trans.length > 0 && trans[0].length != 0 )
                        break;
                }
            }
        }

        // default to english if we lack a match, or match has zero length
        if ( trans.length == 0 || trans[0].length == 0 ) {
            trans = [ msgid, msgid_plural ];
        }

        var translation = trans[0];
        if (plural) {
            var p;
            if (found && this.isValidObject(domain_used.head.plural_func) ) {
                var rv = domain_used.head.plural_func(n);
                if (! rv.plural) rv.plural = 0;
                if (! rv.nplural) rv.nplural = 0;
                // if plurals returned is out of bound for total plural forms
                if (rv.nplural <= rv.plural) rv.plural = 0;
                p = rv.plural;
            } else {
                p = (n != 1) ? 1 : 0;
            }
            if (this.isValidObject(trans[p]))
                translation = trans[p];
        }

        return translation;
    };

    /* utility method, since javascript lacks a printf */
    Gettext.strargs = function (str, args) {
        // make sure args is an array
        if ( null == args ||
             'undefined' == typeof(args) ) {
            args = [];
        } else if (args.constructor != Array) {
            args = [args];
        }

        // NOTE: javascript lacks support for zero length negative look-behind
        // in regex, so we must step through w/ index.
        // The perl equiv would simply be:
        //    $string =~ s/(?<!\%)\%([0-9]+)/$args[$1]/g;
        //    $string =~ s/\%\%/\%/g; # restore escaped percent signs

        var newstr = "";
        while (true) {
            var i = str.indexOf('%');
            var match_n;

            // no more found. Append whatever remains
            if (i == -1) {
                newstr += str;
                break;
            }

            // we found it, append everything up to that
            newstr += str.substr(0, i);

            // check for escpaed %%
            if (str.substr(i, 2) == '%%') {
                newstr += '%';
                str = str.substr((i+2));

            // % followed by number
            } else if ( match_n = str.substr(i).match(/^%(\d+)/) ) {
                var arg_n = parseInt(match_n[1]);
                var length_n = match_n[1].length;
                if ( arg_n > 0 && args[arg_n -1] != null && typeof(args[arg_n -1]) != 'undefined' )
                    newstr += args[arg_n -1];
                str = str.substr( (i + 1 + length_n) );

            // % followed by some other garbage - just remove the %
            } else {
                newstr += '%';
                str = str.substr((i+1));
            }
        }

        return newstr;
    }

    /* instance method wrapper of strargs */
    Gettext.prototype.strargs = function (str, args) {
        return Gettext.strargs(str, args);
    }

    /* verify that something is an array */
    Gettext.prototype.isArray = function (thisObject) {
        return this.isValidObject(thisObject) && thisObject.constructor == Array;
    };

    /* verify that an object exists and is valid */
    Gettext.prototype.isValidObject = function (thisObject) {
        if (null == thisObject) {
            return false;
        } else if ('undefined' == typeof(thisObject) ) {
            return false;
        } else {
            return true;
        }
    };

    Gettext.prototype.sjax = function (uri) {
        var xmlhttp;
        if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
        } else if (navigator.userAgent.toLowerCase().indexOf('msie 5') != -1) {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } else {
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        }

        if (! xmlhttp)
            throw new Error("Your browser doesn't do Ajax. Unable to support external language files.");

        xmlhttp.open('GET', uri, false);
        try {xmlhttp.send(null);}
        catch (e) {return;}

        // we consider status 200 and 0 as ok.
        // 0 happens when we request local file, allowing this to run on local files
        var sjax_status = xmlhttp.status;
        if (sjax_status == 200 || sjax_status == 0) {
            return xmlhttp.responseText;
        } else {
            var error = xmlhttp.statusText + " (Error " + xmlhttp.status + ")";
            if (xmlhttp.responseText.length) {
                error += "\n" + xmlhttp.responseText;
            }
            alert(error);
            return;
        }
    }

    Gettext.prototype.JSON = function (data) {
        return eval('(' + data + ')');
    }
}
/*********** END Gettext ************/

var json_locale_data = {
        "en_EN":{"Sporočilo":[null,"Message"],"":{"MIME-Version":" 1.0","POT-Creation-Date":" 2011-04-06 17:22+0200","X-Poedit-SourceCharset":" utf-8","X-Poedit-SearchPath-0":" Users/goran/Development/ZendWorkspace/ispace-current/public/scripts/w2m/v1","X-Poedit-Country":" UNITED STATES","Content-Type":" text/plain; charset=UTF-8","Language-Team":" Kitio Mobile <dev@3line.si>","PO-Revision-Date":" 2011-04-06 17:24+0100","Report-Msgid-Bugs-To":" ","Project-Id-Version":" Web2Mobile","X-Poedit-Basepath":" /","Plural-Forms":" nplurals=4; plural=(n%100==1 ? 0 : n%100==2 ? 1 : n%100==3 || n%100==4 ? 2 : 3);","Language":" ","X-Poedit-Language":" English","Last-Translator":" Goran Dodig <goran@dodig.org>","X-Poedit-KeywordsList":" trans;gettext;gettext_noop;ntrans;transf","Content-Transfer-Encoding":" 8bit"},"Vaša telefonska številka":[null,"Your telephone number"],"Strinjam se s":[null,"I agree with"],"Error fetching price, please try later!":[null,"Error fetching price, please try later!"],"na 6262":[null,"to 6262"],"Pošljite vsebino":[null,"Send content"],"link_do_pogojev":[null,"http://www.kitio.com"],"Vaše ime":[null,"Your name"],"Cena vsakokrat poslane vsebine je":[null,"Price of each delivery of new content is"],"Cena poslane vsebine je":[null,"Price of sending the video is"],"(fetching price...)":[null,"(fetching price...)"],"Za odjavo pošljite":[null,"To unsubscribe, send"],"Uspešno ste se prijavili na vsebino.":[null,"You have successfully subscribed to the content."],"Mobilni operater":[null,"Mobile operator"],"Vsebina je bila uspešno poslana.":[null,"The content has been successfully sent. "],"Potrdi":[null,"Submit"],"Vpišite PIN":[null,"Insert PIN"],"Vnesite GSM številko!":[null,"Enter the GSM number!"],"PIN":[null,"PIN"],"Telefonska številka":[null,"Telephone number"],"Prosimo izberite vašega mobilnega operaterja ter vpišite vašo telefonsko številko ter telefonsko številko prijatelja.":[null,"Please select your mobile operator and enter yours and recipients telephone number."],"fetching price...":[null,"fetching price..."],"Ponovno pošlji PIN":[null,"Send PIN again"],"Splošnimi pogoji":[null,"Terms & Conditions"],"Pošlji sebi":[null,"Send to myself"],"Strinjati se moraš s splošnimi pogoji!":[null,"You have to agree with terms & conditions."],"Vnesite vaše Ime!":[null,"Enter your name!"],"Sporočilo prijatelju":[null,"Message to the recipient"],"Pošljite video":[null,"Send video"],"Vnesi PIN, ki si ga prejel po SMSu.":[null,"Enter the PIN you received to your mobile."],"Prijateljeva telefonska številka":[null,"Recipients telephone number"],"na":[null,"to"]},
        "hr_HR":{"Telefonska številka":[null,"Vaš telefonski broj"],"PIN":[null,"PIN"],"Sporočilo":[null,"Poruka"],"":{"MIME-Version":" 1.0","POT-Creation-Date":" 2011-04-06 17:22+0200","X-Poedit-SourceCharset":" utf-8","X-Poedit-SearchPath-0":" Users/goran/Development/ZendWorkspace/ispace-current/public/scripts/w2m/v1","X-Poedit-Country":" CROATIA","Content-Type":" text/plain; charset=UTF-8","Language-Team":" Kitio Mobile <dev@3line.si>","PO-Revision-Date":" 2011-04-06 17:24+0100","Report-Msgid-Bugs-To":" ","Project-Id-Version":" Web2Mobile","X-Poedit-Basepath":" /","Plural-Forms":" nplurals=4; plural=(n%100==1 ? 0 : n%100==2 ? 1 : n%100==3 || n%100==4 ? 2 : 3);","Language":" ","X-Poedit-Language":" Croatian","Last-Translator":" Goran Dodig <goran@dodig.org>","X-Poedit-KeywordsList":" trans;gettext;gettext_noop;ntrans;transf","Content-Transfer-Encoding":" 8bit"},"Vaša telefonska številka":[null,"Vaš telefonski broj"],"Strinjam se s":[null,"Slažem se sa"],"Prosimo izberite vašega mobilnega operaterja ter vpišite vašo telefonsko številko ter telefonsko številko prijatelja.":[null,"Molimo, iz izbornika odaberite mobilnog operatera, upišite vaš telefonski broj te broj primatelja."],"Error fetching price, please try later!":[null,"Pogreška kod učitavanja cijene, molimo pokušajte kasnije!"],"na 6262":[null,"na 88302"],"Pošljite vsebino":[null,"Pošaljite odabrani sadržaj na mobilni telefon"],"Ponovno pošlji PIN":[null,"Ponovno pošalji PIN"],"fetching price...":[null,"učitavam cijenu..."],"Splošnimi pogoji":[null,"Općim uvjetima"],"link_do_pogojev":[null,"http://www.kitio.com"],"Pošlji sebi":[null,"Pošalji sebi"],"Vaše ime":[null,"Vaše ime"],"Strinjati se moraš s splošnimi pogoji!":[null,"Morate prihvatiti opće uslove upotrebe!"],"Vnesite vaše Ime!":[null,"Unesite vaše ime!"],"Cena vsakokrat poslane vsebine je":[null,"Cijena svakokratnog slanja sadržaja je"],"Cena poslane vsebine je":[null,"Cijena poslanog sadržaja je"],"(fetching price...)":[null,"(učitavam cijenu...)"],"Sporočilo prijatelju":[null,"Poruka prijatelju"],"Za odjavo pošljite":[null,"Za odjavu pošaljite"],"Vnesi PIN, ki si ga prejel po SMSu.":[null,"Unesi PIN, kojeg si dobio putem SMS-a."],"Uspešno ste se prijavili na vsebino.":[null,"Uspješno ste se prijavili na sadržaj."],"Mobilni operater":[null,"Mobilni operater"],"Vsebina je bila uspešno poslana.":[null,"Sadržaj je bio uspješno poslan."],"Potrdi":[null,"Potvrdi"],"Vpišite PIN":[null,"Upišite PIN"],"Prijateljeva telefonska številka":[null,"Telefonski broj prijatelja"],"na":[null,"na"],"Vnesite GSM številko!":[null,"Unesite GSM broj!"]},
        "sl_SI":{"Sporočilo":[null,"Sporočilo"],"":{"MIME-Version":" 1.0","POT-Creation-Date":" 2011-04-06 17:22+0200","X-Poedit-SourceCharset":" utf-8","X-Poedit-SearchPath-0":" Users/goran/Development/ZendWorkspace/ispace-current/public/scripts/w2m/v1","X-Poedit-Country":" SLOVENIA","Content-Type":" text/plain; charset=UTF-8","Language-Team":" Kitio Mobile <dev@3line.si>","PO-Revision-Date":" 2011-04-06 17:24+0100","Report-Msgid-Bugs-To":" ","Project-Id-Version":" Web2Mobile","X-Poedit-Basepath":" /","Plural-Forms":" nplurals=4; plural=(n%100==1 ? 0 : n%100==2 ? 1 : n%100==3 || n%100==4 ? 2 : 3);","Language":" ","X-Poedit-Language":" Slovenian","Last-Translator":" Goran Dodig <goran@dodig.org>","X-Poedit-KeywordsList":" trans;gettext;gettext_noop;ntrans;transf","Content-Transfer-Encoding":" 8bit"},"Vaša telefonska številka":[null,"Vaša telefonska številka"],"Strinjam se s":[null,"Strinjam se s"],"Error fetching price, please try later!":[null,"Napaka pri prebiranju cene, prosimo poskusite kasneje!"],"na 6262":[null,"na 6262"],"Pošljite vsebino":[null,"Pošljite vsebino sebi ali prijatelju"],"link_do_pogojev":[null,"http://www.kitio.si/slo/menux1.php#w2m"],"Vaše ime":[null,"Vaše ime"],"Cena vsakokrat poslane vsebine je":[null,"Cena vsakokrat poslane vsebine je"],"Cena poslane vsebine je":[null,"Cena poslane vsebine je"],"(fetching price...)":[null,"(prebiram ceno...)"],"Za odjavo pošljite":[null,"Za odjavo pošljite"],"Uspešno ste se prijavili na vsebino.":[null,"Uspešno ste se prijavili na vsebino."],"Mobilni operater":[null,"Vaš mobilni operater"],"Vsebina je bila uspešno poslana.":[null,"Vsebina je bila uspešno poslana."],"Potrdi":[null,"Potrdi"],"Vpišite PIN":[null,"Vpišite aktivacijsko kodo"],"Vnesite GSM številko!":[null,"Vnesite GSM številko!"],"PIN":[null,"Aktivacijska koda"],"Telefonska številka":[null,"Vaša telefonska številka"],"Prosimo izberite vašega mobilnega operaterja ter vpišite vašo telefonsko številko ter telefonsko številko prijatelja.":[null,"Prosimo izberite vašega mobilnega operaterja ter vpišite vašo telefonsko številko ter telefonsko številko prejemnika."],"fetching price...":[null,"prebiram ceno..."],"Ponovno pošlji PIN":[null,"Ponovno pošlji aktivacijsko kodo"],"Splošnimi pogoji":[null,"Splošnimi pogoji"],"Pošlji sebi":[null,"Pošlji sebi"],"Strinjati se moraš s splošnimi pogoji!":[null,"Strinjati se moraš s splošnimi pogoji!"],"Vnesite vaše Ime!":[null,"Vnesite vaše Ime!"],"Sporočilo prijatelju":[null,"Sporočilo prejemniku"],"Pošljite video":[null,"Pošljite video"],"Vnesi PIN, ki si ga prejel po SMSu.":[null,"Vnesite aktivacijsko kodo, ki ste jo prejeli po SMS sporočilu."],"Prijateljeva telefonska številka":[null,"Prejemnikova telefonska številka"],"na":[null,"na"]},
        "sr_RS":{"Telefonska številka":[null,""],"PIN":[null,""],"Sporočilo":[null,""],"":{"MIME-Version":" 1.0","POT-Creation-Date":" 2011-04-06 17:22+0200","X-Poedit-SourceCharset":" utf-8","X-Poedit-SearchPath-0":" Users/goran/Development/ZendWorkspace/ispace-current/public/scripts/w2m/v1","X-Poedit-Country":" YUGOSLAVIA","Content-Type":" text/plain; charset=UTF-8","Language-Team":" Kitio Mobile <dev@3line.si>","PO-Revision-Date":" 2011-03-25 17:29+0100","Report-Msgid-Bugs-To":" ","Project-Id-Version":" Web2Mobile","X-Poedit-Basepath":" /","Plural-Forms":" nplurals=4; plural=(n%100==1 ? 0 : n%100==2 ? 1 : n%100==3 || n%100==4 ? 2 : 3);","Language":" ","X-Poedit-Language":" Serbian","Last-Translator":" Goran Dodig <goran@dodig.org>","X-Poedit-KeywordsList":" trans;gettext;gettext_noop;ntrans;transf","Content-Transfer-Encoding":" 8bit"},"Vaša telefonska številka":[null,""],"Strinjam se s":[null,""],"Prosimo izberite vašega mobilnega operaterja ter vpišite vašo telefonsko številko ter telefonsko številko prijatelja.":[null,""],"Error fetching price, please try later!":[null,""],"Ponovno pošlji PIN":[null,""],"fetching price...":[null,""],"Splošnimi pogoji":[null,""],"link_do_pogojev":[null,""],"Pošlji sebi":[null,""],"Vaše ime":[null,""],"Strinjati se moraš s splošnimi pogoji!":[null,""],"Vnesite vaše Ime!":[null,""],"Cena vsakokrat poslane vsebine je":[null,""],"Cena poslane vsebine je":[null,""],"(fetching price...)":[null,""],"Sporočilo prijatelju":[null,""],"Za odjavo pošljite":[null,""],"Vnesi PIN, ki si ga prejel po SMSu.":[null,""],"Uspešno ste se prijavili na vsebino.":[null,""],"Mobilni operater":[null,""],"Vsebina je bila uspešno poslana.":[null,""],"Potrdi":[null,""],"Vpišite PIN":[null,""],"Prijateljeva telefonska številka":[null,""],"na":[null,""],"Vnesite GSM številko!":[null,""]}}

//load default locale, change language by calling web2Mobile.setLanguage(), before calling web2Mobile.init()
var gt = new Gettext({"domain" : defaultLanguage,
                      "locale_data" : json_locale_data});

// define locale helper functions
function trans(msgid){return gt.gettext(msgid);}
function transf(msgid, argArray){return gt.strargs(msgid, argArray);}
function ntrans(msgid, msgid_plural, n){return gt.ngettext(msgid, msgid_plural, n);}

var dom = {};
dom.query = jQuery;

var web2Mobile = {
    apiServer: 'http://'+ locationHost + '/w2m/js',
    apiVersion: "1.0",
    apiKey: null,
    language:defaultLanguage,
    url: null,
    encryptedRel: null,
    isEncrypted: false,
    operatorId: null,
    myMsisdn: null,
    senderName: null,
    friendMsisdn: null,
    customMessage: null,
    siteParams: null,
    tariffs: null,
    title: null,
    mobileOperators: {
        "sl_SI": {
            "1": "Mobitel",
            "2": "Simobil"
        },
        "hr_HR": {
            "11": "VIPnet",
            "12": "T-Mobile",
            "14": "Tele2"
        }
    },
    setLanguage: function(language) {
        oldLanguage = this.language;
        this.language = language;
        gt.textdomain(language);
        dom.query("#w2m-operator").html(this.getMobileOperators());
        dom.query("#w2m-subscription-operator_id").html(this.getMobileOperators());
    },
    startRestCall: function(filename) {
        filename += '/?' + Math.random(0, 1000) + '=' + Math.random(0, 1000);
        var fileref=document.createElement('script');
        fileref.setAttribute("type","text/javascript");
        fileref.setAttribute("src", filename);
        document.getElementsByTagName("head")[0].appendChild(fileref);
    },
    setApiKey: function(apiKey) {
        dom.query = jQuery; // move jQuery to new namespace
        this.apiKey = apiKey;
        var params = {
            'apiVersion': this.apiVersion,
            'apiKey': apiKey,
            'language': this.language,
            'method': 'init'
        };
        var url = this.apiServer + '/p/' + Base64.encode(JSON.stringify(params));
        this.startRestCall(url);
    },
    setNoConflictMode: function() {
        dom.query = jQuery.noConflict(true);
    },
    rebind:function() {
        // If checked - hide / show friends number
        if (dom.query("#send-to-self").is(":checked")) {
            // hide div
            dom.query("#my-name-is").hide("fast");
            dom.query("#friend-msisdn").hide("fast");
            // change description
            dom.query("#message-to-friend-label").html(trans('Sporočilo'));
        } else {
            dom.query("#my-name-is").show("fast");
            dom.query("#friend-msisdn").show("fast");
            dom.query("#message-to-friend-label").html(trans('Sporočilo prijatelju'));
        }

        dom.query("#send-to-self").click(function(){
            // If checked
            if (dom.query("#send-to-self").is(":checked")) {
                //hide div
                dom.query("#my-name-is").hide("fast");
                dom.query("#friend-msisdn").hide("fast");
                dom.query("#message-to-friend-label").html(trans('Sporočilo'));
            } else {
                dom.query("#my-name-is").show("fast");
                dom.query("#friend-msisdn").show("fast");
                dom.query("#message-to-friend-label").html(trans('Sporočilo prijatelju'));
            }
        });

        /**
         * Subscriptions
         */
        dom.query("a[rel^=w2m-subscription]").click(function(){
            var rel = dom.query(this).attr('rel');
                var patt, splitter;
                var encrypted = rel.indexOf("##!");
                if (encrypted > 0) {
                    patt = /##!/g;
                    splitter = '##!';
                    web2Mobile.isEncrypted = true;
                } else {
                    web2Mobile.isEncrypted = false;
                    patt = /##/g;
                    splitter = '##';
                }
                var result = rel.match(patt);
                var relElem = rel.split(splitter, result.length+1);
                web2Mobile.prefix = relElem[0];
                if (web2Mobile.isEncrypted) {
                    web2Mobile.encryptedRel = relElem[1];
                    web2Mobile.url = null;
                } else {
                    web2Mobile.encryptedRel = null;
                    web2Mobile.url = relElem[1];
                    if (result.length == 2) {
                        web2Mobile.title = relElem[2];
                    }
                    web2Mobile.popupMesssage = relElem[5];
                }
                // get price
                var priceUrl;
                if (web2Mobile.isEncrypted) {
                    // if the params are encrypted, send the whole ecrypted string as tariff
                    priceUrl = "http://" + locationHost + "/w2m/get-subscription-price/format/js/encrypted/true/apiKey/" + web2Mobile.apiKey + "/v/" + web2Mobile.apiVersion +  "/tariff/" + web2Mobile.encryptedRel + "/language/" + web2Mobile.language;
                } else {
                    // get default tariff from siteParams
                    priceUrl = "http://" + locationHost + "/w2m/get-subscription-price/format/js/apiKey/" + web2Mobile.apiKey + "/v/" + web2Mobile.apiVersion +  "/tariff/" + web2Mobile.siteParams.tariffId + "/language/" + web2Mobile.language + "/url/" + Base64.encode(web2Mobile.url) + "/title/" + web2Mobile.title + "/popupMessage/" + web2Mobile.popupMesssage;
                }
                w2mTmpSubscriptionPrice = null; // this get's loaded from the "priceUrl" js
                web2Mobile.startRestCall(priceUrl);

        }).colorbox({
            href:'#w2m-subscription-phone-info-container',
            inline:true,
            overlayClose: false,
            escKey: false,
            onComplete: function(){
                var priceCheckCallCounter = 0;
                var maxCalls = 10;
                // on interval check if the "web2Mobile.startRestCall(priceUrl);" has already loaded the price
                var priceIntervalId = setInterval(function() {
                    priceCheckCallCounter++;

                    if (priceCheckCallCounter > maxCalls) {
                        // after max. number of calls, give up!
                        dom.query("#w2m-subscription-phone-info-submit").val(trans("Error fetching price, please try later!"));
                        clearInterval(priceIntervalId);
                    } else {
                        if (w2mTmpSubscriptionPrice != null) {
                            dom.query("#contentPriceSubscription").html(w2mTmpSubscriptionPrice.price);
                            dom.query("#w2m-SubscriptionPopupMessage").html(w2mTmpSubscriptionPrice.popupMessage + "<br /><br />");
                            dom.query("#w2m-SubscriptionKeyword").html(w2mTmpSubscriptionPrice.keyword);
                            dom.query("#w2m-SubscriptionShortNumber").html(w2mTmpSubscriptionPrice.shortNumber);
                            // enable submition
                            dom.query("#w2m-subscription-phone-info-submit").removeAttr("disabled");
                            dom.query("#w2m-subscription-phone-info-submit").val(trans("Potrdi"));
                            dom.query("#w2m-subscription-phone-info-loader").hide();
                            clearInterval(priceIntervalId);
                        }
                    }
                    dom.query.fn.colorbox.resize();dom.query.fn.colorbox.resize();
                }, 1000);

                dom.query("#cboxTitle").hide();
                dom.query('#cboxNext').hide();
                dom.query('#cboxPrevious').hide();
                dom.query('#cboxCurrent').hide();
                dom.query('#w2m-subscription-phone-info-container').show();
                dom.query('#w2m-subscription-phone-info-container p.error').hide();
            }
        });

        dom.query('#w2m-subscription-phone-info-submit').die();
        dom.query('#w2m-subscription-phone-info-submit').live('click', function(){
            var myNumber      = dom.query('#w2m-subscription-msisdn').val();
            var terms         = dom.query('#w2m-subscription-terms').is(':checked');

            //hide error panel
            dom.query('#w2m-subscription-phone-info-container p.error').hide();

            if (!myNumber) {
                dom.query('#w2m-subscription-phone-info-container p.error').html(trans('Vnesite GSM številko!'));
                dom.query('#w2m-subscription-phone-info-container p.error').show();
                dom.query.fn.colorbox.resize();dom.query.fn.colorbox.resize();
                return false;
            }

            if (!terms) {
                dom.query('#w2m-subscription-phone-info-container p.error').html(trans('Strinjati se moraš s splošnimi pogoji!'));
                dom.query('#w2m-subscription-phone-info-container p.error').show();
                dom.query.fn.colorbox.resize();dom.query.fn.colorbox.resize();
                return false;
            }

            web2Mobile.operatorId = dom.query('#w2m-subscription-operator_id').val();
            web2Mobile.myMsisdn = myNumber;

            var params = {
                'apiVersion': web2Mobile.apiVersion,
                'apiKey': web2Mobile.apiKey,
                'language': web2Mobile.language,
                'method': 'subscribe-sendpin',
                'operatorId': web2Mobile.operatorId,
                'msisdn': myNumber
            };

            var url = web2Mobile.apiServer + '/p/' + Base64.encode(JSON.stringify(params));

            dom.query('#w2m-subscription-phone-info-container').hide();
            dom.query('#cboxLoadingGraphic').show();
            web2Mobile.startRestCall(url);
        });

        // disable accidential form submition by disabling enter key in pin entry submit
        dom.query('#w2m-subscription-pin').die();
        dom.query('#w2m-subscription-pin').live('keypress', function(e) {
            if (e.keyCode == 13) {
                return false;
            }
        });

        //w2m-subscription-insert-pin-submit
        dom.query('#w2m-subscription-insert-pin-submit').die();
        dom.query('#w2m-subscription-insert-pin-submit').live('click',function(){

            var pin = dom.query('#w2m-subscription-pin').val();

            dom.query('#w2m-subscription-insert-pin-container p.error').hide();

            if (!pin) {
                dom.query('#w2m-subscription-insert-pin-container p.error').html(trans('Vpišite PIN'));
                dom.query('#w2m-subscription-insert-pin-container p.error').show();
                dom.query.fn.colorbox.resize();dom.query.fn.colorbox.resize();
                return false;
            }

            var params = {
                'apiVersion': web2Mobile.apiVersion,
                'apiKey': web2Mobile.apiKey,
                'language': web2Mobile.language,
                'method': 'subscribe',
                'pin': pin,
                'isEncrypted': web2Mobile.isEncrypted,
                'url': web2Mobile.url,
                'uniqueHash': web2Mobile.url,
                'encryptedRel': web2Mobile.encryptedRel,
                'contentType': web2Mobile.siteParams.contentType,
                'channelTitle': web2Mobile.title,
                'operatorId': web2Mobile.operatorId,
                'msisdn': web2Mobile.myMsisdn
            };
            var url = web2Mobile.apiServer + '/p/' + Base64.encode(JSON.stringify(params));

            dom.query('#w2m-subscription-insert-pin-container').hide();
            dom.query('#cboxLoadingGraphic').show();
            web2Mobile.startRestCall(url);
        });

        /**
         * Sending Content
         */
        dom.query("a[rel^=w2m-remote]").click(function(){

            var rel = dom.query(this).attr('rel');
            var patt, splitter;
            var encrypted = rel.indexOf("##!");
            if (encrypted > 0) {
                patt = /##!/g;
                splitter = '##!';
                web2Mobile.isEncrypted = true;
            } else {
                web2Mobile.isEncrypted = false;
                patt = /##/g;
                splitter = '##';
            }

            var result = rel.match(patt);
            var relElem = rel.split(splitter, result.length+1);
            web2Mobile.prefix = relElem[0];
            if (web2Mobile.isEncrypted) {
                web2Mobile.encryptedRel = relElem[1];
                web2Mobile.url = null;
            } else {
                web2Mobile.encryptedRel = null;
                web2Mobile.url = relElem[1];
            }

            // first get the title set in rel attribute
            var title = relElem[2];
            // if it's empty, try to get it from the title attribute
            if (title == '' || title == undefined) {
                title = dom.query(this).attr('title');
            }
            // if still empty, take the documents title
            if (title == '' || title == undefined) {
                title = document.title;
            }

            // set content title in popup
            dom.query('#w2m_ContentTitle').html(' "' + title + '"');
            // set content title for processing
            web2Mobile.title = title;

            // get price
            var priceUrl;
            if (web2Mobile.isEncrypted) {
                // if the params are encrypted, send the whole ecrypted string as tariff
                priceUrl = "http://" + locationHost + "/w2m/get-price/format/js/encrypted/true/apiKey/" + web2Mobile.apiKey + "/tariff/" + web2Mobile.encryptedRel + "/language/" + web2Mobile.language;
            } else {
                // get default tariff from siteParams
                priceUrl = "http://" + locationHost + "/w2m/get-price/format/js/apiKey/" + web2Mobile.apiKey + "/tariff/" + web2Mobile.siteParams.tariffId + "/language/" + web2Mobile.language;
            }
            w2mTmpPrice = null; // this get's loaded from the "priceUrl" js
            web2Mobile.startRestCall(priceUrl);

        }).colorbox({
            href:'#w2m-phone-info-container',
            inline:true,
            overlayClose: false,
            escKey: false,
            onComplete: function(){
                var priceCheckCallCounter = 0;
                var maxCalls = 10;
                // on interval check if the "web2Mobile.startRestCall(priceUrl);" has already loaded the price
                var priceIntervalId = setInterval(function() {
                    priceCheckCallCounter++;

                    if (priceCheckCallCounter > maxCalls) {
                        // after max. number of calls, give up!
                        dom.query("#w2m-phone-info-submit").val(trans("Error fetching price, please try later!"));
                        clearInterval(priceIntervalId);
                    } else {
                        if (w2mTmpPrice != null) {
                            dom.query("#contentPrice").html(w2mTmpPrice.price);
                            // enable submition
                            dom.query("#w2m-phone-info-submit").removeAttr("disabled");
                            dom.query("#w2m-phone-info-submit").val(trans("Potrdi"));
                            dom.query("#w2m-phone-info-loader").hide();
                            clearInterval(priceIntervalId);
                        }
                    }
                    dom.query.fn.colorbox.resize();dom.query.fn.colorbox.resize();
                }, 1000);

                dom.query("#cboxTitle").hide();
                dom.query('#cboxNext').hide();
                dom.query('#cboxPrevious').hide();
                dom.query('#cboxCurrent').hide();
                dom.query('#w2m-phone-info-container').show();
                dom.query('#w2m-phone-info-container p.error').hide();
            }
        });

        dom.query('#w2m-phone-info-submit').die();
        dom.query('#w2m-phone-info-submit').live('click', function(){
            var myNumber      = dom.query('#my-w2m-msisdn').val();
            var senderName    = (dom.query("#send-to-self").is(":checked")) ?  dom.query('#my-w2m-msisdn').val() : dom.query('#my-name').val();
            var customMessage = dom.query('#message-to-friend').val();
            var friendNumber  = dom.query('#friend-w2m-msisdn').val();
            var terms         = dom.query('#w2m-terms').is(':checked');
            var sendSelf      = dom.query("#send-to-self").is(":checked");

            //hide error panel
            dom.query('#w2m-phone-info-container p.error').hide();

            if (sendSelf) {
                if (!myNumber) {
                    dom.query('#w2m-phone-info-container p.error').html(trans('Vnesite GSM številko!'));
                    dom.query('#w2m-phone-info-container p.error').show();
                    dom.query.fn.colorbox.resize();dom.query.fn.colorbox.resize();
                    return false;
                }
            } else {
                if (!myNumber || !friendNumber) {
                    dom.query('#w2m-phone-info-container p.error').html(trans('Vnesite GSM številko!'));
                    dom.query('#w2m-phone-info-container p.error').show();
                    dom.query.fn.colorbox.resize();dom.query.fn.colorbox.resize();
                    return false;
                }
            }

            if (!customMessage) {
                // if the message is empty - fill it with video title
                customMessage = dom.query('#w2m_ContentTitle').html();
            }
            if (!senderName) {
                dom.query('#w2m-phone-info-container p.error').html(trans('Vnesite vaše Ime!'));
                dom.query('#w2m-phone-info-container p.error').show();
                dom.query.fn.colorbox.resize();dom.query.fn.colorbox.resize();
                return false;
            }
            if (!terms) {
                dom.query('#w2m-phone-info-container p.error').html(trans('Strinjati se moraš s splošnimi pogoji!'));
                dom.query('#w2m-phone-info-container p.error').show();
                dom.query.fn.colorbox.resize();dom.query.fn.colorbox.resize();
                return false;
            }

            web2Mobile.operatorId = dom.query('#w2m-operator').val();
            web2Mobile.myMsisdn = myNumber;
            web2Mobile.friendMsisdn = (sendSelf) ? myNumber : friendNumber;
            web2Mobile.senderName = senderName;
            web2Mobile.customMessage = customMessage;

            var params = {
                'apiVersion': web2Mobile.apiVersion,
                'apiKey': web2Mobile.apiKey,
                'language': web2Mobile.language,
                'method': 'sendpin',
                'operatorId': web2Mobile.operatorId,
                'senderMsisdn': myNumber,
                'receiverMsisdn': web2Mobile.friendMsisdn,
                'senderName': senderName,
                'customMessage': escape(customMessage)
            };
            var url = web2Mobile.apiServer + '/p/' + Base64.encode(JSON.stringify(params));

            dom.query('#w2m-phone-info-container').hide();
            dom.query('#cboxLoadingGraphic').show();
            web2Mobile.startRestCall(url);
        });

        // disable accidential form submition by disabling enter key in pin entry submit
        dom.query('#w2m-pin').die();
            dom.query('#w2m-pin').live('keypress', function(e) {
                if (e.keyCode == 13) {
                    return false;
                }
              });

        dom.query('#w2m-insert-pin-submit').die();
            dom.query('#w2m-insert-pin-submit').live('click',function(){

                var pin = dom.query('#w2m-pin').val();

                dom.query('#w2m-insert-pin-container p.error').hide();

                if (!pin) {
                    dom.query('#w2m-insert-pin-container p.error').html(trans('Vpišite PIN'));
                    dom.query('#w2m-insert-pin-container p.error').show();
                    dom.query.fn.colorbox.resize();dom.query.fn.colorbox.resize();
                    return false;
                }

                var params = {
                    'apiVersion': web2Mobile.apiVersion,
                    'apiKey': web2Mobile.apiKey,
                    'language': web2Mobile.language,
                    'method': 'send',
                    'pin': pin,
                    'isEncrypted': web2Mobile.isEncrypted,
                    'url': web2Mobile.url,
                    'encryptedRel': web2Mobile.encryptedRel,
                    'contentType': web2Mobile.siteParams.contentType,
                    'name': web2Mobile.title,
                    'operatorId': web2Mobile.operatorId,
                    'senderMsisdn': web2Mobile.myMsisdn,
                    'receiverMsisdn': web2Mobile.friendMsisdn,
                    'senderName': web2Mobile.senderName,
                    'customMessage': escape(web2Mobile.customMessage)
                };
                var url = web2Mobile.apiServer + '/p/' + Base64.encode(JSON.stringify(params));

                dom.query('#w2m-insert-pin-container').hide();
                dom.query('#cboxLoadingGraphic').show();
                web2Mobile.startRestCall(url);
        });


        dom.query('a.w2m-send-pin-again').click(function(){
                dom.query('#w2m-phone-info-container').show();
                dom.query('#w2m-phone-info-container p.error').hide();
        }).colorbox({
            inline:true,
            href:"#w2m-phone-info-container",
            overlayClose: false,
            escKey: false,
            onComplete:function(){
                dom.query("#cboxTitle").hide();
                dom.query('#cboxNext').hide();
                dom.query('#cboxPrevious').hide();
                dom.query('#cboxCurrent').hide();
                dom.query.fn.colorbox.resize();
                dom.query.fn.colorbox.resize();
            }
        });
    },
    getMobileOperators: function() {
        var optionString = "";
        for(var operatorId in this.mobileOperators[this.language]) {
            optionString += '<option value="' + operatorId + '">' + this.mobileOperators[this.language][operatorId] + '</option>';
        }
        return optionString;
    },
    init: function() {
        // apend our popup
        var colorboxHtml = '<div style="display: none;"><div style="width: 200px;" class="w2m-container" id="w2m-phone-info-container"><form method="post" id="w2m-phone-info"><p class="instructions"><span id=\'w2m_ContentTitle\'></span></br><br/> ' + trans("Cena poslane vsebine je") + ' <span id="contentPrice">' + trans("(fetching price...)") + '</span>.<br /><br />' + trans('Prosimo izberite vašega mobilnega operaterja ter vpišite vašo telefonsko številko ter telefonsko številko prijatelja.') + '</p><table border="0"><tbody><tr><td><label for="w2m-operator">' + trans('Mobilni operater') + '</label><br><select id="w2m-operator" name="operator_id">' + this.getMobileOperators() + '</select></td></tr><tr><td class="terms"> <div class="checkbox-container"> <input type="checkbox" value="1" class="checkbox" id="send-to-self" name="send-to-self" /> </div> <label for="send-to-self">' + trans('Pošlji sebi') + '</label><br> </td> </tr><tr> <td> <label for="my-w2m-msisdn">' + trans('Vaša telefonska številka') + '</label><br> <input type="text" id="my-w2m-msisdn" name="my-w2m-msisdn" /> </td> </tr><tr id="friend-msisdn"> <td colspan="2"> <label for="friend-w2m-msisdn">' + trans('Prijateljeva telefonska številka') + '</label><br> <input type="text" id="friend-w2m-msisdn" name="friend-msisdn" /> </td> </tr><tr id="my-name-is"> <td> <label for="my-name">' + trans('Vaše ime') + '</label><br> <input type="text" id="my-name" name="my-name" /> </td> </tr><tr> <td> <label id="message-to-friend-label" for="message-to-friend">' + trans('Sporočilo prijatelju') + '</label><br> <textarea maxlength="140" id="message-to-friend" name="message-to-friend"></textarea> </td> </tr><tr> <td class="terms"> <div class="checkbox-container"> <input type="checkbox" value="1" class="checkbox" id="w2m-terms" name="terms" /> </div> <label for="w2m-terms">' + trans('Strinjam se s') + ' <a target="_blank" href="' + trans('link_do_pogojev') + '">' + trans('Splošnimi pogoji') + '</a></label> </td> </tr><tr> <td> <input type="button" value="' + trans('fetching price...') + '" class="submit" disabled="disabled" id="w2m-phone-info-submit" /><br/><img id="w2m-phone-info-loader" src="http://'+ locationHost + '/images/w2m/colorbox/loading.gif" /></td> </tr> </tbody> </table><input type="hidden" name="category_name" id="w2m-category_name" /></form> <p class="error" style="display: none;"> &nbsp; </p> </div> </div><div style="display:none;"><div class="w2m-container" id="w2m-insert-pin-container"><p class="instructions">' + trans('Vnesi PIN, ki si ga prejel po SMSu.') + '</p><form id="w2m-insert-pin" method="post"><table border="0"><tr><td><label for="w2m-pin">' + trans('PIN') + '</label><br /><input type="text" id="w2m-pin" name="pin" /></td></tr><tr><td><input type="button" id="w2m-insert-pin-submit" class="submit" value="' + trans('Potrdi') + '" />&nbsp; &nbsp;<a href="#" class="w2m-send-pin-again">' + trans('Ponovno pošlji PIN') + '</a></td></tr></table></form><p class="error">&nbsp;</p></div></div><div style="display:none;"><div id="w2m-msg" class="w2m-container"><p class="success">' + trans('Vsebina je bila uspešno poslana.') + '</p></div></div>';
        dom.query('body').append(colorboxHtml);

        var subscriptionHtml =  '<div style="display:none;"><div id="w2m-subscription-phone-info-container"><p class="subscription-instructions"></p>' + trans("Cena vsakokrat poslane vsebine je") + ' <span id="contentPriceSubscription">' + trans("(fetching price...)") + '</span>.<br /><br /> <div id="w2m-SubscriptionPopupMessage"></div> <form id="w2m-subscription-phone-info" method="post"><table cellpadding="0" cellspacing="0" border="0"><tr><td><label for="operator">' + trans("Mobilni operater") + '</label><br /><select name="w2m-subscription-operator_id" id="w2m-subscription-operator_id">' + this.getMobileOperators() + '</select></td></tr><tr><td><label for="w2m-subscription-msisdn">' + trans("Telefonska številka") + '</label><br /><input type="text" name="w2m-subscription-msisdn" id="w2m-subscription-msisdn" /></td></tr><tr><td class="terms"><div class="checkbox-container"><input type="checkbox" name="terms" id="w2m-subscription-terms" class="checkbox" /></div><label for="w2m-subscription-terms">' + trans('Strinjam se s') + ' <a target="_blank" href="' + trans('link_do_pogojev') + '">' + trans('Splošnimi pogoji') + '</a></label></td></tr><tr><td><input type="button" id="w2m-subscription-phone-info-submit" class="submit" disabled="disabled" value="' + trans('fetching price...') + '" /><br/> <img id="w2m-subscription-phone-info-loader" src="http://'+ locationHost + '/images/w2m/colorbox/loading.gif" /><br/><br/>' + trans("Za odjavo pošljite") + " <span id='w2m-SubscriptionKeyword'>...</span>" + " STOP " + trans("na") + " " + "<span id='w2m-SubscriptionShortNumber'>...</span>" + ' </td></tr></table></form><p class="error">&nbsp;</p></div></div><div style="display:none;"><div id="w2m-subscription-insert-pin-container"><p class="instructions">' + trans("Vnesi PIN, ki si ga prejel po SMSu.") + '</p><form id="insert-pin" method="post"><table cellpadding="0" cellspacing="0" border="0"><tr><td><label for="w2m-subscription-pin">' + trans('PIN') + '</label><input type="text" id="w2m-subscription-pin" name="w2m-subscription-pin" /></td></tr><tr><td><input type="button" id="w2m-subscription-insert-pin-submit" class="w2m-subscription-submit" value="' + trans('Potrdi') + '" /><a href="#" class="w2m-subscription-send-pin-again">' + trans('Ponovno pošlji PIN') + '</a></td></tr></table></form><p class="error">&nbsp;</p></div></div><div style="display:none;"><div id="w2m-subscription-msg"><p class="success">' + trans('Uspešno ste se prijavili na vsebino.') + '</p></div></div>';
        dom.query('body').append(subscriptionHtml);

        // append our banner
        if (web2Mobile.siteParams.banner != null) {
            var banner = 'http://'+ locationHost + web2Mobile.siteParams.banner;
            var insertBanner = '<img src="' + banner + '" border="0" alt="" width="200" style="margin-bottom:10px;" /><br />';
            dom.query(".instructions").before(insertBanner);
            dom.query(".subscription-instructions").before(insertBanner);
        }

        // append our custom header Text
        var customHeader = web2Mobile.siteParams.customHeaderText;
        if (customHeader.length)
            customHeader += "<br /><br />";
        dom.query(".instructions").before(customHeader);

        web2Mobile.rebind();
    }
};

/**
 * Function for adding onload event, without overriding existing onload calls
 * @param fnc Function to be added to onload
 */
function addOnloadEvent(fnc){
    if ( typeof window.addEventListener != "undefined" )
      window.addEventListener( "load", fnc, false );
    else if ( typeof window.attachEvent != "undefined" ) {
      window.attachEvent( "onload", fnc );
    }
    else {
      if ( window.onload != null ) {
        var oldOnload = window.onload;
        window.onload = function ( e ) {
          oldOnload( e );
          window[fnc]();
        };
      }
      else
        window.onload = fnc;
    }
}

/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/
var Base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            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 +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        // make url safe
        output.replace("+","-");
        output.replace("/","_");

        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        // make url safe
        output.replace("-","+");
        output.replace("_","/");

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : 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;
    }
};

