/* Stack up window.onload event using this function from Simon Willison - http://www.sitepoint.com/blog-post-view.php?id=171578 */
var addLoadEvent = function (func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            oldonload();
            func();
        }
    }
}

/*
 * (c)2006 Jesse Skinner/Dean Edwards/Matthias Miller/John Resig
 * Special thanks to Dan Webb's domready.js Prototype extension
 * and Simon Willison's addLoadEvent
 *
 * For more info, see:
 * http://www.thefutureoftheweb.com/blog/adddomloadevent
 * http://dean.edwards.name/weblog/2006/06/again/
 * http://www.vivabit.com/bollocks/2006/06/21/a-dom-ready-extension-for-prototype
 * http://simon.incutio.com/archive/2004/05/26/addLoadEvent
 * 
 *
 * To use: call addDOMLoadEvent one or more times with functions, ie:
 *
 *    function something() {
 *       // do something
 *    }
 *    addDOMLoadEvent(something);
 *
 *    addDOMLoadEvent(function() {
 *        // do other stuff
 *    });
 *
 */
 
addDOMLoadEvent = (function(){
    // create event function stack
    var load_events = [],
        load_timer,
        script,
        done,
        exec,
        old_onload,
        init = function () {
            done = true;

            // kill the timer
            clearInterval(load_timer);

            // execute each function in the stack in the order they were added
            while (exec = load_events.shift())
                exec();

            if (script) script.onreadystatechange = '';
        };

    return function (func) {
        // if the init function was already ran, just run this function now and stop
        if (done) return func();

        if (!load_events[0]) {
            // for Mozilla/Opera9
            if (document.addEventListener)
                document.addEventListener("DOMContentLoaded", init, false);

            // for Internet Explorer
            /*@cc_on @*/
            /*@if (@_win32)
                document.write("<script id=__ie_onload defer src=//0><\/scr"+"ipt>");
                script = document.getElementById("__ie_onload");
                script.onreadystatechange = function() {
                    if (this.readyState == "complete")
                        init(); // call the onload handler
                };
            /*@end @*/

            // for Safari
            if (/WebKit/i.test(navigator.userAgent)) { // sniff
                load_timer = setInterval(function() {
                    if (/loaded|complete/.test(document.readyState))
                        init(); // call the onload handler
                }, 10);
            }

            // for other browsers set the window.onload, but also execute the old window.onload
            old_onload = window.onload;
            window.onload = function() {
                init();
                if (old_onload) old_onload();
            };
        }

        load_events.push(func);
    }
})();

    // класс список
    var ListClass = new Class({
        initialize: function(event, elementclass)
        {
            this.objList = Array();
            this.objListH = Array();
            this.objInitList = Array();
            this.objInitListOID = Array();
            this.event = event;
            this.elementclass = elementclass;
        },

        addObject: function(book_id, object_id)
        {
            if (book_id == '' || object_id == '') return;

            this.objInitList.push(book_id);
            this.objInitListOID.push(object_id);
        },

        bindAll: function()
        {
            //alert(this.objInitList);
            for (i = 0; i < this.objInitList.length; i++)
            {
                this.objList[i] = new this.elementclass(this.objInitList[i]);
                this.objListH[i] = this.objList[i].send.bindAsEventListener(this.objList[i]);

                $(this.objInitListOID[i]).addEvent(this.event, this.objListH[i]);
            }
        },

        unbindAll: function()
        {
            for (i = 0; i < this.objInitList.length; i++)
            {
                if ($(this.objInitListOID[i]))
                {
                    $(this.objInitListOID[i]).removeEvent(this.event, this.objListH[i]);
                }
            }
        },

        clear: function()
        {
            this.unbindAll();
            this.objList = Array();
            this.objListH = Array();
            this.objInitList = Array();
            this.objInitListOID = Array();
        }
    });

    // привязка событий к списку элементов
    function BindList(HTMLClass, ListObject){
        if ($$(HTMLClass).length>0){ListObject.clear();}
        $$(HTMLClass).each(function(item) {
            id = item.id.substr(item.id.lastIndexOf('-') + 1);
            ListObject.addObject(id, item.id);
        });
        if ($$(HTMLClass).length>0)ListObject.bindAll();
    }

    var trim = function($str) {
        return $str.replace(/^\s+|\s+$/g,"");
    }

    var strToQueryString = function(str)
    {
        //var reg = new RegExp("\\\\",'g');
        //str = str.replace(reg, '[!!!backslash!!!]');
        //alert(str);

        var reg = new RegExp('([\\\\"])','g');
        str = str.replace(reg, '\\$1');

        //alert(str);
        str = encodeURIComponent(str);
        //alert(str);

        // /-%2F
        //var reg = new RegExp('\/', 'i');
        //str = str.replace(reg, '%2F');

        //alert(str);
        return str;
    }

    // 3 врапера 
    function xshow(el){
        //Element.show(el);
        //$(el).setOpacity(1);
        if (!$(el))
        {
            alert("xshow. Object not found:" + el);
        }
        $(el).setStyle('display', 'block');
    }

    function xhide(el){
        //Element.hide(el);
        //$(el).setOpacity(0);
        if (!$(el))
        {
            alert("xhide. Object not found:" + el);
        }
        $(el).setStyle('display', 'none');
    }

    function xtoggle(el){
        if (!$(el))
        {
            alert("xtoggle. Object not found:" + el);
        }
        if ($(el).getStyle('display') == 'none') $(el).setStyle('display', 'block'); else $(el).setStyle('display', 'none');
    }

    // "loading..." block
    var showLoading = false;
    var periodical;

    /**
     *  Инициализация блока лоадинг. и показ блока. Для пока вызывать именно этот метод.
     *
     *
     */
    var initAd = function()
    {
        //$('systemWorking').setOpacity(1);
        xshow('systemWorking');
        showLoading = true;
        showAd();
        periodical = showAd.periodical(100);
    }
    /**
     *  Показ блока лоадинг. Вызывается из initAd();
     *
     *
     */
    var showAd = function()
    {
        //status="11111";
        if (showLoading){
            //$('systemWorking').top = window.getScrollTop+20;
            $('systemWorking').setStyle('top', window.getScrollTop()+20);
            //setTimeout("showAd()", 100);
        }
        else
        {
            $clear(periodical);
        }
    }
    /**
     *  Сокрытие блока лоадинг
     *
     *
     */
    var closeAd = function()
    {
        //$('systemWorking').setOpacity(0);
        xhide('systemWorking');
        showLoading = false;
        $clear(periodical);
    }
    /**
     *  Сокрытие блока лоадинг
     *
     *
     */
    var fail = function(t)
    {
        //$('systemWorking').setHTML = Object.keys(t)//'Error!';
        $('systemWorking').setHTML('Error!');
        //showLoading = false;
        //$clear(periodical);
    }
    // end of "loading..." block


    /**
     *  Привязка событий к действиям пользователя
     *
     *
     */
    var bindLoadEvents = function()
    {
        BindList('.menu-toggler', menulist);
        BindList('.menu-toggler2', menulist2);
    }
    addDOMLoadEvent(bindLoadEvents);


    var MenuItem = new Class({
        initialize:function(object_id)
        {
            this.object_id = object_id;
            //this.slide_obj = new Fx.Slide('menu-level2-' + object_id);
        },

        send: function()
        {
            //this.slide_obj.toggle();
            xtoggle('menu-level2-' + this.object_id)
            img_obj = $('menu-toggler-' + this.object_id);
            img_obj.src = img_obj.src.indexOf('right') > 0 ? "/img/menuarrowdown.gif" : "/img/menuarrowright.gif";

            return false;
        }
    });
    menulist = new ListClass('click', MenuItem);
    menulist2 = new ListClass('click', MenuItem);





var strToJson = function($str)
{
    return eval('(' + $str + ')');
}

var clear_select = function(id)
{
    select = $(id);

    if (select)
    {
        options = select.options;
        for ( i = options.length; i >= 0; i--) 
        { 
            options[i] = null; 
        }
    }
}

var fill_select = function(id, json_arr, first_option)
{
    sel = $(id);
    if (sel != null && json_arr != null)    
    {
        clear_select(sel);
    
        start_index = 0;
        if (first_option != null)
        {
            sel.options[0]  = new Option(first_option, "0");
            start_index = 1;
        }

        for (i = start_index; i <= json_arr.length; i++)
        {
            el = json_arr[i-1];
            sel.options[i]  = new Option(el.name, el.id);
        }

        sel.disabled = false;
    }
}

var hide_element = function(id)
{
    el = $(id);

    if (el)
    {
        el.style.display    = "none";
        el.style.visibility = "hidden";
    }
}

var show_element = function(id)
{
    el = $(id);

    if (el)
    {
        el.style.display    = "";
        el.style.visibility = "visible";
    }
}

var protect_email = function(address, domain)
{
    var href ='&#109;&#97;&#105;&#108;&#116;&#111;&#58;' + address + '&#64;' + domain;
    document.write('<a href="' + href + '" target="_blank">' + address + '&#64;' + domain + '</a>');
}

function show_large(url)
{
    var width       = 800;
    var height      = 800;
    
    var winwidth    = screen.availWidth; 
    var winheight   = screen.availHeight;
    var left        = (winwidth - width)/2;
    var top         = (winheight - height)/2;
    var version     = parseInt(navigator.appVersion);

    if (navigator.appName == "NetScape") { if (version <= 4) { widh = widh + 150; } }

    window.open(url, 'edit_photos', 'left=' + left + ', top=' + top + ', width=' + width + ', height=' + height + ', scrollbars=1');
}



////////////////////// login

function logon()
{
    var url     = "/user/account/logon/"
    var data    = "";

    data = data + ($('contact') != null ? 'contact=' + $('contact').value + '&' : "");
    data = data + ($('pass')    != null ? 'pass=' + $('pass').value + '&' : "");    
    data = data + ($('captcha') != null ? 'captcha=' + $('captcha').value + '&' : "");  

    var myAjax  = new Ajax(url, {onSuccess: bind, onFailure: fail}).request(data); 

    return false;
}
    
function bind(json)
{
    json         = strToJson(json);

    var message  = json.message;
    var redirect = json.redirect;
    var err_code = json.err_code;

    if (message != '')
    {
        if ($('login_msg') != null)
        {
            $('login_msg').setHTML(message);
        }
    }
    else
    {
        if (redirect != null)
        {
            redirect_href = (redirect == '/' ? location.href : '/' + redirect);
            location.replace(redirect_href);
        }
    }

    return false;
}



/* start comments */

function save_comment(param_comment_id)
{
    var_comment_text    = $('comment_text' + param_comment_id).value;
    var_data            = 'comment_id=' + param_comment_id + '&comment_text=' + var_comment_text;

    var myAjax  = new Ajax('/comments/main/savecomment/', {onComplete: bind_comment_object, onFailure: fail}).request(var_data); 
}

function get_comment_object(param_comment_id, param_comment_action)
{    
    xhide('answer' + param_comment_id);

    var_data    = 'comment_id=' + param_comment_id + '&comment_action=' + param_comment_action;
    var myAjax  = new Ajax('/comments/main/getcommentobject/', {onComplete: bind_comment_object, onFailure: fail}).request(var_data);
}

function bind_comment_object(json)
{
    json = strToJson(json);

    if (json.error == '')
    {
        $('commenttext' + json.comment_id).innerHTML = json.content;
    }

    if (json.comment_action == "view")
    {
        xshow('answer' + json.comment_id);    
    }
}




function get_comment_answer_form(param_comment_id)
{    
    xhide('answer' + param_comment_id);

    var_data    = 'comment_id=' + param_comment_id;
    var myAjax  = new Ajax('/comments/main/getanswerform/', {onComplete: bind_answer_form, onFailure: fail}).request(var_data);
}

function bind_answer_form(json)
{
    json = strToJson(json);

    if (json.error == '')
    {
        $('answerform' + json.comment_id).innerHTML = json.content;
    }
}

function clear_comment_answer_form(param_comment_id)
{
    xshow('answer' + param_comment_id);
    $('answerform' + param_comment_id).innerHTML = '';
}

function post_comment(param_parent_id)
{
    var_comment_text    = $('answer_text' + param_parent_id).value;        
    var_data            = 'parent_id=' + param_parent_id + '&comment_text=' + var_comment_text;

    var myAjax  = new Ajax('/comments/main/postcomment/', {onComplete: bind_answer_post, onFailure: fail}).request(var_data); 
}

function bind_answer_post(json)
{
    json = strToJson(json);

    if (json.error == '')
    {
        $('answerform' + json.comment_id).innerHTML = '';
        $('comment' + json.comment_id).innerHTML += json.content;
    }
}


/* end comments */


function bind_event()
{
    if ($('btnLogin'))
    {
        $('btnLogin').addEvent('click', function(){ return logon();});
    }
}

addDOMLoadEvent(bind_event);

