(function($) {
    if ($.browser.mozilla) {
        $.fn.disableTextSelect = function() {
            return this.each(function() {
                $(this).css({
                    'MozUserSelect' : 'none'
                });
            });
        };
        $.fn.enableTextSelect = function() {
            return this.each(function() {
                $(this).css({
                    'MozUserSelect' : ''
                });
            });
        };
    } else if ($.browser.msie) {
        $.fn.disableTextSelect = function() {
            return this.each(function() {
                $(this).bind('selectstart.disableTextSelect', function() {
                    return false;
                });
            });
        };
        $.fn.enableTextSelect = function() {
            return this.each(function() {
                $(this).unbind('selectstart.disableTextSelect');
            });
        };
    } else {
        $.fn.disableTextSelect = function() {
            return this.each(function() {
                $(this).bind('mousedown.disableTextSelect', function() {
                    return false;
                });
            });
        };
        $.fn.enableTextSelect = function() {
            return this.each(function() {
                $(this).unbind('mousedown.disableTextSelect');
            });
        };
    }
})(jQuery);

function absPosition(obj)
{
    var x = y = 0;
    
    while(obj)
    {
        x += obj.offsetLeft;
        y += obj.offsetTop;
        obj = obj.offsetParent;
    }
    
    return {x:x, y:y};
}

function str_replace(search, replace, subject)
{
    return subject.split(search).join(replace);
}

function go_(link)
{
    if ( link != document.location )
    {
        window.location.href = link;
    }
}

function isset(name)
{
    return typeof name != "undefined";
}

$.fn.hoverclass = function()
{
    $(this).each( function()
    {
        var hoverclass = $(this).attr("hover");
        
        $(this)
            .bind("mouseover", function()
            {
                $(this).addClass(hoverclass);
            })
            .bind("mouseout", function()
            {
                $(this).removeClass(hoverclass);
            });
    });
    
    return this;
}

$.fn.hoverimg = function()
{   
    $(this).parent().bind("mouseover", function()
    {
        $(".pict_hover").hide();
        $(this).find(".pict").hide();
        $(this).find(".pict_hover").show();
        
    }).bind("mouseout", function()
    {
        $(".pict_hover").hide();
        $(this).find(".pict").show();
    });
    
    return this;
}

$.fn.serverText = function()
{
    var tmp = this;
    
    $(this).each( function()
    {
        if ( $(this).html() == '' )
        {
            $(this).html('...');
        }
    });
    
    $(this).unbind("click").bind("click", function(e)
    {
        if ( !e.ctrlKey && !e.shiftKey )
        {
            var input = $('<textarea class="edit"></textarea>')
                            .css({
                                width: $(this).width()+"px",
                                height: $(this).height()
                                //fontSize: $(this).css("font-size")                            
                            })                        
                            .val(str_replace('<br>', '\n', $(this).html()));
                            
            $(this).html(input).unbind("click");
                    
            input.focus().bind("blur keypress keydown", function(e)
            {            
                if ( ( (e.type == "keypress" || e.type == "keydown") && e.keyCode == 13 && e.ctrlKey ) || e.type == "blur" )
                {
                    $(this).parent().unbind("click");
                    request({path: $(this).parent().attr("servertext"), value: str_replace('\n', '<br>', $(this).val())});
                }
            });
        }
    });
    
    return this;
}

/*
$.fn.drag = function(settings) // handle, padding-left, 0.1
{   
    var obj = $(this);
    var axis = $(this).attr("drag") || 'y';
    var subject = $(this).attr("subject") || $(this).attr("class");
    
    if ( settings == 'remove' )
    {
        $(this).css({"padding-left": "0px"})
        $("."+subject+"_drag").remove();
    }
    else
    {    
        var handle = $('<div class="'+subject+'_drag" style="'+
            'position: absolute;'+
            'margin-left: -15px;'+
            'margin-top: -'+$(this).height()+'px;'+
            'width: 15px;'+
            'height: '+$(this).height()+'px;'+
            'background-color: #dddddd'+
            '"></div>');    
        
        $(this).css({"padding-left": "15px"}).append(handle);
        
        $("."+subject+"_drag").bind("mousedown", function()
        {
            var mousedown = $(this).parent();
            
            $(mousedown).css("background-color", "#eaeaea");        
            $($(this)).css("background-color", "#ccffaa");        
            $("*").disableTextSelect();
            
            $(obj).unbind("mousemove").bind("mousemove", function(e)
            {
                $("html").disableTextSelect();
                s_obj = document.getElementById($(this).attr("id"));
                
                if ( ( axis == 'y' && e.pageY - absPosition(s_obj).y < $(this).height()/2 ) || ( axis == 'x' && e.pageX - absPosition(s_obj).x < $(this).width()/2 ) )
                {
                    $(mousedown).remove();
                    $(this).before($(mousedown));
                    path = subject + "/order/" + $(mousedown).attr("id") + "/" + $(this).attr("id") + "/before";
                }
                else
                {
                    $(mousedown).remove(); 
                    $(this).after($(mousedown));
                    path = subject + "/order/" + $(mousedown).attr("id") + "/" + $(this).attr("id") + "/after";
                }
            });
            
            $("body").unbind("mouseup").bind("mouseup", function(e)
            {                
                if ( mousedown )
                {
                    $(mousedown).css("background-color", "");
                    mousedown = false;
                    $(obj).unbind("mousedown").unbind("mousemove").unbind("mouseenter").unbind("mousemove").drag();
                    $("*").enableTextSelect();
                    request({path: path});
                }
            });
        });    
    }
    
    return this;
}
*/

$.fn.mce = function() // 0.1
{
    $(this).each( function()
    {
        if ( $(this).html() == '' )
        {
            $(this).html('...');
        }
    });
    
    $(this).unbind("click").bind("click", function(e)
    {
        if ( !e.ctrlKey && !e.shiftKey )
        {
            $(".drag_handle").addClass("hidden"); // dnd conflict
            
            var tmp = $(this);
            var backup = $(this).html();
            
            $(this).tinymce(
            {
                script_url: site+'/scripts/tiny_mce/tiny_mce.js',
                width: $(this).width(),
                height: $(this).height()+200,
                theme: "advanced",
                plugins: "images,safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template, typograf",
                theme_advanced_buttons1 : "save,newdocument,|,undo,redo,|,preview,print,|,cut,copy,paste,pastetext,pasteword,|,search,replace,|,formatselect,fontselect,fontsizeselect",
                theme_advanced_buttons2 : "typograf,forecolor,backcolor,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,|,outdent,indent,|,link,unlink,anchor,images,cleanup,code,|,insertdate,inserttime",
                theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,|,cancel",
                theme_advanced_toolbar_location: "top",
                theme_advanced_toolbar_align: "left",
                theme_advanced_statusbar_location: "bottom",
                theme_advanced_resizing: true,
                
                save_onsavecallback: function()
                {
                    request({path: tinyMCE.activeEditor.id, value: tinyMCE.activeEditor.getContent()});                     
                },
                
                save_oncancelcallback: function()
                {
                    tinyMCE.activeEditor.remove();
                    if ( !tinyMCE.activeEditor ) $(".drag_handle").removeClass("hidden"); // dnd conflict
                    $(tmp).html(backup);
                },
                
                relative_urls: false,
                remove_script_host: true,                    
                extended_valid_elements: "tcut",                    
                language: "ru"
            });
        }
    });
    
    return this;    
}

$.fn.form = function () // 1.0
{   
    var form_ = $(this);
    
    $(form_).find("input[type='submit']").bind("click", function()
    {
        var form_data = {};        
        form_data.id = $(form_).attr("id");
        
        $(form_).find("input[p]").each( function()
        {
            form_data[$(this).attr("p")] = $(this).attr("value");
        });
        
        $(form_).find("textarea[p]").each( function()
        {
            form_data[$(this).attr("p")] = $(this).val();
        });
        
        request(form_data);
    });
    
    return this;
}

function request(q)
{    
    $.post(site+'/request.php', {q: $.toJSON(q)}, function (response)
    {   
        apply(eval("("+response+")"));
    });
}

function apply(data)
{
    if ( data )
    {
        if ( data.html )    {$(data.container).html(data.html);}
        if ( data.append )  {$(data.container).append(data.append);}
        if ( data.prepend ) {$(data.container).prepend(data.prepend);}
        if ( data.before )  {$(data.container).before(data.before);}
        if ( data.after )   {$(data.container).after(data.after);}        
        
        if ( data.script )  eval(data.script);
    }
}

function confirm_(q)
{
    $("a.confirmationbox").click();
    
    $("#confirm").unbind("click").bind("click", function()
    {
        request(q);
        $.fancybox.close();
    });
    
    $("#discard").unbind("click").bind("click", function()
    {
        $.fancybox.close();
    });
}

$.fn.drag = function()
{    
    $(this).tableDnD(
    {
        onDragClass: "drag_highlight",
        dragHandle: "drag_handle",
        
        onDrop: function(table, row) 
        {
            var rows = table.tBodies[0].rows;
            var w = "";
            
            for ( var i=0; i<rows.length; i++ )
            {
                w += rows[i].id + ";";
            }
            
            request({path: $(table).attr("drag")+'/renumber/'+w, row: row.id});
        }
    });
}

function binds(context)
{
    // load virtual blocks (?)
    //$("[load]", context).each( function(){request({path: $(this).attr("load")});});
    
    $("a.licenses_a").fancybox({
        speedIn: 100,
        speedOut: 100,
        changeSpeed: 100,
        titleFormat : function(title, currentArray, currentIndex, currentOpts) 
        {
            if ( title )
            {
                return "<div style='background-color: #000000; padding: 5px'>"+title+"</div>";
            }
        }
    });
    
    $("a.photos").fancybox({
        speedIn: 100,
        speedOut: 100,
        changeSpeed: 100,
        titleFormat : function(title, currentArray, currentIndex, currentOpts) 
        {
            if ( title )
            {
                return "<div style='background-color: #000000; padding: 5px'>"+title+"</div>";
            }
        }
    });
    
    $("input[upload]", context).each(function()
    {
        var path = $(this).attr("upload");
        var multi = $(this).attr("multi") || false;
        
        $(this).uploadify(
        {
            'uploader'          : site+'/scripts/uploadify.swf',
            'script'            : site+'/upload.php',
            'auto'              : true,
            'scriptData'        : {path: path, sessid: sessid},
            'multi'             : multi,
            
            onComplete: function(event, queueID, fileObj, response, data)
            {
                if (response) { apply(eval("("+response+")")); }
            }
        });
    });
    
    $("[path]", context)     .unbind("click").bind("click", function(){request({path: $(this).attr("path")});});
    $("[link]", context)     .unbind("click").bind("click", function(){go_($(this).attr("link"));});
    $("[toggle]", context)   .unbind("click").bind("click", function(){$("#"+$(this).attr("toggle")).toggle();});    
    $("[confirm]", context)  .unbind("click").bind("click", function(){confirm_({path: $(this).attr("confirm")});});
    
    $("[hover]", context).hoverclass();
    
    if ( auth == 1 )
    {
        $("[servertext]", context).serverText();
        $("[mce]").mce(); // CONTEXT NOT WORK !? why
        $("[drag]").drag();
    }
    
    $("[calendar]", context).each(function()
    {
        var tmp = $(this);
        
        $(this).DatePicker(
        {
            extraHeight: 10,
            date: $(tmp).html(),
            current: $(tmp).html(),
            
            onBeforeShow: function()
            {
                $(this).bind("contextmenu", function ()
                {
                    $(tmp).DatePickerHide();
                    return false;
                });
            }, 
            
            onChange: function(formated)
            {
                request({path: $(tmp).attr("calendar"), value: formated});
            }
        });
    });
    
    $(".form").each(function(){$(this).form();});
    
    $("a.confirmationbox", context).fancybox();
    $("a.loginbox", context).fancybox();
    $("a.metabox", context).fancybox();
    
    $("a.confirmationbox", context).fancybox();
    $("a.loginbox", context).fancybox();
    $("a.metabox", context).fancybox();
    
    $("a.imagebox").fancybox({
        onClosed: function()
        {
            //binds("#images");
        }
    });    
    
       
}

var sort_block = false;

$(document).ready(function()
{       
    binds(document);
    
    /*$("#content").dropShadow(
    {
        left    : 4,
        top     : 0,
        blur    : 5,
        opacity : 0.6,
        color   : "black",
        swap    : false
    });*/
    
    if ( auth == 1 )
    {
        $("#images").sortable({
            start: function(event, ui)
            {
                sort_block = true;
            },
            update: function(event, ui)
            {
                var sequence = '';
                $(".image").each(function()
                {
                    sequence += $(this).attr("image_id") + ";";
                });
                
                request({path: 'gallery/renumber/'+sequence});
            }
        });
        
        $("#images").disableSelection();
        
        $(".image")    
            .unbind("click").bind("click", function(e)
            {
                if ( e.ctrlKey )
                {
                    $(this).toggleClass("select");
                }
                else
                {
                    if ( sort_block == false )
                    {
                        if ( !($(this).hasClass("select")) ) $(this).addClass("select");
                
                        var selection = '';            
                        $(".image.select").each( function()
                        {
                            selection = selection + $(this).attr("image_id") + ';';
                        });
                        
                        request({path: 'gallery/cp/'+selection});  
                    }
                }
                
                return false;
            }); 
    }
    
    $("#index_links_equipment, #index_links_engineering")
        .corner("7px")
        .bind("mouseover", function()
        {
            $(this).parent().find("h2").addClass("a");
            $(this).addClass("index_links_equipment_hover");
        })
        .bind("mouseout", function()
        {
            $(this).parent().find("h2").removeClass("ul");
        });
    
    $(document).bind("keypress keydown", function(e)
    {
        if ( e.keyCode == "0x78" )
        {
            if (e.ctrlKey)
            {                
                $("a.loginbox").click();
                $("[p=login], #logout_submit").focus();
                
                $("#login, #pass").unbind("keypress keydown").bind("keypress keydown", function(e)
                {
                    if ( e.keyCode == "0x0D" )
                    {
                        $("#login_submit").click();
                    }
                });
            }
            else
            {
                $("a.metabox").click();
            }
        }
    });
});

