﻿var style_cookie;
var style_cookie_txt;
var style_cookie_site;
var kumod_set=false;
var ispage;
var is_entering=false;

var _ = {
    noLocalStorage: "localStorage не поддерживается браузером",
    loading: "Загрузка",
    oops: "Что-то пошло не так...",
    blankResponse: "пустой ответ",
    watchlistAdd: "Тред добавлен в список избранных.",
    watchlistRemove: "Тред удален из списка избранных.",
    expandingThread: "Разворачиваем тред...",
    newThread: "новый тред",
    replyTo: "ответ на",
    cancel: "Отмена",
    update: "Обновить", 
    updatingCounts: "Ищем новые посты...",
    couldntFetch: "Не удалось загрузить этот пост",
    noNewPosts: "Нет новых постов",
    replies: "Ответы",
    settings_fxEnabled: "Анимированные эффекты",
    settings_showReplies: "Показывать ответы внутри поста",
    settings_sfwMode: "Мамка в комнате",
    settings_expandImgFull: "Разворачивать картинки до исходного размера",
    deletePost: "Удалить пост", 
    deleteAndBan: "Удалить пост и забанить постера",
    enterCaptcha: "Пожалуйста, введите капчу.",
    selectText: "Текст не выделен"
    
}

function trace() {
    if (!console.log) return;
    
    var f = arguments.callee.caller;
    var path = arguments[0];
    if (path == '') path += "trace()";
    
    while (f != null) {
        var re = /function ([^\(]+)/;
        var fname = re.exec(f.toString());
        if (fname == null) fname = ''; else fname = fname[1];
        var args = [];
        for (var i = 0; i < f.arguments.length; i++) args.push(f.arguments[i]);
        fname += "(" + args.join(', ') + ")"; 
        path += ' <- ' + fname;
        f = f.caller;
    }
    console.log(path);
}

/* IE/Opera fix, because they need to go learn a book on how to use indexOf with arrays */
if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function(elt /*, from*/) {
    var len = this.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++) {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}
    
/* Utf8 strings de-/encoder */
var Utf8 = {
    // public method for url encoding
    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);
            }
        }
        utftext = utftext.replace(/\n/g,"\r\n");
        return utftext;
    },
    // public method for url decoding
    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;
    }
}

function Cookie(name) {
    if (arguments.length == 1) {
        with(document.cookie) {
            var regexp=new RegExp("(^|;\\s+)"+name+"=(.*?)(;|$)");
            var hit=regexp.exec(document.cookie);
            if(hit&&hit.length>2) return Utf8.decode(unescape(replaceAll(hit[2],'+','%20')));
            else return '';
        }
    } else {
        var value = arguments[1];
        var days = arguments[2];
        if(days) {
            var date=new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            var expires="; expires="+date.toGMTString();
        } else expires="";
        document.cookie=name+"="+value+expires+"; path=/";
    }
}
   

function replaceAll(str, from, to) {
    var idx = str.indexOf( from );
    while ( idx > -1 ) {
        str = str.replace( from, to );
        idx = str.indexOf( from );
    }
    return str;
}


function insert(text) {
    var textarea=document.forms.postform.message;
    if(textarea) {
        if(textarea.createTextRange && textarea.caretPos) { // IE 
            var caretPos=textarea.caretPos;
            caretPos.text=caretPos.text.charAt(caretPos.text.length-1)==" "?text+" ":text;
        } else if(textarea.setSelectionRange) { // Firefox 
            var start=textarea.selectionStart;
            var end=textarea.selectionEnd;
            textarea.value=textarea.value.substr(0,start)+text+textarea.value.substr(end);
            textarea.setSelectionRange(start+text.length,start+text.length);
        } else {
            textarea.value+=text+" ";
        }
        textarea.focus();
    }
}

function markup(start, end) {
    element = $('textarea#message').get(0);
    if (document.selection) {
        element.focus();
        sel = document.selection.createRange();
        sel.text = start + sel.text + end;
    } else if (element.selectionStart || element.selectionStart == '0') {
        element.focus();
        var startPos = element.selectionStart;
        var endPos = element.selectionEnd;
        element.value = element.value.substring(0, startPos) + start + element.value.substring(startPos, endPos) + end + element.value.substring(endPos, element.value.length);
    } else {
        element.value += start + end;
    }
}
    
function quote(b, a) { 
    var v = eval("document." + a + ".message");
    v.value += ">>" + b + "\n";
    v.focus();
}

function checkhighlight() {
    var match;
    if(match=/#i([0-9]+)/.exec(document.location.toString()))
        if(!document.forms.postform.message.value)
            insert(">>"+match[1]);
    if(match=/#([0-9]+)/.exec(document.location.toString()))
        highlight(match[1]);
}

function highlight(post, checknopage) {
    if (checknopage && ispage)  return;
    $('.highlight').removeClass('highlight').addClass('reply');
    $("#reply" + post).removeClass('reply').addClass('highlight');
    var match = /^([^#]*)/.exec(document.location.toString());
    document.location = match[1] + "#" + post;
}    
    
function get_password(name) {
    var pass = getCookie(name);
    if(pass) return pass;

    var chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    pass='';

    for(var i=0;i<8;i++) {
        var rnd = Math.floor(Math.random()*chars.length);
        pass += chars.substring(rnd, rnd+1);
    }
    Cookie(name, pass, 365);
    return(pass);
}

function togglePassword() {
    var passwordbox_html = $("#passwordbox").html().toLowerCase();
    var newhtml = '<td></td><td></td>';
    if (passwordbox_html == newhtml) {
        newhtml = '<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>';
    }
    $("#passwordbox").html(newhtml);
    return false;
}

/* used for textboards only, deleted, src in clean */
function toggleOptions(D,C,B){ trace('deprecated!') }

// proxied functions
function getCookie(name)                {   return Cookie(name)                     }  
function set_cookie(name,value,days)    {   return Cookie(name,value,days)          }       
        
        
function set_stylesheet(styletitle) {
    set_cookie("kustyle_site",styletitle,365);
    set_cookie("kustyle",styletitle,365);

    var links=document.getElementsByTagName("link");
    var found=false;
    for(var i=0;i<links.length;i++) {
        var rel=links[i].getAttribute("rel");
        var title=links[i].getAttribute("title");

        if(rel.indexOf("style")!=-1&&title) {
            links[i].disabled=true; // IE needs this to work. IE needs to die.
            if(styletitle==title) { links[i].disabled=false; found=true; }
        }
    }
    if(!found) set_preferred_stylesheet();
}
     
function set_preferred_stylesheet() {
    var links=document.getElementsByTagName("link");
    for(var i=0;i<links.length;i++) {
        var rel=links[i].getAttribute("rel");
        var title=links[i].getAttribute("title");
        if(rel.indexOf("style")!=-1&&title) {
            links[i].disabled=(rel.indexOf("alt")!=-1);
        }
    }
}
    
function get_active_stylesheet() {
    var links=document.getElementsByTagName("link");
    for(var i=0;i<links.length;i++) {
        var rel=links[i].getAttribute("rel");
        var title=links[i].getAttribute("title");
        if(rel.indexOf("style")!=-1&&title&&!links[i].disabled) return title;
    }

    return null;
}
        
function get_preferred_stylesheet() {
    var links=document.getElementsByTagName("link");
    for(var i=0;i<links.length;i++) {
        var rel=links[i].getAttribute("rel");
        var title=links[i].getAttribute("title");
        if(rel.indexOf("style")!=-1&&rel.indexOf("alt")==-1&&title) return title;
    }

    return null;
}

function delandbanlinks() {
    if (!kumod_set) return;
    
    $('span[class^=dnb]').each(function(index,element) {
        dnbinfo = $(this).attr('class').split('|');
        var newhtml = '&#91;<a href="' + ku_cgipath + '/manage_page.php?action=delposts&boarddir=' + dnbinfo[1] + '&del';
        if (dnbinfo[3] == 'y') {
            newhtml += 'thread';
        } else {
            newhtml += 'post';
        }
        newhtml += 'id=' + dnbinfo[2] + '" title="Delete" onclick="return confirm(\''+_.deletePost+'?\');">D<\/a>&nbsp;<a href="' + ku_cgipath + '/manage_page.php?action=delposts&boarddir=' + dnbinfo[1] + '&del';
        if (dnbinfo[3] == 'y') {
            newhtml +='thread';
        } else {
            newhtml += 'post';
        }
        newhtml +='id=' + dnbinfo[2] + '&postid=' + dnbinfo[2] + '" title="Delete &amp; Ban" onclick="return confirm(\''+_.deleteAndBan+'?\');">&amp;<\/a>&nbsp;<a href="' + ku_cgipath + '/manage_page.php?action=bans&banboard=' + dnbinfo[1] + '&banpost=' + dnbinfo[2] + '" title="Ban">B<\/a>&#93;';

        $(this).html(newhtml);
    });
}
    
var HiddenThreads = {
    list: function() {
        if (localStorage == null) {
            trace(_.noLocalStorage);
            return [];
        }
        var list = localStorage.getItem('hiddenThreads.' + this_board_dir);
        if (list == null) return [];
        return list.split(',');
    },
    isHidden: function(threadid) { return HiddenThreads.list().indexOf(threadid) != -1 },
    hide: function(threadid) { 
        if (localStorage == null) alert(_.noLocalStorage);
        else {
            var newlist = HiddenThreads.list();
            newlist.push(threadid.toString());
            localStorage.setItem('hiddenThreads.' + this_board_dir, newlist.join(','));
        }
    },
    unhide: function(threadid) { 
        if (localStorage == null) alert(_.noLocalStorage);
        else {
            var list = HiddenThreads.list();
            var i = list.indexOf(threadid.toString());
            if (i == -1) return;
            var newlist = list.slice(0,i);
            newlist = newlist.concat(list.slice(i+1));
            localStorage.setItem('hiddenThreads.' + this_board_dir, newlist.join(','));
        }
    }
}
    
function togglethread(threadid) {
    if (HiddenThreads.isHidden(threadid)) {
        $('#unhidethread' + threadid + this_board_dir).slideUp();
        $('#thread' + threadid + this_board_dir).slideDown();
        HiddenThreads.unhide(threadid);
    } else {
        $('#unhidethread' + threadid + this_board_dir).slideDown();
        $('#thread' + threadid + this_board_dir).slideUp();
        HiddenThreads.hide(threadid);
    }
    return false;
}
  
function toggleblotter(save) {
    $('li.blotterentry').each(function(index,element) {
        if($(this).is(":hidden")) {
            $(this).slideDown();
            if (save) Cookie('ku_showblotter', '1', 365);
        } else {
            $(this).slideUp();
            if (save) Cookie('ku_showblotter', '0', 365);
        }
    });
}

function expandthread(threadid, board) {
    if ($('#replies' + threadid + board).get() != '') {
        $('#replies' + threadid + board).prepend("<img src=\"/images/loading.gif\" align=\"middle\" /> " + _.expandingThread + '<br />');
        $.ajax({
            url: '/expand.php?board=' + board + '&threadid=' + threadid,
            success: function(data) {
                var rep = $('#replies' + threadid + board);
                if (data) {
                    rep.html(data);
                    Settings.sfwMode(false);
                    PostPreviews.setupPreviews(rep);
                    showreplies(rep);
                    rep.hide().fadeIn();
                } else {
                    $('#replies' + threadid + board).prepend(_.oops + " ("+_.blankResponse+")");
                }
                delandbanlinks();
            },
            error: function(xhr, status) {
                $('#replies' + threadid + board).prepend(_.oops + " (" + status + ")");
            }
        });
    }
    return false;
}   

function getnewposts(threadid) {
    var lastpost = ($('.postnode').last().find('td[id^=reply]').attr('id'));
    lastpost = lastpost ? lastpost.substring(5) : threadid;
    $.ajax({
        url: '/expand.php?after=' + lastpost + '&board=' + this_board_dir + '&threadid=' + threadid,
        success: function(data) {
            if (data) {
                $('.postnode').last().after('<div class="newposts">' + data + '</div>');
                PostPreviews.setupPreviews($('.newposts').last());
                Settings.sfwMode(false);
                showreplies();
                $('.newposts').last().hide().fadeIn();
            } else {
                popupMessage(_.noNewPosts);
            }
            $('#newposts_get').show();
            $('#newposts_load').hide();
            delandbanlinks();
        },
        error: function(xhr, status) {
            popupMessage(_.oops + " (" + status + ")");
            $('#newposts_get').show();
            $('#newposts_load').hide();
        }
    });
    $('#newposts_get').hide();
    $('#newposts_load').show();
    return false;
}  

function quickreply(threadid) {
    if (threadid == 0) {
        $('#posttypeindicator').html(_.newThread);
    } else {
        $('#posttypeindicator').html(_.replyTo + ' ' + threadid + ' [<a href="#postbox" onclick="javascript:quickreply(\'0\');" title="' + _.cancel + '">x</a>]');
    }
    document.postform.replythread.value = threadid;
} 
    
    
function getwatchedthreads(threadid, board) {
    if ($('#watchedthreadlist').get()!='') {
        $('#watchedthreadlist').html(_.loading + '...');
        $.ajax({
            url: '/threadwatch.php?board=' + board + '&threadid=' + threadid,
            success: function(data) {
                $('#watchedthreadlist').html(data || (_.oops + " ("+_.blankResponse+")"));
            },
            error: function(xhr, status) {
                $('#watchedthreadlist').html(_.oops + " (" + status + ")");
            }
        });
    }
}  

function popupMessage(text, delay) {
    if (delay == null) delay = 1000;
    if ($('#popupMessage').get() == '') {
        $('body').children().last().after('<div id="popupMessage" class="reply"></div>');
        $('#popupMessage').css('position', 'fixed');
        $('#popupMessage').css('top', '50px');
        $('#popupMessage').css('padding', '20px');
        $('#popupMessage').css('width', '40%');
        $('#popupMessage').css('left', '30%');
        $('#popupMessage').css('text-align', 'center');
        $('#popupMessage').css('-webkit-box-shadow', '#666 0px 0px 10px');
        $('#popupMessage').hide();
    }
    $('#popupMessage').html("<span class=\"postername\">" + text + "</span>");
    $('#popupMessage').fadeIn(150).delay(delay).fadeOut(300);
}


function addtowatchedthreads(threadid, board) {
    if ($('#watchedthreadlist').get()!='') {
        $.ajax({
            url: '/threadwatch.php?do=addthread&board=' + board + '&threadid=' + threadid,
            success: function(data) {
                popupMessage(_.watchlistAdd)
                getwatchedthreads('0', board);
            },
            error: function(xhr, status) {
                popupMessage(_.oops + " (" + status + ")");
            }
        });
    }
}
  
function removefromwatchedthreads(threadid, board) {
    if ($('#watchedthreadlist').get()!='') {
        $.ajax({
            url: '/threadwatch.php?do=removethread&board=' + board + '&threadid=' + threadid,
            success: function(data) {
                popupMessage(_.watchlistRemove)
                getwatchedthreads('0', board);
            },
            error: function(xhr, status) {
                popupMessage(_.oops + " (" + status + ")");
            }
        });
    }
}
    
function hidewatchedthreads() {
    Cookie('showwatchedthreads','0',30);
    $("#watchedthreads").fadeOut();
}    
    
function showwatchedthreads() {
    Cookie('showwatchedthreads','1',30);
    window.location.reload(true);
}
    
function checkcaptcha(formid) {
    if($('input[name=captcha]').length > 0) {
        if ($('input[name=captcha]').val() =='') {
            popupMessage(_.enterCaptcha);
            return false;
        }
    }
    return true;
}
    
function expandimg(postnum, imgurl, thumburl, imgw, imgh, thumbw, thumbh) {
    var element = document.getElementById("thumb" + postnum);
    if (element == null) return false;
    if (element.getElementsByTagName('img')[0].getAttribute('alt').substring(0,4)!='full') {
        $(element).html('<img src="'+imgurl+'" alt="full'+postnum+'" class="thumb" height="'+imgh+'" width="'+imgw+'">'); 
        if (Settings.expandImgFull()) return false;    
        element = document.getElementById("thumb" + postnum);
        var img = element.getElementsByTagName('img')[0];
        var max_w = document.documentElement?document.documentElement.clientWidth : document.body.clientWidth;
        var offset = 50;
        var offset_el = img;

        while (offset_el != null) {
                offset += offset_el.offsetLeft;
                offset_el = offset_el.offsetParent;
        }
        var new_w = max_w - offset;
        if (img.width > new_w) {
                var ratio = img.width / img.height;


                var zoom = 1 - new_w / img.width;
                var new_h = new_w / ratio;
                var notice = document.createElement('div');
                notice.setAttribute('class', 'filesize');
                notice.style.textDecoration = 'underline'; 
                var textNode = document.createTextNode("Картинка ужата на " + Math.round(zoom*100) + "% по размеру окна.");
                notice.appendChild(textNode);  
                element.insertBefore(notice, img);
                $(img).width(new_w);
                $(img).height(new_h);

        }     
    } else{
        element.innerHTML = '<img src="' + thumburl + '" alt="' + postnum + '" class="thumb" height="' + thumbh + '" width="' + thumbw + '">';
        if (Settings.sfwMode()) {
            $(element).find('img').stop(true, true).animate({opacity: 0.05}, {duration: 100});
        }
    }
    return false;
}
/*
function expandimg(postnum, imgurl, thumburl, imgw, imgh, thumbw, thumbh) {
    if ($('#expimg'+postnum).length == 0) {
        $(element).before("<span id=\"expimg"+postnum+"\"></span>");
        var expimgspan = $('#expimg'+postnum);
        var thumbimgspan = $('#thumb'+postnum);
        expimgspan.css({position: 'absolute', top: thumbimgspan.offset().top, left: thumbimgspan.offset().left});
        expimgspan.append('<img src="'+imgurl+' class="thumb" />');
        var expimg = expimgspan.find('img').get(0);
        var thumbimg = thumbimgspan.find('img').get(0);

        var max_w = document.documentElement?document.documentElement.clientWidth : document.body.clientWidth;
        var offset = 50;
        var offset_el = img;
        while (offset_el != null) {
                offset += offset_el.offsetLeft;
                offset_el = offset_el.offsetParent;
        }
        var new_w = max_w - offset;
        if (img.width > new_w) {
                var ratio = img.width / img.height;
                var zoom = 1 - new_w / img.width;
                var new_h = new_w / ratio;
                var notice = document.createElement('div');
                notice.setAttribute('class', 'filesize');
                notice.style.textDecoration = 'underline'; 
                var textNode = document.createTextNode("Картинка ужата на " + Math.round(zoom*100) + "% по размеру окна.");
                notice.appendChild(textNode);  
                element.insertBefore(notice, img);
                img.width = new_w;
                img.height = new_h;
        }     
    } else{
        $('#expimg'+postnum).remove();
        var thumbimg = $('#thumb' +postnum).find('img').get(0);
        thumbimg.width = thumb_w;
        thumbimb.height = thumb_h;
    }
} */
    
/* txt only. deleted. src in clean */
function postpreview(D,A,C,B){}
    
function set_inputs(id) {
    if (document.getElementById(id)) {
        with(document.getElementById(id)) {
            if(!name.value) name.value = getCookie("name");
            if(!em.value) em.value = getCookie("email");
            if(!postpassword.value) postpassword.value = get_password("postpassword");
        }
    }
}
    
function set_delpass(id) {
    if (document.getElementById(id).postpassword) {
        with(document.getElementById(id)) {
            if(!postpassword.value) postpassword.value = get_password("postpassword");
        }
    }
}   

(function ($) {
    $.event.special.load = {
        add: function (callback) {
            if ( this.nodeType === 1 && this.tagName.toLowerCase() === 'img' && this.src !== '' ) {
                if ( this.complete || this.readyState === 4 ) {
                    callback.handler.apply(this);
                }
                else if ( this.readyState === 'uninitialized' && this.src.indexOf('data:') === 0 ) {
                    $(this).trigger('error');
                }

                else {
                    $(this).bind('load', callback.handler);
                }
            }
        }
    };
}(jQuery));

var Settings = {
    _checkbox: function(clicked, settingName, defaultValue) {
        if (localStorage == null) {
            trace(_.noLocalStorage);
            return false;
        }
        if (localStorage[settingName] == null) {
            localStorage[settingName] = defaultValue;
        }
        if (clicked == true) {
            // save it
            localStorage[settingName] = $('#settings_' + settingName).is(":checked");
        } else {
            // update checkbox (called on load)
            if (localStorage[settingName] == 'true')
                $('#settings_' + settingName).attr("checked","checked");
            else 
                $('#settings_' + settingName).removeAttr("checked");
        }
        return (localStorage[settingName] == 'true') || (localStorage[settingName] == true) ;
    },
    
    fxEnabled: function(changed) { 
        var enabled = Settings._checkbox(changed, 'fxEnabled', true);
        if (changed != null) {
            $.fx.off = !enabled;
        }
        return enabled;
    },
    
    showReplies: function(changed) {
        var enabled = Settings._checkbox(changed, 'showReplies', false);
        if (changed != null) {
            enabled ? showreplies() : $('.replieslist').remove();
        }
        return enabled;
    },
    
    sfwMode: function(changed) {
        var enabled = Settings._checkbox(changed, 'sfwMode', false);
        if (changed != null) {
            var target = $('img.thumb');
            if(enabled) {
                target.die();
                if (changed) target.stop(true, true).animate({opacity: 0.05},{duration: 100});
                else         target.css({opacity: 0.05});
                target.live('mouseover',      function() {$(this).animate({opacity: 1},   {duration: 100})});
                target.live('mouseout load',  function() {$(this).animate({opacity: 0.05},{duration: 100})});
             
            } else { 
                target.animate({opacity: 1},{duration: 100}).die();
            }
        }
        return enabled;
    },
    
    expandImgFull: function(changed) {
        return Settings._checkbox(changed, 'expandImgFull', false);
    }
}

$(window).ready(function(){shareLinks();});

// HATERS GONNA HATE
function shareLinks() {  
    $("div[id^=thread]").each(function() {
        var url = "http://www.0chan.ru" + $(this).find('.reflink').find('a').first().attr('href').split("#")[0];
        var text = $(this).find('.postnode').first().find('.postmessage').text();

        if (text.length > 100) {
            text = text.substr(0, 100);
            var searchEnd = function(string, endchar) {
                for(var i=99; i>80; i--)
                    if (string.charAt(i) == endchar)
                        return i;
                return -1;
            }
            var ends = ["\n", ".", "?", "!", ";", ",", " "];
            for(var e in ends) {
                var end = searchEnd(text, ends[e]);
                if (end == -1) continue;
                text = text.substr(0, end) + "...";
                break;
            }    
        }

        var title = $(this).find('.postnode').first().find('.filetitle').text();
        title = $.trim(replaceAll(title, "\n", " "));
        if (title == "") {
            var thread = url.split("/")[5].split(".")[0];
            title = document.getElementsByTagName('title')[0].innerHTML+", тред №"+thread; 
        }
        text = $.trim(replaceAll(text, "\n", " "));
        if (text == "") {
            text = title;
        }
        text  = encodeURIComponent(text);
        url   = encodeURIComponent(url);
        title = encodeURIComponent(title); 

        var shares = [
            {name: "1chan",     link: "http://1chan.ru/live/addXS/?link="+url+"&description="+text },
            {name: "twitter",   link: "http://twitter.com/share?url="+url+"&text="+escape("#0chan ")+text },
            {name: "vkontakte", link: "http://vkontakte.ru/share.php?url="+url+"&title="+title+"&description="+text },
            {name: "facebook",  link: "http://www.facebook.com/sharer.php?u="+url+"&t="+text },
        ];

        var sharesBtns = "";
        for (var s in shares) {
            sharesBtns += "<a href=\""+shares[s].link+"\" onclick=\"window.open(this.href, 'Поделиться ссылкой в "+shares[s].name+"', 'width=700,height=300'); return false\" target=\"_blank\"><img hspace=\"1\" class=\"shareSite\" border=\"0\" alt=\""+shares[s].name+"\" src=\"http://img.0chan.ru/images/share/"+shares[s].name+".png\" /></a>";
        }
        $(this).find('.extrabtns').first().append(sharesBtns);
    });
    $(".shareSite").css({opacity: 0.35});
    $(".shareSite").bind('mouseover', function() {$(this).animate({opacity: 1.00}, {duration: 100})});
    $(".shareSite").bind('mouseout',  function() {$(this).animate({opacity: 0.35}, {duration: 100})});
};

$(window).ready(function(){Settings.sfwMode(false)});

$(window).ready(function() {
    // TODO: move that to board-post.class.php
    $('textarea#message').before('<div><nobr>'
    +'<a href="#" onclick="javascript:markup(\'**\', \'**\')" class="uibutton"><b>Жирный</b></a>'
    +'<a href="#" onclick="javascript:markup(\'*\', \'*\')" class="uibutton"><i>Курсив</i></a>'
    +'<a href="#" onclick="javascript:markup(\'[u]\', \'[/u]\')" class="uibutton"><u>Подчеркнутый</u></a>'
    +'<a href="#" onclick="javascript:markup(\'[s]\', \'[/s]\')" class="uibutton"><s>Зачеркнутый</s></a>'
    +'<a href="#" onclick="javascript:markup(\'%%\', \'%%\')" class="uibutton">Спойлер</a>'
    +'<a href="#" id="code_button" class="uibutton">Код ▼</a>'
    +'</nobr></div>');

    $('body').children().first().before('<div style="position: absolute; display: none; z-index:999999" id="code_markup"></div>');
    var code_markup_html = "<select size=\"8\" id=\"code_markup_select\" multiple=\"multiple\">";
    for(var lang_id in code_langs) {
       // code_markup_html += '<a href="#" onclick="javascript:markup(\'[code='+lang_id+']\', \'[/code]\')" class="uibutton">'+code_langs[lang_id]+'</a>';
       code_markup_html += '<option value="'+lang_id+'">'+code_langs[lang_id]+'</option>';
    }
    $('#code_markup').html(code_markup_html);

    $('#code_button').click(function(e) {
        var off = $(this).offset();
        $('#code_markup_select option').each(function() { $(this).removeAttr('selected') });
        $('#code_markup').slideDown(150).css({top: off.top + $(this).height()+1, left: off.left});
    });
    $('#code_markup').bind("mouseleave", function() { $(this).slideUp(150); $(this) });
    $('#code_markup_select').bind("change", function() { 
        var lang = $(this).val().toString();
        if (lang && lang != '') {
            markup('[code='+lang.split(',')[0]+']', '[/code]');
        }
        $('#code_markup').slideUp(150); $(this) 
    });

    $('.uibutton').button().css({fontSize: "12px"}); 
}) 

    
window.onload=function(e) {
    delandbanlinks();
    checkhighlight();
    
    checkgotothread();
    checknamesave();
    
    if (localStorage) {
        for(var s in Settings) {
            if (s.substring(0,1) == "_") continue;
            $("#js_settings").append('<label><input type="checkbox" onchange="javascript:Settings.'+s+'(true)" name="settings_'+s+'" id="settings_'+s+'" value="true"> '+_['settings_'+s]+'</label><br />');
            Settings[s](false);
        }
    } else {
        $("#js_settings").append("<span style=\"color:#F00\">"+_.noLocalStorage+"</span><br />Твой браузер — говно. Скачай <a href=\"http://google.com/chrome\" target=\"_blank\">Chome</a>, например.");
    }   
    
    

    
    $("#watchedthreads").draggable({stop: watchedthreadsdragend, handle: '#watchedthreadsdraghandle'});
    $("#watchedthreads").resizable({stop: watchedthreadsresizeend});
    if (!$.browser.webkit)
        $("textarea#message").resizable();

        function watchedthreadsdragend() {
            set_cookie('watchedthreadstop',document.getElementById('watchedthreads').style.top,30);
            set_cookie('watchedthreadsleft',document.getElementById('watchedthreads').style.left,30);

        }

        function watchedthreadsresizeend() {
            var watchedthreadswidth = document.getElementById('watchedthreads').offsetWidth;
            var watchedthreadsheight = document.getElementById('watchedthreads').offsetHeight;

            set_cookie('watchedthreadswidth',watchedthreadswidth,30);
            set_cookie('watchedthreadsheight',watchedthreadsheight,30);
        }
    //}

    var textbox = document.getElementById('message');
    if(textbox)
    {
        textbox.onfocus=function(){is_entering = true;}
        textbox.onblur=function(){is_entering = false;}
    } 
}

if(style_cookie) {
    var cookie = getCookie(style_cookie);
    var title = cookie ? cookie : get_preferred_stylesheet();

    set_stylesheet(title);
}

/*if(style_cookie_txt) {
    var cookie=getCookie(style_cookie_txt);
    var title=cookie?cookie:get_preferred_stylesheet();

    set_stylesheet(title, true);
}*/

if(style_cookie_site) {
    var cookie=getCookie(style_cookie_site);
    var title=cookie?cookie:get_preferred_stylesheet();

    set_stylesheet(title, false, true);
}

if (getCookie('kumod')=='yes') {
    kumod_set = true;
}

function updatenewpostscount() {
    $.ajax({
        url: '/newpostscount.php?last=' + getCookie('kus_lastvisit'),
        success: function(data) {
            var response = data;
            var resp = response.split('@');
            var arr = resp[0].split(';');
            for(var i = 0; i < arr.length; i++){
                var pair = arr[i].split('='); 
                $('#newposts_' + pair[0]).html((pair[1] == 0)?"" : ' (' + pair[1] + ')');
            }
            $('#refreshnewposts').html('<a href="#" onclick="javascript:updatenewpostscount();return false" target="_self">'+_.update+'</a>');
            Cookie('kus_lastvisit', resp[1], 365);
        },
        error: function() {
            alert(_.oops);
        }
    });
    $('#refreshnewposts').html(_.updatingCounts);
}

var mp3playerid = 0;
function expandmp3(id, path){
    if (mp3playerid == id)
    {
        document.getElementById('player'+id).innerHTML = '';
        document.getElementById('player'+id).style.display = 'none';
        mp3playerid = 0;
    } else {
        if(mp3playerid != 0)
        {
            document.getElementById('player'+mp3playerid).innerHTML = '';
            document.getElementById('player'+mp3playerid).style.display = 'none';
        }

        document.getElementById('player'+id).innerHTML = '<embed src="/mediaplayer.swf?type=mp3&file='+path+'" width="320" height="20">';
        document.getElementById('player'+id).style.display = 'block';
        mp3playerid = id;
    }
}

var swfplayerid = 0;
function expandswf(id, path, w, h){
    if (swfplayerid == id)
    {
        document.getElementById('swfplayer'+id).innerHTML = '';
        document.getElementById('swfplayer'+id).style.display = 'none';
        swfplayerid = 0;
    } else {
        if(swfplayerid != 0)
        {
            document.getElementById('swfplayer'+swfplayerid).innerHTML = '';
            document.getElementById('swfplayer'+swfplayerid).style.display = 'none';
        }

        document.getElementById('swfplayer'+id).innerHTML = '<embed src="'+path+'" width="'+w+'" height="'+h+'">';
        document.getElementById('swfplayer'+id).style.display = 'block';
        swfplayerid = id;
    }
}

function checknamesave(){
    var checkd;
    if(getCookie('name') != '') {
        checkd = true;
    } else {
        checkd = false;
    }
    var doc = document.getElementById('save');
    if (doc != null) doc.checked = checkd;
}
function checkgotothread(){
    var checkd; 
    if(getCookie('gotothread') == 'on') {
        checkd = true;
    } else {
        checkd = false;
    }
    document.getElementById('gotothread').checked = checkd;
}

function navigatepages (event)
{
   
	if (!document.getElementById) return;
        if (is_entering) return;
	if (window.event) event = window.event;

	if (event.ctrlKey)
	{

		var link = null;
		var href = null;

                var docloc = document.location.toString();
                if (docloc.indexOf('/res/') != -1) return;
                if (docloc.indexOf('.html') == -1 || docloc.indexOf('board.html') != -1) {
                    var page = 0;
                    var docloc_trimmed = docloc.substr(0, docloc.lastIndexOf('/') + 1);
                } else {
                    var page = docloc.substr((docloc.lastIndexOf('/') + 1));
                    page = (+page.substr(0, page.indexOf('.html')));
                    var docloc_trimmed = docloc.substr(0, docloc.lastIndexOf('/') + 1);
                }
                if (page == 0) {
                    var docloc_valid = docloc_trimmed;
                } else {
                    var docloc_valid  = docloc_trimmed + page + '.html';
                }
                if(match=/#s([0-9]+)/.exec(docloc)) {
                    var relativepost = (+match[1]);
                } else {
                    var relativepost = -1;
                }
                var maxthreads = 0;
                while(document.getElementsByName('s'+(++maxthreads)).length>0){}

                switch (event.keyCode ? event.keyCode : event.which ? event.which : null)
                {
                        case 0x25: // ctrl+left
                                link = document.getElementById('prevPage');
                                break;
                        case 0x27: // ctrl+right
                                link = document.getElementById('nextPage');
                                break;

                        case 0x28: // ctrl+down
                            if (relativepost == maxthreads - 1) {
                                break; //var newrelativepost = 0;
                            } else {
                                var newrelativepost = relativepost + 1;
                            }
                            href = docloc_valid + '#s' + newrelativepost;
                            break;

                        case 0x26: // ctrl+up
                            if (relativepost == -1 || relativepost == 0) {
                                break; //var newrelativepost = maxthreads - 1;
                            } else {
                                var newrelativepost = relativepost - 1;
                            }
                            href = docloc_valid + '#s' + newrelativepost;
                            break;

                        case 0x24: // ctrl+home
                                document.location = docloc_trimmed;
                                break;
                }

                if (link && link.action) document.location = link.action;
                if (href) document.location.href = href;
	}
}
 

if (window.document.addEventListener) {
   window.document.addEventListener("keydown", navigatepages, false);
} else {
   window.document.attachEvent("onkeydown", navigatepages);
}

// YOBA previews 
var PostPreviews = {
    zindex:  1,
    cached: {},
    parent: {},

    showPreview: function(e) {
        var href = this.getAttribute("href");
        var postid = href.split("#")[1];
        var board = href.split("/")[1] || this_board_dir;
        var previewid = 'preview_'+board+'_'+postid;
        var preview = $('#' + previewid);
        if (preview.length == 0) {
            $('body').children().first().before('<div id="'+previewid+'"></div>');
            preview = $('#preview_'+board+'_'+postid);
            preview.addClass('reflinkpreview').addClass('content-background');         
            preview.mouseleave(PostPreviews.onMouseOut);
            preview.mouseover(PostPreviews.onMouseOver);
        }
        var parent = $(this).parents('div[id^=preview]');
        if (parent.length > 0) {
            if (previewid == parent.attr('id')) { return; } // anti-recursion
            for(var id in PostPreviews.parent) { if (id == previewid || PostPreviews.parent[id] == previewid) return }
            PostPreviews.parent[previewid] = parent.attr('id');
        } else {
            for(var id in PostPreviews.parent) {
                $('#'+id).stop(true, true);
                $('#'+id).fadeOut(1);
                $('#'+PostPreviews.parent[id]).stop(true, true);
                $('#'+PostPreviews.parent[id]).fadeOut(1);
            }
            PostPreviews.parent = [];
        }
        preview.css({top:e.pageY+5, left:e.pageX+15, zIndex: PostPreviews.zindex++});     
        if (PostPreviews.cached[previewid] != null) {  
            preview.html(PostPreviews.cached[previewid]);  
            PostPreviews.setupPreviews(preview);
            $(preview).fadeIn(100);	
        } else {
            preview.html("<img alt=\"...\" src=\"/images/loading.gif\" />");
            $.ajax({
                url: "/getsinglepost.php?b="+board+"&p="+postid,
                success: function(data){
                    var text = data||(_.oops + " (" + _.blankResponse + ")");
                    preview.html(text);
                    if (data) {
                        PostPreviews.cached[previewid] = data;
                        PostPreviews.setupPreviews(preview);
                        Settings.sfwMode(false);
                    }
                    $(preview).fadeIn(100);
                },
                error: function(){
                    preview.html(_.couldntFetch);
                    $(preview).fadeIn(100);
                }
            });
        }
    },

    onMouseOver: function() {
        var preview = $(this);
        if ($(this).is('a')) {
            var href = this.getAttribute("href");
            var postid = href.split("#")[1];
            var board = href.split("/")[1] || this_board_dir;
            preview = $('#preview_'+board+"_"+postid).first();
        }
        while (preview.length > 0) {
            preview.stop(true,true);
            preview.fadeIn(1);
            preview = $('#' + PostPreviews.parent[preview.attr('id')]);
            
        }
    },
    
    onMouseOut: function() {
        var preview = $(this);
        if ($(this).is('a')) {
            var href = this.getAttribute("href");
            var postid = href.split("#")[1];
            var board = href.split("/")[1] || this_board_dir;
            preview = $('#preview_'+board+"_"+postid).first();
        }
        while (preview.length > 0) {
            preview.delay(100).fadeOut(100).queue('fx', function() { 
                delete PostPreviews.parent[$(this).attr('id')];
                $(this).remove();
            });
            preview = $('#' + PostPreviews.parent[preview.attr('id')]);   
        }
    },

    setupPreviews: function(root) {
        $(root).find('a').each(function(i,e) { 
            if ($(this).html().substring(0,8) == "&gt;&gt;") {
                $(this).mouseenter(PostPreviews.showPreview);
                $(this).mouseleave(PostPreviews.onMouseOut);
            }
        });
    }

}


// inline replies
function showreplies(root) {
    if (/*ispage || */!Settings.showReplies()) return;
    root = root ? root : 'body';
    $(root).find('.replieslist').remove();
    var repliesStrings = [];
    $(root).find('.postnode').each(function(index, element) {
        var postlink = $(this).find('span.reflink').find('a').first().attr('href');
        var postid = postlink.split('#')[1];
        var replies = [];
        $(root).find(".postmessage").find('a').each(function(index, element) {
            if ($(this).attr('href') == postlink)
                replies.push($(this).parents('.postnode').first().find('span.reflink').find('a').attr('href'));
        });
        replies = $.unique(replies);
        if (replies.length > 0) { 
            repliesStrings[postid] = '<div class="replieslist"><br />'+_.replies+': ';
            for (var i = 0; i < replies.length; i++) {
                var replypostlink = replies[i];
                var replypostid = replypostlink.split('#')[1];
                repliesStrings[postid] += '<a href="'+replypostlink+'" onclick="javascript:highlight(\''+replypostid+'\', true);">&gt;&gt;'+replypostid+"</a>";
                if (i != replies.length - 1) repliesStrings[postid] += ', ';
            }
        }
    });
    $(root).find('.postnode').each(function(index, element) {
        var postid = $(this).find('span.reflink').find('a').first().attr('href').split('#')[1];
        if (repliesStrings[postid]) {
            $(this).find('.postmessage').append(repliesStrings[postid]);
            PostPreviews.setupPreviews($(this).find('.replieslist').get());
        }
    });
}

var lastVoice = null;
function voicePlay(id) {
    if (lastVoice) {
        $("object#voicePlay").remove();
        $("div#voice_"+lastVoice).show();
    }
    if (id) {
        $("div#voice_"+id).hide();
        var player_code = '<object id="voicePlay" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" '+
                        '         width="370" height="70" '+
                        '         codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab">'+
                        '     <param name="movie" value="/voiceplay.swf?id='+id+'&p=1" />'+
                        '     <param name="quality" value="high" />'+
                        '     <param name="bgcolor" value="#eeeeee" />'+
                        '     <param name="wmode" value="transparent" />'+
                        '     <param name="allowScriptAccess" value="always" />'+
                        '     <embed id="voicerec" src="/voiceplay.swf?id='+id+'&p=1" wmode="transparent" quality="high" bgcolor="#eeeeee" '+
                        '         width="370" height="70" name="voicerec" align="middle" '+
                        '         play="true" loop="false" quality="high" allowScriptAccess="always" '+
                        '         type="application/x-shockwave-flash" '+
                        '         pluginspage="http://www.macromedia.com/go/getflashplayer">'+
                        '     </embed>'+
                        ' </object>';
        $("div#voice_"+id).after(player_code);
    }

    lastVoice = id;
}

/// overlay menu
var menu_current = '';
var menu_last = '';
function menu_show(id)
{
    if(menu_current != '')
    {
        $('#'+menu_current).delay(100).slideUp(150);
        menu_last = menu_current;
    }
    if (id != '') {
        if (menu_last == id && $('#' + id).queue().length > 0) {
            $('#' + id).clearQueue();
        } else {
            $('#' + id).slideDown(150);
        }
    }
    menu_current = id;
}
function menu_pin(){
    if(document.getElementById('overlay_menu').style.position == 'absolute') {
        document.getElementById('overlay_menu').style.position = 'fixed';
        Cookie('ku_menutype', 'fixed', 365);
    } else { 
        document.getElementById('overlay_menu').style.position = 'absolute';
        Cookie('ku_menutype', 'absolute', 365);
    }
}

$(function() {
    if(getCookie('ku_menutype')) {
        var c = Cookie('ku_menutype');
        if(c != 'default' && c != '')
            document.getElementById('overlay_menu').style.position = c;
    }
})

function set_oldmenu(cookie){
    if(cookie) {
        Cookie('ku_oldmenu', 'yes', 90);
    }
    var h = document.getElementById('boardlist_header');
    var f = document.getElementById('boardlist_footer');
    if (h && f) {
        h.innerHTML = f.innerHTML + ' <a href=\"#\" onclick=\"javascript:set_cookie(\'ku_oldmenu\', \'no\', 90);parent.document.location.reload(true);\">[overlay]</a>';
    }
}

var code_langs = {
    text: "Простой текст",
    actionscript: "ActionScript",
    actionscript3: "ActionScript 3",
    ada: "Ada",
    applescript: "AppleScript",
    asm: "ASM",
    asp: "ASP",
    avisynth: "AviSynth",
    bash: "Bash",
    bf: "Brainfuck",
    blitzbasic: "BlitzBasic",
    c: "C",
    cobol: "COBOL",
    cpp: "C++",
    csharp: "C#",
    css: "CSS",
    d: "D",
    delphi: "Delphi",
    diff: "Diff",
    dos: "DOS",
    fortran: "Fortran",
    haskell: "Haskell",
    html4strict: "HTML",
    ini: "INI",
    java: "Java",
    javascript: "Javascript",
    latex: "LaTeX",
    lisp: "Lisp",
    lua: "Lua",
    make: "GNU make",
    matlab: "Matlab M",
    mirc: "mIRC Scripting",
    mpasm: "Microchip Assembler",
    mxml: "MXML",
    mysql: "MySQL",
    objc: "Objective-C",
    ocaml: "OCaml",
    pascal: "Pascal",
    perl: "Perl",
    php: "PHP",
    pic16: "PIC16",
    powershell: "posh",
    prolog: "Prolog",
    python: "Python",
    qbasic: "QBasic/QuickBASIC",
    rails: "Rails",
    ruby: "Ruby",
    scala: "Scala",
    smalltalk: "Smalltalk",
    smarty: "Smarty",
    sql: "SQL",
    tcl: "TCL",
    tsql: "T-SQL",
    vb: "Visual Basic",
    vbnet: "vb.net",
    xml: "XML"
}


;(function(){
    var $$;
    $$ = jQuery.fn.flash = function(htmlOptions, pluginOptions, replace, update) {
    var block = replace || $$.replace;
    pluginOptions = $$.copy($$.pluginOptions, pluginOptions);
    if(!$$.hasFlash(pluginOptions.version)) {
        if(pluginOptions.expressInstall && $$.hasFlash(6,0,65)) {
            var expressInstallOptions = {
                flashvars: {      
                    MMredirectURL: location,
                    MMplayerType: 'PlugIn',
                    MMdoctitle: jQuery('title').text() 
                }                    
            };
        } else if (pluginOptions.update) {
            block = update || $$.update;
        } else {
            return this;
        }
    }
    htmlOptions = $$.copy($$.htmlOptions, expressInstallOptions, htmlOptions);
    return this.each(function(){
            block.call(this, $$.copy(htmlOptions));
        });
    };
    
    $$.copy = function() {
        var options = {}, flashvars = {};
        for(var i = 0; i < arguments.length; i++) {
            var arg = arguments[i];
            if(arg == undefined) continue;
            jQuery.extend(options, arg);
            if(arg.flashvars == undefined) continue;
            jQuery.extend(flashvars, arg.flashvars);
        }
        options.flashvars = flashvars;
        return options;
    };
    
    $$.hasFlash = function() {
        if(/hasFlash\=true/.test(location)) return true;
        if(/hasFlash\=false/.test(location)) return false;
        var pv = $$.hasFlash.playerVersion().match(/\d+/g);
        var rv = String([arguments[0], arguments[1], arguments[2]]).match(/\d+/g) || String($$.pluginOptions.version).match(/\d+/g);
        for(var i = 0; i < 3; i++) {
            pv[i] = parseInt(pv[i] || 0);
            rv[i] = parseInt(rv[i] || 0);
            if(pv[i] < rv[i]) return false;
            if(pv[i] > rv[i]) return true;
        }
        return true;
    };
    
    $$.hasFlash.playerVersion = function() {
        try {
            try {
                var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
                try { axo.AllowScriptAccess = 'always';    } 
                catch(e) { return '6,0,0'; }                
            } catch(e) {}
            return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
        } catch(e) {
            try {
                if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){
                    return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
                }
            } catch(e) {}        
        }
        return '0,0,0';
    };
    
    $$.htmlOptions = {
        height: 240,
        flashvars: {},
        pluginspage: 'http://www.adobe.com/go/getflashplayer',
        src: '#',
        type: 'application/x-shockwave-flash',
        width: 320        
    };
     
    $$.pluginOptions = {
        expressInstall: false,
        update: true,
        version: '6.0.65'
    };
    
    $$.replace = function(htmlOptions) {
        this.innerHTML = '<div class="alt">'+this.innerHTML+'</div>';
        jQuery(this)
            .addClass('flash-replaced')
            .prepend($$.transform(htmlOptions));
    };
    
    $$.update = function(htmlOptions) {
        var url = String(location).split('?');
        url.splice(1,0,'?hasFlash=true&');
        url = url.join('');
        var msg = '<p>This content requires the Flash Player. <a href="http://www.adobe.com/go/getflashplayer">Download Flash Player</a>. Already have Flash Player? <a href="'+url+'">Click here.</a></p>';
        this.innerHTML = '<span class="alt">'+this.innerHTML+'</span>';
        jQuery(this)
            .addClass('flash-update')
            .prepend(msg);
    };
    
    function toAttributeString() {
        var s = '';
        for(var key in this)
            if(typeof this[key] != 'function')
                s += key+'="'+this[key]+'" ';
        return s;        
    };
    
    function toFlashvarsString() {
        var s = '';
        for(var key in this)
            if(typeof this[key] != 'function')
                s += key+'='+encodeURIComponent(this[key])+'&';
        return s.replace(/&$/, '');        
    };
    
    $$.transform = function(htmlOptions) {
        htmlOptions.toString = toAttributeString;
        if(htmlOptions.flashvars) htmlOptions.flashvars.toString = toFlashvarsString;
        return '<embed ' + String(htmlOptions) + '/>';        
    };
    
    if (window.attachEvent) {
        window.attachEvent("onbeforeunload", function(){
            __flash_unloadHandler = function() {};
            __flash_savedUnloadHandler = function() {};
        });
    }
    
})();
