
function Widget ()
{
    this.pos = 0;
    this._pos = 0; // last ok position
    this._back = true;
    this._html = "";
    this._BB_id;
    this.bb;
    this.C_ids;
    // animation default (invisible)
    this._alpha = 0;
    this._interval = 0;
    this.settings = {};
    this.settings.slideshowTime = 5;
    this._slideshowId = false;
    this._categories = false;
    this._win = false;
    var oThis = this;

    // els
    this.wbbm = oel('wbbm');
    this.wbbel = oel('wbbel');

    // bduttons
    this.buts = [];
    this.buts.categories = oel('wbc');
    this.buts.slideshow = oel('wbs');
    this.buts.prev = oel('wbprev');
    this.buts.next = oel('wbnext');
    this.buts.cclose = oel('wwcbc');
    this.buts.sclose = oel('wwsbc');
    this.buts.signin = oel('wsignin');
    this.buts.signout = oel('wsignout');
    this.buts.ccall = oel('wwccall');


    this._evtMethod(this.buts.prev, "click", "getPrev", null, true);
    this._evtMethod(this.buts.next, "click", "getNext", null, true);
    this._evtMethod(this.buts.slideshow, "click", "slideshow", null, true);
    this._evtMethod(this.buts.categories, "click", "categories", null, true);
    //this._evtMethod(this.buts.cclose, "click", "endCategories", null, true);
    this._evtMethod(this.buts.cclose, "click", "closeWindow", null, true);
    this._evtMethod(this.buts.sclose, "click", "closeWindow", null, true);
    this._evtMethod(this.buts.signin, "click", "signin", null, true);
    this._evtMethod(oel('wwsbSubmit'), "click", "doSignin", null, true);
    this._evtMethod(this.buts.signout, "click", "doSignout", null, true);


    // handle next/prev loads
    this.oJsr = new Jsr();
    this.oJsr.onload = function (oJsr)
    {
        for (var method in oJsr.results) {
            if (method == 'getNext' || method == 'getHistory') {
                if (oJsr.results[method]) {
                    oThis._pos = oJsr.params.pos;
                    oThis._html = oJsr.results[method];
                    oThis.bbChange();
        		    // continue slideshow
        	        oThis.slideshow(true);
                } else {
                    // set the but disabled
                    //alert("dbg: no more / " + oJsr.params.pos);
                    if (method == 'getHistory') {
                        // but - disable
                        oThis.pos = oThis._pos;
                        oThis._back = false;
                        oThis.buts.prev.style.backgroundPosition = "top";
                    }
                }
            }
        }
    }


    // categories
    this.wins = {};
    this.wins.b = oel('ww-b');
    this.wins.mask = oel('ww-m');
    this.wins.categories = oel('ww-c');
    this.wins.signin = oel('ww-s');


    // set categoriy checkboxes
    var checks = this.wins.categories.getElementsByTagName('input');
    try {
        this.C_ids = document.cookie.split("w_C_ids=")[1].split(';')[0].split(",");
    } catch (e) {}

    if (this.C_ids) {
        for (var i=0; i<checks.length; i++) {
            checks[i].checked = false;
            for (var j=0; j<this.C_ids.length; j++) {
                if (this.C_ids[j] == Number(checks[i].id.substr(2))) {
                   checks[i].checked = true;
                }
            }
        }
    } else {
        for (var i=0; i<checks.length; i++) {
            checks[i].checked = true;
        }
    }

    // checks
    this._updateChecksAll();
    this._evtMethod(this.buts.ccall, "click", "checkAll", null, false);
    oel("wcc").onclick = function (evt)
    {
        var evt = evt? evt : window.event;
        var el = evt.target? evt.target : evt.srcElement;
        if (el.tagName.toLowerCase() != "input") {
            return;
        }
        if (! el.checked) {
            oThis.buts.ccall.checked = false;
        }
        oThis._updateChecksAll();
    }
    // mask close add
    this._evtMethod(this.wins.mask, "click", "closeWindow", null, true);

    // Safari patch
    //this._evtMethod(oel('safp'), "click", "closeWindow", null, true);
    if (navigator.userAgent.indexOf("Safari") != -1) {
        var safp = document.createElement('div');
        this.wins.categories.appendChild(safp);
        safp.style.cssText = "display: block; position: absolute; top: 240px; let: 0; width: 290px; height: 45px; z-index: 100000;";
        this._evtMethod(safp, "click", "closeWindow", null, true);
    }

    // load first
    this.getNext();
}

Widget.init = function (settings)
{
    if (BDP.U_id == false && BDP.AU_id == false) {
        setTimeout(function(){Widget.init(settings)}, 1000);
        return;
    }
    if (window.oWidget) {
        return;
    }
    window.oWidget = new Widget();
    if (typeof settings == "object") {
        for (k in settings) {
            oWidget.settings[k] = settings[k];
        }
    }

}

Widget.prototype._evtMethod = BuzzBite.prototype._evtMethod;


Widget.prototype.openWindow = function(win)
{
    //this.wins.mask.style.display = "block";
    //this.wins[win].style.display = "block";
    toAlpha(this.wins.mask, 70);
    toAlpha(this.wins[win], 100);
    this._win = win;

}
Widget.prototype.closeWindow = function()
{
    if (! this._win) return;
    if (this._win == "categories") {
        if (this.saveCategories() == false) {
            return;
        }
    }
    //this.wins.mask.style.display = "none";
    //this.wins[this._win].style.display = "none";
    toAlpha(this.wins.mask, 0);
    toAlpha(this.wins[this._win], 0);
    this._win = false;
}


Widget.prototype.doSignin = function()
{
    var oThis = this;
    var oJsr = new Jsr();
    oJsr.onload = function (oJsr)
    {
        var res = oJsr.results.signin;
        if (res == false) {
            BDP.message('w_login_invalid');
            return;
        } else {
            // OK
            BDP.U_id = res.U_id;
            if (res.U_username.length > 8) {
                oel('wusername').innerHTML = res.U_username.substring(0, 8) + '&hellip;';
            } else {
                oel('wusername').innerHTML = res.U_username;
            }
            oThis.buts.signin.style.display = "none";
            oThis.buts.signout.style.display = "inline";
            oThis.closeWindow();
        }
        // set display:
    }
    var params = {};
    params.U_username = oel('U_username').value;
    params.U_password = oel('U_password').value;
    if (! params.U_username) return BDP.message('w_login_nouser');
    if (! params.U_password) return BDP.message('w_login_nopass');
    oJsr.call('misc', 'signin', params);
}
Widget.prototype.doSignout = function()
{
    BDP.U_id = 0;

    BDP.setCookie('U[U_id]', false);
    BDP.setCookie('U[hash]', false);

    this.buts.signin.style.display = "inline";
    this.buts.signout.style.display = "none";

    oel('wusername').innerHTML = "";

    BDP.init();
}


Widget.prototype._updateChecksAll = function()
{
    var checks = oel("wcc").getElementsByTagName('input');
    for (var i=0; i<checks.length; i++) {
        if (checks[i].checked == false) {
            this.buts.ccall.checked = false;
            return;
        }
    }
    this.buts.ccall.checked = true;
}

Widget.prototype.checkAll = function()
{
    var state = this.buts.ccall.checked;
    var checks = oel("wcc").getElementsByTagName('input');
    for (var i=0; i<checks.length; i++) {
        checks[i].checked = state;
    }
}

Widget.prototype.saveCategories = function()
{
    var checks = oel("wcc").getElementsByTagName('input');
    var checked = [];
    for (var i=0; i<checks.length; i++) {
        if (checks[i].checked) {
            checked.push(checks[i].id.split('_')[1]);
        }
    }
    if (checked.length == 0) {
        BDP.message("w_categories_missing");
        return false;
    }
    this.C_ids = checked;
    // set cookie
    //ablajev:delete w_C_id cookie - all cats selected, no need to make IN C_ids!
    if(this.buts.ccall.checked !== true) {
        BDP.setCookie('w_C_ids', checked.join(","), (10*365*24*60*60))
    } else {
        BDP.setCookie('w_C_ids', "", (10*-365*24*60*60))
    }
    return true;
}

Widget.prototype.categories = function()
{
    this.openWindow('categories');
}

Widget.prototype.signin = function ()
{
    this.openWindow('signin');
}

Widget.prototype.getNext = function()
{
    if (this._back == false) {
        this.buts.prev.style.backgroundPosition = "bottom";
        this._back = true;
    }
    if (this.pos < 0) {
        ++ this.pos;
        this.oJsr.call('buzzbite', 'getHistory', {pos: this.pos});
    } else {
        this.oJsr.call('buzzbite', 'getNext', {pos: this.pos});
    }
}

Widget.prototype.getPrev = function()
{
    if (this._back == false) {
        return;
    }
    -- this.pos;
	this.oJsr.call('buzzbite', 'getHistory', {pos: this.pos});
}

Widget.prototype.slideshow = function(restore)
{
    // restore
    if (restore) {
        if (this._slideshowId) {
            var state = true;
        } else {
            return;
        }
    }
    // togle
    else {
        var state = new Boolean(this._slideshowId == false);
    }

    var oThis = this;
    // on
    if (state == true) {
        // stop prev
        if (this._slideshowId) {
            clearTimeout(this._slideshowId);
        }
        // start
        var t = restore? this.settings.slideshowTime * 1000 : 0;
        this._slideshowId = setTimeout(function () { oThis.getNext() }, t);

        // but - disable
        this.buts.slideshow.style.backgroundPosition = "bottom";

    }
    // off
    else {
        if (this._slideshowId) {
            clearTimeout(this._slideshowId);
        }
        this._slideshowId = false;

        // but - enable
        this.buts.slideshow.style.backgroundPosition = "top";
    }

}

Widget.prototype.bbChange = function ()
{
    // set (bb destr) & show (init new bb)
    function onShow ()
    {
        this.bb = new BuzzBite( this._getBB_id() );
        this.slideshow(true);
    }
    function onHide ()
    {
        if (this.bb) {
            this.bb.destroy();
        }
        this.wbbel.innerHTML = this._html;
        this._html = "";
        toAlpha(this.wbbm, 0, [onShow, this]);
    }

    // hide
    toAlpha(this.wbbm, 100, [onHide, this]);
}
Widget.prototype._getBB_id = function ()
{
    var els = this.wbbel.getElementsByTagName("div");
    for (var i=0; i<els.length; i++) {
        if (els[i].id && els[i].id.indexOf('bb_') == 0) {
            return els[i].id.substr(3);
        }
    }
}




////////////// common /////////////////////////////////////

function toAlpha (el, alpha, onComplete, settings)
{
    if (el._a === undefined) {
        el._a = getAlpha(el);
    }

    var start, end, step, speed, tune;

    var start = el._a;
    var end = alpha;
	var step = 0;
	var speed = 20;
	var tune = 10; //1;

	if (start == end) {
	    step = 0;
	} else if (start < end) {
	    step = +1;
	} else {
	    step = -1;
	}

	// sped tune
	step *= tune;

	// stop prev
    if (el._2ai) {
        clearInterval(el._2ai);
    }

	var cur = el._a;
	function f ()
	{
	    cur += step;
	    if ((step == 0) || (step < 0 && cur <= end) || (step > 0 && cur >= end)) {
	        cur = end;
	    }
        setAlpha(el, cur);
        el._a = cur;
		if (cur == end) {
		    clearInterval(el._2ai);
		    if (!onComplete) return;
		    switch (onComplete.constructor)
		    {
                case String:
                    onComplete = new Function(onComplete);
                case Function:
                    onComplete();
                break;
                case Array:
                    onComplete[0].apply(onComplete[1], onComplete[2]? onComplete[2] : []);
                break;
		    }
		}
	}
	el._2ai = setInterval(f, speed);
}

function setAlpha (el, alpha)
{
    try {
		var s = el.style;
		s.display = alpha? "block" : "none";
		s.visibility = alpha? "visible" : "hidden";
		s.opacity = (alpha / 100);
		s.MozOpacity = (alpha / 100);
		s.KhtmlOpacity = (alpha / 100);
		s.filter = "alpha(opacity=" + alpha + ")";
    } catch (e) {}
}

function getAlpha(el)
{
    var style;
    if (el.currentStyle) {
        style = el.currentStyle;
    }
    else if (document.defaultView.getComputedStyle) {
        style = document.defaultView.getComputedStyle(el, null);
    }
    if (! style) {
        return;
    }
    if (style.display == "none" || style.visibility == 'hidden') {
        return 0;
    }
    var alpha = 100;
    var props = ['opacity', 'moz-opacity', 'khtml-opacity'];
    for (var i=0; i<props.length; i++) {
        for (var k in style) {
            if (k == props[i]) {
                return style[k] * 100;
            }
        }
    }
    if (style.filter) {
        var m = style.filter.match(/opacity=(\d+)/i);
        if (m && m[1]) {
            alpha = m[1];
        }
    }
    return alpha;
}


function oel (id) { return document.getElementById(id); }