var defaultstylesheet;
var style_cookie;
var style_cookie_txt;
var style_cookie_site;
var kumod_set = false;
var quick_reply = false;
var ispage;
var lastid;
var val = 0;
var loopid;

var Utf8 = {
    encode: function (a) {
        a = a.replace(/\r\n/g, "\n");
        var b = "";
        for (var n = 0; n < a.length; n++) {
            var c = a.charCodeAt(n);
            if (c < 128) {
                b += String.fromCharCode(c)
            } else if ((c > 127) && (c < 2048)) {
                b += String.fromCharCode((c >> 6) | 192);
                b += String.fromCharCode((c & 63) | 128)
            } else {
                b += String.fromCharCode((c >> 12) | 224);
                b += String.fromCharCode(((c >> 6) & 63) | 128);
                b += String.fromCharCode((c & 63) | 128)
            }
        }
        return b
    },
    decode: function (a) {
        var b = "";
        var i = 0;
        var c = c1 = c2 = 0;
        while (i < a.length) {
            c = a.charCodeAt(i);
            if (c < 128) {
                b += String.fromCharCode(c);
                i++
            } else if ((c > 191) && (c < 224)) {
                c2 = a.charCodeAt(i + 1);
                b += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2
            } else {
                c2 = a.charCodeAt(i + 1);
                c3 = a.charCodeAt(i + 2);
                b += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3
            }
        }
        return b
    }
};

function toggle(a, b) {
    if (match = /manage/.exec(document.location.toString())) var c = 0;
    else var c = "normal";
    $('#' + b).slideToggle(c, function () {
        $(a).html($(this).is(":hidden") ? '+' : '&minus;');
        set_cookie('nav_show_' + b, $(this).is(":hidden") ? '0' : '1', 30)
    })
}
function removeframes() {
	if (match = /news.php/.exec(parent.main.window.location.toString())) {
		$('a.boardlink').attr("target", "_top");
		$("#removeframes").html("Frame rimosso.")
	} else {
		frame = $("#main", top.document);
		
		frame.css("left", (frame.width()  * .15) + "px");
		frame.animate({
			left: "0",
			"width": "100%"
		},
		1000, '', function () {
			set_cookie('frameremoved', 1, 30);
			top.document.title =  $(this).contents().find("title").html();
			$(this).contents().find(".navbar").after("<a id=\"toggleframe\"></a>");
			$(this).contents().find("#toggleframe").html("< Bring back frame").bind("click",
			function() {
				set_cookie('frameremoved', 0, 30);
				$(this).remove();
				frame = $("#main", top.document);
				frame.css("left", 0);
				frame.animate({
					left: (frame.width() * .15) + "px",
					"width": (frame.width() - frame.width() * .15) + "px"
				}, 1000, '');
			});
		});
	}
	return false
}

function reloadmain() {
    if (parent.main) {
        parent.main.location.reload()
    }
}
function replaceAll(a, b, c) {
    var d = a.indexOf(b);
    while (d > -1) {
        a = a.replace(b, c);
        d = a.indexOf(b)
    }
    return a
}
function insert(a) {
    //if (!ispage || quick_reply) {
        var b = document.forms.postform.message;
        if (b) {
            if (b.createTextRange && b.caretPos) {
                var c = b.caretPos;
                c.text = c.text.charAt(c.text.length - 1) == " " ? a + " " : a
            } else if (b.setSelectionRange) {
                var d = b.selectionStart;
                var e = b.selectionEnd;
                b.value = b.value.substr(0, d) + a + b.value.substr(e);
                b.setSelectionRange(d + a.length, d + a.length)
            } else {
                b.value += a + " "
            }
			var jumptoform = getCookie('jumptoform');
			var navigatore = getCookie('navigatore');
			if (jumptoform == '1') {
				window.location.hash = "postbox"; 
				b.focus();
			} else if (navigatore != '0') {
				$('#fake_area').show()
				$('#fakearea').focus();
			}
			
			var t=document.getElementById("fakearea");
			if(t) {
				if(t.createTextRange && t.caretPos) { // IE 
					var caretPos=t.caretPos;
					caretPos.a=caretPos.a.charAt(caretPos.a.length-1)==" "?a+" ":a;
				} else if(t.setSelectionRange) { // Firefox 
					var start=t.selectionStart;
					var end=t.selectionEnd;
					t.value=t.value.substr(0,start)+a+t.value.substr(end);
					t.setSelectionRange(start+a.length,start+a.length);
				} else {
					t.value+=a+" ";
				}
			}
			
			if(quick_reply)
				return false
        }
    //}
    return true
}
function checkhighlight() {
    var a;
    if (a = /#i([0-9]+)/.exec(document.location.toString())) if (!document.forms.postform.message.value) insert(">>" + a[1] + "\n");
    if (a = /#([0-9]+)/.exec(document.location.toString())) highlight(a[1])
}
function highlight(post, checknopage) {
    $("td.highlight").removeClass().addClass("reply");
    var reply = $("#reply" + post);
    var replytable = reply.parents("table");
    if ((reply.length || $('#postform [name=replythread]').val() == post) && replytable.parent().attr("class") != "reflinkpreview") {
        if (reply.length && reply.is(':visible')) {
            reply.removeClass();
            reply.addClass("highlight")
        }
        var match = /^([^#]*)/.exec(document.location.toString());
        document.location = match[1] + "#" + post;
        return false
    }
    return true
}
function get_password(a) {
    var b = getCookie(a);
    if (b) return b;
    var c = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    var b = '';
    for (var i = 0; i < 8; i++) {
        var d = Math.floor(Math.random() * c.length);
        b += c.substring(d, d + 1)
    }
    set_cookie(a, b, 365);
    return (b)
}
function togglePassword() {
    $("#passwordbox").html('<td class="postblock">Mod</td><td><input type="text" name="modpassword" size="28" maxlength="75">&nbsp;<acronym title="Display staff status (Mod/Admin)">D</acronym>:&nbsp;<input type="checkbox" name="displaystaffstatus" checked>&nbsp;<acronym title="Lock">L</acronym>:&nbsp;<input type="checkbox" name="lockonpost">&nbsp;&nbsp;<acronym title="Sticky">S</acronym>:&nbsp;<input type="checkbox" name="stickyonpost">&nbsp;&nbsp;<acronym title="Raw HTML">RH</acronym>:&nbsp;<input type="checkbox" name="rawhtml">&nbsp;&nbsp;<acronym title="Name">N</acronym>:&nbsp;<input type="checkbox" name="usestaffname"></td>');
    return false
}
function toggleOptions(a, b, c) {
    if ($('#opt' + a).length) {
        if (!$('#opt' + a).is(":hidden")) {
            $('#opt' + a).toggle();
            $('#opt' + a).html()
        } else {
            var d = '<td class="label"><label for="formatting">Formatting:</label></td><td colspan="3"><select name="formatting"><option value="" onclick="$(\'#formattinginfo' + a + '\').html(\'Tutta la formattazione e\' fatta dall\'utente\');">Normal</option><option value="aa" onclick="$(\'#formattinginfo' + a + '\').html(\'[aa] e [/aa] includeranno il tuo messaggio\');"';
            if (getCookie('kuformatting') == 'aa') {
                d += ' selected'
            }
            d += '>Text Art</option></select> <input type="checkbox" name="rememberformatting"><label for="rememberformatting">Remember</label> <span id="formattinginfo' + a + '">';
            if (getCookie('kuformatting') == 'aa') {
                d += '[aa] and [/aa] will surround your message.'
            } else {
                d += 'All formatting is performed by the user.'
            }
            d += '</span></td><td><input type="button" value="Preview" class="submit" onclick="javascript:postpreview(\'preview' + a + '\', \'' + c + '\', \'' + a + '\', document.' + b + '.message.value);"></td>';
            $('#opt' + a).html(d);
            $('#opt' + a).toggle()
        }
    }
}
function getCookie(a) {
    with(document.cookie) {
        var b = new RegExp("(^|;\\s+)" + a + "=(.*?)(;|$)");
        var c = b.exec(document.cookie);
        if (c && c.length > 2) return Utf8.decode(unescape(replaceAll(c[2], '+', '%20')));
        else return ''
    }
}
function set_cookie(a, b, c) {
    if (c) {
        var d = new Date();
        d.setTime(d.getTime() + (c * 24 * 60 * 60 * 1000));
        var e = "; expires=" + d.toGMTString()
    } else e = "";
    document.cookie = a + "=" + b + e + "; path=/"
}
function del_cookie(a) {
    document.cookie = a + '=; expires=Thu, 01-Jan-70 00:00:01 GMT; path=/'
}
function set_cookiestyle(styletitle, txt, site) {
	if (txt) {
		set_cookie("kustyle_txt",styletitle,365);
	} else if (site) {
		set_cookie("kustyle_site",styletitle,365);
	} else {
		set_cookie("kustyle",styletitle,365);
	}
}


function set_stylesheet(styletitle, asd) {
	if (styletitle != 'undefined' && styletitle != '') {
		$('#stylesheet').attr('href',ku_boardspath + '/css/' + styletitle.toLowerCase() + '.css');
		set_cookiestyle(styletitle, asd, false);
	}
}
function delandbanlinks(c) {
    if (!kumod_set) return;
    if (!c) {
        togglePassword();
        var d = $("#fileonly");
        d.length && d.parent().html('[<input type="checkbox" name="fileonly" id="fileonly" value="on" /><label for="fileonly">File Only</label>] <input name="moddelete" onclick="return confirm(\'Sei sicuro di voler cancellare questi post?\')" value="Cancella" type="submit" /> <input name="modban" value="Ban" onclick="this.form.action=\'' + ku_cgipath + '/manage_page.php?action=bans\';" type="submit" />')
    }
    var e;
	/*if (ku_board != 'p') {
		var f = $("span[id^='dnb']", c).each(function (i) {
			dnbinfo = $(this).attr("id").split('-');
			$.get(ku_boardspath + "/manage_page.php?action=getip&boarddir=" + dnbinfo[1] + "&id=" + dnbinfo[2], {},
			function (a, b) {
				ipaddr = a.split("=") || "what are you doing get out you don't even fit";
				$("#" + ipaddr[0]).prepend("[<img src=\"http://www.diochan.com/images/plainflags/"+ipaddr[2]+".png\" /> IP: " + ipaddr[1] + " <a href=\"" + ku_boardspath + "/manage_page.php?action=deletepostsbyip&ip=" + ipaddr[1] + "\" title=\"Cancella tutti i post di questo IP\">D</a> / <a href=\"" + ku_boardspath + "/manage_page.php?action=ipsearch&ip=" + ipaddr[1] + "\" title=\"Cerca tutti i post di questo IP\">S</a>] ")
			});
			var j = (dnbinfo[3] == 'y') ? 'thread' : 'post';
			e = '&#91;<a href="' + ku_cgipath + '/manage_page.php?action=delposts&boarddir=' + dnbinfo[1] + '&del' +
			j+'id=' + dnbinfo[2] + '" title="Cancella" onclick="return confirm(\'Sei sicuro di voler cancellare questo post/thread?\');">D<\/a>&nbsp;<a href="' + ku_cgipath + '/manage_page.php?action=delposts&boarddir=' + dnbinfo[1] + '&del'+
			j+'id=' + dnbinfo[2] + '&postid=' + dnbinfo[2] + '" title="Cancella & Banna" onclick="return confirm(\'Sei sicuro di voler cancellare e bannare chi ha scritto questo post/thread?\');">&amp;<\/a>'+
			'(<a href="' + ku_cgipath + '/manage_page.php?action=deletepostsbyipinthread&id=' + dnbinfo[2] + '&board=' + dnbinfo[1] + '" title="Cancella tutti post per IP in questo thread">T</a>)'+
			'<a href="' + ku_cgipath + '/manage_page.php?action=bans&banboard=' + dnbinfo[1] + '&banpost=' + dnbinfo[2] + '" title="Ban">B<\/a>&#93;&nbsp;&#91;<a href="' + ku_cgipath + '/manage_page.php?action=bans&banboard=' + dnbinfo[1] + '&banpost=' + dnbinfo[2] + '&instant=y" title="Permaban istantaneo" onclick="instantban(\'' + dnbinfo[1] + '\',' + dnbinfo[2] + '); return false;">P<\/a>&#93;&nbsp;&#91;<a href="' + ku_cgipath + '/manage_page.php?action=delposts&boarddir=' + dnbinfo[1] + '&del'+
			j+'id=' + dnbinfo[2] + '&postid=' + dnbinfo[2] + '&cp=y" title="Child Pornography" onclick="return confirm(\'Sei sicuro che questa sia pedopornografia?\');">CP<\/a>&#93;';
			$(this).html(e)
		})
	} else {*/
		var g = '';
		var f = $("span[id^='dnb']", c).each(function (i) {
			dnbinfo = $(this).attr("id").split('-');
			var j = (dnbinfo[3] == 'y') ? 'thread' : 'post';
			e = '&#91;<a href="' + ku_cgipath + '/manage_page.php?action=delposts&boarddir=' + dnbinfo[1] + '&del' +
			j+'id=' + dnbinfo[2] + '" title="Cancella" onclick="return confirm(\'Sei sicuro di voler cancellare questo post/thread?\');">D<\/a>&nbsp;<a href="' + ku_cgipath + '/manage_page.php?action=delposts&boarddir=' + dnbinfo[1] + '&del'+
			j+'id=' + dnbinfo[2] + '&postid=' + dnbinfo[2] + '" title="Cancella & Banna" onclick="return confirm(\'Sei sicuro di voler cancellare e bannare chi ha scritto questo post/thread?\');">&amp;<\/a>'+
			'(<a href="' + ku_cgipath + '/manage_page.php?action=deletepostsbyipinthread&id=' + dnbinfo[2] + '&board=' + dnbinfo[1] + '" title="Cancella tutti post per IP in questo thread">T</a>)'+
			'<a href="' + ku_cgipath + '/manage_page.php?action=bans&banboard=' + dnbinfo[1] + '&banpost=' + dnbinfo[2] + '" title="Ban">B<\/a>&#93;&nbsp;&#91;<a href="' + ku_cgipath + '/manage_page.php?action=bans&banboard=' + dnbinfo[1] + '&banpost=' + dnbinfo[2] + '&instant=y" title="Permaban istantaneo" onclick="instantban(\'' + dnbinfo[1] + '\',' + dnbinfo[2] + '); return false;">P<\/a>&#93;&nbsp;&#91;<a href="' + ku_cgipath + '/manage_page.php?action=delposts&boarddir=' + dnbinfo[1] + '&del'+
			j+'id=' + dnbinfo[2] + '&postid=' + dnbinfo[2] + '&cp=y" title="Child Pornography" onclick="return confirm(\'Sei sicuro che questa sia pedopornografia?\');">CP<\/a>&#93;';
			$(this).html(e)
			g = g+','+dnbinfo[2];
		})
		$.getJSON(ku_boardspath + "/manage_page.php?action=newgetip&boarddir=" + ku_board + "&ids=" + g,
		function (data) {
			$.each(data, function(i,item){
				$("#" + item.guid).prepend("[<img src=\"http://www.diochan.com/images/plainflags/"+item.flag+".png\" /> IP: " + item.ip + " <a href=\"" + ku_boardspath + "/manage_page.php?action=deletepostsbyip&ip=" + item.ip + "\" title=\"Cancella tutti i post di questo IP\">D</a> / <a href=\"" + ku_boardspath + "/manage_page.php?action=ipsearch&ip=" + item.ip + "\" title=\"Cerca tutti i post di questo IP\">S</a>] ")
			});
			return false;
		});
	// }
}
function instantban(c, d) {
    var e = prompt('Sei sicuro di voler bannare permanentemente l\'autore di questo post/thread?\nSe sei sicuro inserisci un messaggio di ban o clicka OK per usare il motivo default. Per cancellare questa operazione premi "Cancel"');
    if (typeof e === 'string') {
        var f = ku_cgipath + '/manage_page.php?action=bans&banboard=' + c + '&banpost=' + d + '&instant=y';
        if (e != '') {
            f += '&reason=' + e
        }
        $.get(f, {},
        function (a, b) {
            if (a == "success") alert("Ban inserito correttamente");
            else alert("Ban non riusito");
            if (b != "success") alert("Ban non riuscito")
        })
    } else {
        alert("Nessuna azione intrapresa")
    }
}
function togglethread(a) {
    if (hiddenthreads.toString().indexOf(a) !== -1) {
        $('#unhidethread' + a).toggle();
        $('#thread' + a).toggle("thread");
        hiddenthreads.splice(hiddenthreads.indexOf(a), 1);
        set_cookie('hiddenthreads', hiddenthreads.join('!'), 30)
    } else {
        $('#thread' + a).toggle();
        $('#unhidethread' + a).toggle();
        hiddenthreads.push(a);
        set_cookie('hiddenthreads', hiddenthreads.join('!'), 30)
    }
    return false
}
function toggleblotter(a) {
    $(".blotterentry").slideToggle("normal", function () {
        if (a) {
            set_cookie('ku_showblotter', $(this).is(":hidden") ? '0' : '1', 365)
        }
    })
}
function expandthread(c, d) {
	var e = $("#replies" + c + d);
    if (e.length) {
        e.prepend("Sto espandendo il thread...<br /><br />");
		if (d == 'aster') {
		e.load(ku_boardspath + '/expand.php?board=*&threadid=' + c, {},
        function (a, b) {
            if (!a) {
                e.html("Qualcosa e' andato storto (nessuna risposta)")
            }
            if (b == "error") {
                alert('Qualcosa e\' andato storto')
            }
            delandbanlinks(this);
            addpreviewevents(this)
        })
		} else {
        e.load(ku_boardspath + '/expand.php?board=' + d + '&threadid=' + c, {},
        function (a, b) {
            if (!a) {
                e.html("Qualcosa e' andato storto (nessuna risposta)")
            }
            if (b == "error") {
                alert('Qualcosa e\' andato storto')
            }
            delandbanlinks(this);
            addpreviewevents(this)
        })
		}
    }
    return false
}

function checkstylesheet() {
	 if(style_cookie) {
		 var cookie = getCookie(style_cookie);
		 var title=cookie ? cookie : defaultstylesheet;
		 set_cookiestyle(title);		 
		 set_stylesheet(title, false);
	 }

	if(style_cookie_txt) {
		var cookie = getCookie(style_cookie_txt);
		var title = cookie ? cookie : defaultstylesheet;
		set_cookiestyle(title, true);		
		set_stylesheet(title, true);
	}

	if(style_cookie_site) {
		var cookie = getCookie(style_cookie_site);
		var title = cookie ? cookie : defaultstylesheet;
		set_cookiestyle(title, false, true);
		set_stylesheet(title, false);		
	}
}

function quickreply(a) {
    if (a == 0) {
        quick_reply = false;
        $('#posttypeindicator').html('nuovo thread');
		$('[name=quickreply]').val('0');
    } else {
        quick_reply = true;
        $('#posttypeindicator').html('risposta a ' + a + ' [<a href="#postbox" onclick="javascript:quickreply(\'0\');" title="Cancella">x</a>]');
		$('[name=quickreply]').val('1');
    }
	var jumptoform = getCookie('jumptoform');
	var navigatore = getCookie('navigatore');
	if (jumptoform == '1') {
		window.location.hash = "postbox"; 
		$('#postform_comment').focus();
	} else if (navigatore != '0') {
		$('#fake_area').show()
		$('#fakearea').focus();
	}
    $('#postform [name=replythread]').val(a)
	return true;
}
function startPostSpyTimeout(a, b, c) {
    var d = getCookie('postspy');
    if (d == '1') {
        if ($('#thread' + a + b).length) {
            lastid = c;
            setTimeout('postSpy(' + a + ', "' + b + '");', 10000)
        }
    }
}
function postSpy(d, e) {
    var threadblock = $("#thread" + d + e);
    if (threadblock.length) {
        $.get(ku_boardspath + '/expand.php?board=' + e + '&threadid=' + d + '&pastid=' + lastid, {},
        function (response, b) {
            if (b != "success") {
                alert('Qualcosa e\' andato storto')
            } else {
				
                var response_split = response.split('|');
                newlastid = response_split[0];
                if (newlastid != '') {
                    response = response.substr((newlastid.length + 1));
                    oldpost = $("#spy" + lastid);
                    if (!oldpost.length) {
                        oldpost = threadblock.children("table:last")
                    }
                    if (!oldpost.length) {
                        oldpost = threadblock
                    }
					
                    $("#thread" + d + e).append($("<div id=\"spy" + newlastid + "\">" + response).hide());
					
                    lastid = newlastid;
                    newpost = $("#spy" + lastid);
                    newpost.slideToggle("normal");
					
					
					
                    addpreviewevents(newpost);
                    delandbanlinks(newpost)
                }
                setTimeout('postSpy(' + d + ', "' + e + '");', 5000)
            }
        })
    }
}
function getwatchedthreads(c, d) {
    var e = $("#watchedthreadlist");
    if (e.length) {
        e.html("Sto caricando i thread guardati");
        e.load(ku_boardspath + '/threadwatch.php?board=' + d + '&threadid=' + c, {},
        function (a, b) {
            if (!a) {
                e.html("Qualcosa e' andato storto (nessuna risposta)")
            }
            if (b == "error") {
                alert('Qualcosa e\' andato storto')
            }
            $("#watchedthreads").css("min-height", ($("#watchedthreadlist").attr('offsetHeight') + $("#watchedthreadsdraghandle").attr('offsetHeight') + $("#watchedthreadsbuttons").attr('offsetHeight')))
        })
    }
}
function addtowatchedthreads(c, d) {
    var e = $("#watchedthreadlist");
    if (e.length) {
        $.get(ku_boardspath + '/threadwatch.php?do=addthread&board=' + d + '&threadid=' + c, {},
        function (a, b) {
            if (b == "success") {
                alert("Thread correttamente aggiunto alla tua lista di thread guardati");
                getwatchedthreads('0', d)
            } else {
                alert('Qualcosa e\' andato storto')
            }
        })
    }
}
function removefromwatchedthreads(c, d) {
    var e = $("#watchedthreadlist");
    if (e.length) {
        $.get(ku_boardspath + '/threadwatch.php?do=removethread&board=' + d + '&threadid=' + c, {},
        function (a, b) {
            if (b == "success") {
                getwatchedthreads('0', d)
            } else {
                alert('Qualcosa e\' andato storto')
            }
        })
    }
}
function hidewatchedthreads() {
    set_cookie('showwatchedthreads', '0', 30);
    $("#watchedthreads").fadeOut("slow", function () {
        $(this).remove()
    })
}
function showwatchedthreads() {
    set_cookie('showwatchedthreads', '1', 30);
    window.location.reload(true)
}
function togglePostSpy() {
    var a = getCookie('postspy');
    if (a == '1') {
        set_cookie('postspy', '0', 30);
        alert('Post Spy disabilitato. Tutte le pagine caricate da ora in avanti non utilizzeranno questa funzione.')
    } else {
        set_cookie('postspy', '1', 30);
        alert('Post Spy abilitato. Tutte le pagine caricate da ora in avanti utilizzeranno questa funzione.')
    }
}
function checkcaptcha(a) {
    if ($("#" + a + " [name=captcha]").length && $("#" + a + " [name=captcha]").val() == '') {
        alert('Please enter the captcha image text.');
        $("#" + a + " [name=captcha]").focus();
        return false
    }
    return true
}
function expandimg(a, b, c, d, e, f, g) {
    var h = $("#thumb" + a + " img:first-child");
    var i = $("#thumb" + a);
    if (h.attr("src") == c) {
        i.html('<img src="' + b + '" alt="' + a + '" class="' + h.attr("class") + '" height="' + e + '" width="' + d + '">')
    } else if (h.attr("src") == b) {
        i.html('<img src="' + c + '" alt="' + a + '" class="' + h.attr("class") + '" height="' + g + '" width="' + f + '">')
    }
}
function postpreview(c, d, e, f) {
    var g = $("#" + c);
    if (g.length) {
        g.load(ku_boardspath + '/expand.php?preview&board=' + d + '&thread=' + e + '&message=' + escape(f), {},
        function (a, b) {
            if (!a) {
                g.html("Qualcosa e\' andato storto (nessuna risposta)")
            }
        })
    }
}
function set_inputs(a) {
    if ($("#" + a).length) {
        if (!$('#' + a + ' [name=name]').val()) $('#' + a + ' [name=name]').val(getCookie("name"));
        if (!$('#' + a + ' [name=em]').val()) $('#' + a + ' [name=em]').val(getCookie("email"));
        if (!$('#' + a + ' [name=postpassword]').val()) $('#' + a + ' [name=postpassword]').val(get_password("postpassword"))
    }
}
function set_delpass(a) {
    if ($("#" + a).length) {
        if (!$('#' + a + ' [name=postpassword]').val()) $('#' + a + ' [name=postpassword]').val(get_password("postpassword"))
    }
}
function addpreviewevents(g) {
	var d;
    $("a[class^='ref|']", g).mouseenter(function (e) {
        var c = $(this).attr("class").split('|');
        d = $("<div></div>").addClass('reflinkpreview').attr({
            id: "preview" + $(this).attr("class"),
            style: "left:" + (e.pageX + 50) + "px;display:none;overflow:auto"
        });
        if ($('#postform [name=board]').val() == c[1] && $('#reply' + c[3]).length && (($('#thumb' + c[3]).length && $('#thumb' + c[3] + " img:first-child").attr("src").lastIndexOf("thumb") != -1) || !$('#thumb' + c[3]).length)) {
            var f = true;
            d.html($("#reply" + c[3]).parents("table").html())
        } else {
            $.get(ku_boardspath + '/read.php?b=' + c[1] + '&t=' + c[2] + '&p=' + c[3] + '&single', {},
            function (a, b) {
                if (b != "success") {
                    alert('wat')
                } else { if (a) {
                        d.html(a).toggle()
                    } else {
                        d.html("Qualcosa e' andato storto (nessuna risposta)").toggle()
                    }
                }
            })
        }
        d.insertBefore($(this));
        if (f) d.toggle()
    }).mouseleave(function () {
		/*var a = $("div [id='preview" + asd + "']");
        if (a.length) {
            a.remove();
        }*/
		d.remove();
    }).click(function () {
        var a = $(this).attr("class").split('|');
        return highlight(a[3], true)
    })
}
$(document).ready(function () {
	if ($("#main", top.document).length) {
		if( $.browser.opera  && $("base").length) {
		}
		if (getCookie("frameremoved") == 1) {
			top.document.title =  $(this).contents().find("title").html();
			$(this).contents().find(".navbar").after("<a id=\"toggleframe\"></a>");
			$(this).contents().find("#toggleframe").html("< Bring back frame").bind("click",
			function() {
				set_cookie('frameremoved', 0, 30);
				$(this).remove();
				frame = $("#main", top.document);
				frame.css("left", 0);
				frame.animate({
					left: (frame.width() * .15) + "px",
					"width": (frame.width() - frame.width() * .15) + "px"
				}, 1000, '');
			});
		}
	}
    if (getCookie("kumod") == "allboards") {
        kumod_set = true
    } else if (getCookie("kumod") != "") {
        var h = getCookie("kumod").split('|');
        var i = $("#postform [name=board]").val();
        for (var j in h) {
            if (h[j] == i) {
                kumod_set = true;
                break
            }
        }
    }
    delandbanlinks();
    addpreviewevents();
    checkhighlight();
    if ($('#watchedthreads').length) {
        $('#watchedthreads').draggable({
            handle: '#watchedthreadsdraghandle',
            opacity: 0.7,
            stop: function () {
                set_cookie('watchedthreadstop', $(this).css('top'), 30);
                set_cookie('watchedthreadsleft', $(this).css('left'), 30)
            }
        });
        $('#watchedthreads').resizable({
            minHeight: ($("#watchedthreadlist").attr('offsetHeight') + $("#watchedthreadsdraghandle").attr('offsetHeight') + $("#watchedthreadsbuttons").attr('offsetHeight')),
            stop: function () {
                set_cookie('watchedthreadswidth', $(this).width(), 30);
                set_cookie('watchedthreadsheight', $(this).height(), 30)
            }
        })
    }
	
    $(this).keydown(function (e) {
        if (e.altKey) {
            var a = document.location.toString();
            if ((a.indexOf('catalog.html') == -1 && a.indexOf('/res/') == -1) || (a.indexOf('catalog.html') == -1 && e.keyCode == 80)) {
                if (e.keyCode != 18 && e.keyCode != 16) {
                    if (a.indexOf('.html') == -1 || a.indexOf('board.html') != -1) {
                        var b = 0;
                        var c = a.substr(0, a.lastIndexOf('/') + 1)
                    } else {
                        var b = a.substr((a.lastIndexOf('/') + 1));
                        b = (+b.substr(0, b.indexOf('.html')));
                        var c = a.substr(0, a.lastIndexOf('/') + 1)
                    }
                    if (b == 0) {
                        var d = c
                    } else {
                        var d = c + b + '.html'
                    }
					
					var speciali = getCookie('funzspec');
					if(speciali == '1') {
						if (e.keyCode == 222 || e.keyCode == 221) {
							if (match = /#s([0-9])/.exec(a)) {
								var f = (+match[1])
							} else {
								var f = -1
							}
							if (e.keyCode == 222) {
								if (f == -1 || f == 9) {
									var g = 0
								} else {
									var g = f + 1
								}
							} else if (e.keyCode == 221) {
								if (f == -1 || f == 0) {
									var g = 9
								} else {
									var g = f - 1
								}
							}
							document.location.href = d + '#s' + g
						} else if (e.keyCode == 59 || e.keyCode == 219) {
							if (e.keyCode == 59) {
								b = b + 1
							} else if (e.keyCode == 219) {
								if (b >= 1) {
									b = b - 1
								}
							}
							if (b == 0) {
								document.location.href = c
							} else {
								document.location.href = c + b + '.html'
							}
						} else if (e.keyCode == 80) {
							document.location.href = d + '#postbox'
						}
					}
                }
            }
        }
    });
});
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf(" chrome/") >= 0 || ua.indexOf(" firefox/") >= 0 || ua.indexOf(' gecko/') >= 0) {
	var StringMaker = function () {
		this.str = "";
		this.length = 0;
		this.append = function (s) {
			this.str += s;
			this.length += s.length;
		}
		this.prepend = function (s) {
			this.str = s + this.str;
			this.length += s.length;
		}
		this.toString = function () {
			return this.str;
		}
	}
} else {
	var StringMaker = function () {
		this.parts = [];
		this.length = 0;
		this.append = function (s) {
			this.parts.push(s);
			this.length += s.length;
		}
		this.prepend = function (s) {
			this.parts.unshift(s);
			this.length += s.length;
		}
		this.toString = function () {
			return this.parts.join('');
		}
	}
}
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
function decode64(input) {
	var output = new StringMaker();
	var chr1, chr2, chr3;
	var enc1, enc2, enc3, enc4;
	var i = 0;

	// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
	input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

	while (i < input.length) {
		enc1 = keyStr.indexOf(input.charAt(i++));
		enc2 = keyStr.indexOf(input.charAt(i++));
		enc3 = keyStr.indexOf(input.charAt(i++));
		enc4 = keyStr.indexOf(input.charAt(i++));

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

		output.append(String.fromCharCode(chr1));

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

	return output.toString();
}
function pausecomp(millis)
{
var date = new Date();
var curDate = null;

do { curDate = new Date(); }
while(curDate-date < millis);
} function validatepost() {
	if ($('#recaptcha_response_field').length) {
		$.get('/inc/func/token.php', function(data) {
			$('[name=token]').val(data);
		});
	}
	
	//lol fart
	var sound = document.getElementById("mysound");
	sound.Play();
	
	re = /(>>)/;
	if (!re.test(document.postform.message.value))
		$('[name=quote]').val('0');
	re = /(http\:\/\/)/;
	if (!re.test(document.postform.message.value))
		$('[name=link]').val('0');
	re = /(>)/;
	if (!re.test(document.postform.message.value))
		$('[name=greenquote]').val('0');
	re = /([spoiler])/;
	if (!re.test(document.postform.message.value))
		$('[name=bbcode]').val('0');
		
	if ($('#recaptcha_response_field').length) {
		pausecomp(400);
		if ($('[name=token]').val() != '') {
			return true;
		} else {
			return false;
		}
	}
} 
