/**
 * aka void main()
 */
$(function() {
    Alga.initAjax();
    Alga.LeftMenu.init();

    if (Alga.interfaceName === 'subscribe_form'){
        FlexitesSubscribe.Form('subscribe-form');
    }
});


/**
 * Глобальный неймспейс
 */
Alga = new Object();

/** @type {Object} неймспейс проекта */
Alga = function(undef) {
    return {
        undefined : undef
    }
}();

//----- Общие настройки---------------------------------------------------------

/** @type {String} url для ajax запроса */
Alga.AJAX_URI = '/json/';

/** @type {Number} Значение прозрачности для оверлея */
Alga.overlayOpacity = 0.6;

/** @type {string} Значение цвета для оверлея */
Alga.overlayColor = "#333333";

/** @type {String} id сессии из командной строки */
Alga.SESS_ID = '';
if (window.location.toString().match(/SESS_ID=(\d+)/))
    Alga.SESS_ID = RegExp.$1;

//------------------------------------------------------------------------------

//----- Общие функции ----------------------------------------------------------

/**
 * Выполняет Ajax запрос с JSON-ответом
 * @param {Object} data Данные
 * @param {Function} handler Обработчик
 */
Alga.getJSON = function(data, handler) {
    if (Alga.SESS_ID)
        data['SESS_ID'] = Alga.SESS_ID;
    $.post(Alga.AJAX_URI, data, handler, 'json');
}

/**
 * Выполняет Ajax запрос с xml-ответом
 * @param {Object} data Данные
 * @param {Function} handler Обработчик
 */
Alga.getXML = function(data, handler) {
    if (Alga.SESS_ID)
        data['SESS_ID'] = Alga.SESS_ID;
    $.post('/ajax/', data, handler, 'xml');
}


/**
 * Настройки для Ajax запросов
 */
Alga.initAjax = function() {
    var $body = $(document.body);
    function waitingState(state) {
        if (state) {
            $body.addClass('waiting');
        } else {
            $body.removeClass('waiting');
        }
    }

    $(document)
        .ajaxStart(function() {
            waitingState(true);
        })
        .ajaxStop(function() {
            waitingState(false);
        })
        .ajaxError(function(event, XMLHttpRequest, ajaxOptions, thrownError) {
            alert('Произошла ошибка при загрузки данных. Попробуйте перезагрузить страницу.');
            waitingState(false);
        });
}

/**
 *  Слой - оверлей
 */
Alga.Overlay = function(){
    var $overlay = null;

    function _show(){
        if (!$overlay){
              $overlay = $(document.createElement('div'))
                         .addClass('overlay')
                         .css({
                              opacity: Alga.overlayOpacity
                         }).hide()
                         .appendTo(document.body);
        }
        $overlay.show();
        if (Browser.isIE6)
            $overlay.css({
                position : 'absolute',
                height : document.body.scrollHeight
            });
    }

    function _hide(){
        $overlay.hide();
    }

    return {
        show: function(){
            _show();
        },
        hide: function(){
            _hide();
        },
        onclick: function(handler){
            $overlay.unbind("click");
            $overlay.click(handler);
        }
    }
}();

Alga.textContent = function(xml) {
    var cnt;
    if (xml.text != undefined) {
      cnt = xml.text;
    } else if (xml.textContent != undefined) {
      cnt = xml.textContent;
    } else {
      cnt=xml.firstChild.nodeValue;
    }
    return cnt;
}

//------------------------------------------------------------------------------

//----- Интерфейсные функции ---------------------------------------------------

Alga.ScrollGallery = function(delay,duration) {
    this.delay = delay || 2000;
    this.duration = duration || 300;
    this.setup();
}

Alga.ScrollGallery.prototype = {
    setup: function() {
        var self = this;
        self.container = $(".scroll-gallery");
        self.items = $(".gallery-items",self.container);
        if(Browser.isIE6){
          self.items.each(function(){
              var $this = $(this).find(".cmt");
              if($this.length>0){
                var span = $(document.createElement("span"))
                              .addClass("ie-bg")
                              .css("height",$this.height()+"px")
                              .appendTo($this.parent())
                $this.addClass("ie-no-bg");
                $this.hover(function(){ $(this.parentNode).find(".ie-bg").addClass("ie-no-transp");  },function(){ $(this.parentNode).find(".ie-bg").removeClass("ie-no-transp"); })
              }
          })
        }
        self.drawNavBar();
        self.goTo(1);
        self.resetTimer();
    },
    resetTimer: function() {
        var self = this;
        if (self.timer) window.clearInterval(self.timer);
        self.timer = window.setInterval(function() { self.goToNext(); }, self.delay);
    },
    drawNavBar: function() {
        var self = this;
        self.navBar = $("<div class='gallery-nav'></div>").appendTo(self.container);
        self.imageCount = 0;
        self.currentPos = 0;
        $("img",self.items).each(function(i) {
            var j = i + 1;
            if (!self.imageWidth) {
                self.imageWidth = this.width;
            }
            $("<span class='"+j+"'>"+j+"</span>").click(function() { self.goTo(this.className*1,true); }).appendTo(self.navBar);
            self.imageCount ++;
        });

        $("<span class='gallery-arr ga-l'></span>")
            .click(function(){ self.goToPrev(true); })
            .appendTo(self.container);

        $("<span class='gallery-arr ga-r'></span>")
            .click(function(){ self.goToNext(true); })
            .appendTo(self.container);

        //self.items.width(self.imageWidth);
    },
    goToNext: function(reset) {
        var self = this;
        var k = self.currentPos + 1;
        if (k > self.imageCount) {
            k = 1;
        }
        self.goTo(k,reset);
    },
    goToPrev: function(reset) {
        var self = this;
        var k = self.currentPos - 1;
        if (k <= 0) {
            k = self.imageCount;
        }
        self.goTo(k,reset);
    },
    goTo: function(k,reset) {
        var self = this;
        if (k != self.currentPos) {
            $(".active", self.navBar).removeClass("active");
            $("."+k, self.navBar).addClass("active");
            self.currentPos = k;
            self.items.stop(true,true).animate({scrollLeft: (k - 1)*self.imageWidth}, self.duration);
            if (reset) {
              self.resetTimer();
            }
        }
    }
}

/* Левое меню */
Alga.LeftMenu = function(){

    function _click(el){
        var $el = $(el);
        var $list = $el.parent().parent().find(".smenu");
        if($el.parent().parent().hasClass("mi-h")){
            $list.slideDown(400,function(){ $list.parent().removeClass("mi-h"); });
        }else{
            $list.slideUp(300,function(){ $list.parent().addClass("mi-h"); });
        }
    }

    return {
        init: function(){
            $("#left .menu .mi").each(function(){
                var $this = $(this);
                $this.find(".mia").click(function(){ _click(this); });
                if(!$this.hasClass("miact")){ $this.addClass("mi-h"); }
            });
        }
    }
}();

/* Показ картинки */
function showFBox(link) {
    if ((link) && (link.href)) {
        if (!link.__fbox) {
            link.__fbox = new FBox({
                animation: true,
                showOverlay: true,
                useLoaderAnim: false,
                loaderParams: {
                    animatioLength: 400,
                    animationStep: 50,
                    animationTime: 100
                },
                image: {
                    src: link.href,
                    comment: link.title
                },
                constraints: {
                    minWidth: 300,
                    minHeight: 300,
                    maxWidth: 750,
                    maxHeight: 550
                }
            })
        }
        link.__fbox.show();
        return false;
    }
    return true;
}
window.showFBox = showFBox;

/* ajax галерея */
var bigAjaxGallery = null;
function showAjaxGallery(el) {
    if (!bigAjaxGallery) {
        var gallery_id = el.href.split("?")[1].split("=")[1];
        bigAjaxGallery = new FBox({
            animation: true,
            imagesList: true,
            imagesListWidth: 80,
            useLoaderAnim: true,
            loaderParams: {
                animatioLength: 400,
                animationStep: 50,
                animationTime: 100
            },
            showOverlay: true,
            navigationButtons: true,
            navigationButtonsHover: false,
            ajax: {
                url: '/ajax/',
                iface: 'gallery',
                gallery_id: gallery_id
            },
            constraints: {
                minWidth: 470,
                minHeight: 465,
                maxWidth: 750,
                maxHeight: 550
            }
        });
    }
    bigAjaxGallery.show();
}
window.showAjaxGallery = showAjaxGallery;

function offset(el, to) {
    var tEl = to || document.documentElement;
    var left = 0;
    var top = 0;
    var sel = el;
    do {
        left += sel.offsetLeft;
        top += sel.offsetTop;
    } while ((sel = sel.parentNode) && (sel != tEl));
    return { left: left, top: top };
}


function multipleGalleries(){
    this.name = "MultiGallery";
    this.gallery = null;
    this.start();
}

/* Каталог галерей */
multipleGalleries.prototype = {
    start: function(){
        var self = this;
        $(".galleries .g-item").each(function(){
            var links = $(this).find("a.shg");
            if(links.length>0){
                $(links[0]).click(function(){
                    var gallery_id = this.href.split("?")[1].split("=")[1];
                    if(self.gallery){ self.gallery = null };
                    self.gallery = new FBox({
                            animation: true,
                            imagesList: true,
                            imagesListWidth: 80,
                            useLoaderAnim: true,
                            loaderParams: {
                                animatioLength: 400,
                                animationStep: 50,
                                animationTime: 100
                            },
                            showOverlay: true,
                            navigationButtons: true,
                            navigationButtonsHover: false,
                            ajax: {
                                url: '/ajax/',
                                iface: 'gallery',
                                gallery_id: gallery_id
                            },
                            constraints: {
                                minWidth: 470,
                                minHeight: 465,
                                maxWidth: 750,
                                maxHeight: 550
                            }
                        });
                    self.gallery.show();
                    return false;
                });
                $(links[1]).click(function(){
                    $(links[0]).trigger('click');
                    return false;
                })
            }
        });
    }
}
window.multipleGalleries = multipleGalleries;

/* Галерея в произвольном месте */
function Gallery(el,id){
    if((el)&&(id)){
        if(!el.__gallery){
            el.__gallery = new FBox({
                animation: true,
                imagesList: true,
                imagesListWidth: 80,
                useLoaderAnim: true,
                loaderParams: {
                    animatioLength: 400,
                    animationStep: 50,
                    animationTime: 100
                },
                showOverlay: true,
                navigationButtons: true,
                navigationButtonsHover: false,
                ajax: {
                    url: '/ajax/',
                    iface: 'gallery',
                    gallery_id: id
                },
                constraints: {
                    minWidth: 470,
                    minHeight: 465,
                    maxWidth: 750,
                    maxHeight: 550
                }
            });
        }
        el.__gallery.show();
        return false;
    }
    return true;
}
window.Gallery = Gallery;


FlexitesSubscribe = new Object();

FlexitesSubscribe.Form = function(formId) {

    var $form = $(document.getElementById(formId));

    if (!$form.length)
        return;

    var $methodRadio = $form.find('input[name=_action]');

    function update() {
        var action = '';
        for (var i = 0; $methodRadio.length; i++) {
            var inp = $methodRadio.get(i);
            if (inp.checked) {
                action = inp.value;
                break;
            }
        }
        if (action == 'unsubscribe') {
            $form.find('.attr-subscribe-name, .attr-subscribe-groups').hide();
        } else {
            $form.find('.attr-subscribe-name, .attr-subscribe-groups').show();
        }
    }

    $methodRadio.click(function() {
        update();
    });
    update();

}


/* ------------------------------- */

//------------------------------------------------------------------------------
