$(function () {
    var toolbar = new PICSA.Toolbar("#toolbar", PICSA.cfg);
    new PICSA.Feedback("#feedback", "#feedback-button");

    toolbar.attachObserver("zoom", function (data) {
        if(PICSA.Canvas) PICSA.Canvas.changeZoom(data);
        if(PICSA.ACanvas) PICSA.ACanvas.changeZoom(data);
        $.cookies.set("scale", data);
    }).attachObserver("arrange", function () {
        if(PICSA.Canvas) PICSA.Canvas.alignToGrid();
        if(PICSA.ACanvas) PICSA.ACanvas.alignToGrid();
    }).attachObserver("stick", function (data) {
        if(PICSA.Canvas) PICSA.Canvas.STICK = data;
        if(PICSA.ACanvas) PICSA.ACanvas.STICK = data;
        $.cookies.set("stick", data);
    });

    var scale = $.cookies.get("scale") || 1.0;
    toolbar.notify("zoom", scale);
    if(toolbar.scaleSlider){
        toolbar.scaleSlider.setValue(scale);
        toolbar.slider.setValue(scale);
    }

    var stick = $.cookies.get("stick") || true;
    toolbar.notify("stick", stick=='true');
    if(toolbar.stick){
        if(stick=="true"){
            toolbar.stick.press();
        }else{
            toolbar.stick.release();
        }
    }

    if(PICSA.Canvas && toolbar.album_button){
        var pos = parseInt($.cookies.get("scroll")); //положение скролл-галереи альбомов
        if(pos){
            $('#toolbar #albums ul').css("left", pos);
        }

        PICSA.Canvas.attachObserver("cover", function(data){ // меняем обложку альбома в верхней панели
            $('#toolbar #albums ul div.holder.'+data.album_id+' img').attr({'src': data.src});
        });

        $("#photos .album-drop").droppable({ // раскрываем панель альбомов
            'accept': '.photo',
            'over': function(e, ui){
                if(!toolbar.album_button.isMenu()){
                    toolbar.album_button.showMenu();
                }
            },
            'tolerance': 'touch'
        });
    }

    $(document).click(function(e){
        var parents = $(e.target).parents('.btn-menu');

        if(parents.length == 0){  //у мишени нет родителя с классом .btn-menu
            $('#toolbar .buttons .btn-menu').removeClass('btn-menu');
        }
    });

    initGrowl();
});

jQuery.fn.centering = function () {
    return this.each(function () {
        var offset = jQuery(this).offset(),
            w = jQuery(this).width(),
            h = jQuery(this).height();
        jQuery(this).css({
            'position': 'absolute',
            'width': w,
            'height': h,
            'top': parseInt(jQuery(window).scrollTop() - offset.top +
                     (jQuery(window).height() - h) / 2, 10),
            'left': parseInt(jQuery(window).scrollLeft() - offset.left +
                     (jQuery(window).width() - w) / 2, 10)
        });
    });
};

$.fn.Editor = function(url, callback){
    var root = this;
    
    root.addClass("editor")
        .click(function () {
            var p = $(this), lastVal = p.text();

            var input = $("<input class='edit' type='text' />")
                        .css({'left':p.position().left, 'top':p.position().top, 'width':p.width()+60, 'margin-bottom':20});

            p.addClass("hidden").after(input);

            $("input.edit", this.parentNode)
                .bind("blur", function changeTitle() {

                    var curVal = $(this).val();
                    p.html(curVal).removeClass("hidden");
                    $(this).remove();
                    if (lastVal !== curVal) {
                        $.post(url, {'name': curVal}, function (resp) {
                            callback(resp);
                        }, "json");
                    }
                })
                .bind("keypress", function (e) {
                    if (e.which == 13) {
                       $(this).blur();
                    }
                })
                .val(p.text()).focus();

            return false;
        });
}

$.fn.clearForm = function() {
    return this.each(function() {
        var type = this.type, tag = this.tagName.toLowerCase();
        if (tag == 'form')
            return $(':input',this).clearForm();
        if (type == 'text' || type == 'password' || tag == 'textarea')
            this.value = '';
        else if (type == 'checkbox' || type == 'radio')
            this.checked = false;
        else if (tag == 'select')
        this.selectedIndex = -1;
    });
};

initLivePage = function(data){
    var items = data;
    var cur_picture = 0;

    var shiftNewPicture = function() {
        var item = items[cur_picture];
        cur_picture++;

        if(item){
            PICSA.Canvas.CURCOLUMN = PICSA.Canvas.safeShiftColumn(item, true);
            PICSA.Canvas.incrementColumn();
        }else{
            $.getJSON('/pictures/ll', {'r': parseInt(1e8*Math.random())}, function (data) {
                if(data){
                    items = data;
                    cur_picture = 0;
                }
            });
        }
        setTimeout(shiftNewPicture, 5000);
    }
    setTimeout(shiftNewPicture, 5000);
}

var initGrowl = function(){
  $.growl.settings.displayTimeout = 10000;
  $.growl.settings.dockCss.width = '250px';
  $.growl.settings.dockCss.top = '30px';

  $.growl.settings.noticeTemplate = ''
	+ '<table id="growl" width="250" border="0" cellpadding="0" cellspacing="0">'
	+ '	<tr>'
	+ '		<td class="top" style="">'
	//+ '			<img src="%image%" style="max-width: 25px; max-height: 25px; text-align: center; margin-left: 19px; margin-top: 19px;" />'
	+ '			<h1 style="font-size: 14px; margin: 0pt; margin-left: 20px; margin-bottom: 10px; display: inline;">%title%</h1>'
	+ '		</td>'
	+ '	</tr>'
	+ '	<tr>'
	+ '		<td class="center" style="">'
	+ '			<p style="margin: 20px;">%message%</p>'
	+ '		</td>'
	+ '	</tr>'
	+ '	<tr>'
	+ '	<td class="bottom" style="" valign="top" align="right" >'
	+ '			<a style="margin-right: 45px; font-size: 10px; color: #fff; text-align: right;" href="" onclick="return false;" rel="close">Закрыть</a>'
	+ '		</td>'
	+ '	</tr>'
	+ '</table>';

//$.growl.settings.noticeTemplate = ''
//  + '<div>'
//  + '<div style="float: right; background-image: url(../images/dm_top.png); position: relative; width: 259px; height: 16px; margin: 0pt;"></div>'
//  + '<div style="float: right; background-image: url(../images/dm_repeat.png); position: relative; display: block; color: #ffffff; font-family: Arial; font-size: 12px; line-height: 14px; width: 259px; margin: 0pt;">'
//  + '  <img style="margin: 14px; margin-top: 0px; float: left;" src="%image%" />'
//  + '  <h3 style="margin: 0pt; margin-left: 77px; padding-bottom: 10px; font-size: 13px;">%title%</h3>'
//  + '  <p style="margin: 0pt 14px; margin-left: 77px; font-size: 12px;">%message%</p>'
//  + '</div>'
//  + '<div style="float: right; background-image: url(../images/dm_bottom.png); position: relative; width: 259px; height: 16px; margin-bottom: 10px;"></div>'
//  + '</div>';

  $.growl.settings.noticeCss = {
    position: 'relative'
  };
}
