var ping;
var popup_height;
var popup_width;
var popups = [];

jQuery.fn.outerHTML = function(s) {
    return (s)
    ? this.before(s).remove()
    : jQuery("<p>").append(this.eq(0).clone()).html();
}

function jAttributeCheckValue(attribute, resource, value)
{
    var data = {};    
    
    if(value.length > 0) {
        data["mode"] = "validate";
        data["attribute"] = attribute;
        data["value"] = value;

        $.post(
            "/"+resource,
            data,
            function(result) {
                result = ltrim(result);
                if(result.substr(0,9) != "<!DOCTYPE")
                    jPopupError(attribute, result);
            }
        );
    }
}

function jAttributeShow(attribute)
{
  attr = $("#"+attribute+"_attribute").parent().parent();
      attr.prev().css("display","");
      attr.css("display","");
      attr.next().css("display","");
      attr.next().next().css("display","");
}

function jAttributeHide(attribute)
{
  attr = $("#"+attribute+"_attribute").parent().parent();
      attr.prev().css("display","none");
      attr.css("display","none");
      attr.next().css("display","none");
      attr.next().next().css("display","none");
}

function jCoverFormAttribute(attribute)
{
    attr = $("#"+attribute);

    if(attr) {
        attr.attr("disabled", "disabled");
        
        var pos = absPosition(attr[0]);
        var w = attr.width();
        var h = attr.height();
        
        $("<div id='"+attribute+"_cover'></div>")
            .addClass("cover_box_form")
            .css("top", pos.y)
            .css("left", pos.x)
            .width(w)
            .height(h)
            .appendTo("body")
        ;
    }
}

function jUnCoverFormAttribute(attribute)
{
    $("div#"+attribute+"_cover").remove();        
    $("#"+attribute).removeAttr("disabled");
}

function jUnCoverAll()
{
    $("div.cover_box_form").remove();
}

function jPopupNavigateWait()
{
    attr = $("div#main-inner");
    if(!attr[0])
      attr = $("div#main-popup-inner");
    
    if(attr[0]) {
        var pos = absPosition(attr[0]);
        var w = attr.width();
        var h = attr.height();
        var yd = 0;

        if($.browser.msie) {
            yd = 9;
            var iframe = $("<iframe src=\"/blank.html\" border=0></iframe>")
                .addClass("cover_box")
                .css("position", "absolute")
                .css("top", pos.y+yd)
                .css("left", pos.x)
                .width(w)
                .height(h-yd)
                .css("opacity", 0)
                .appendTo("body")
            ;
        }

        $("<div></div>")
            .addClass("cover_box")
            .css("top", pos.y+yd)
            .css("left", pos.x)
            .width(w)
            .height(h-yd)
            .appendTo("body")
        ;
        
        $("<div></div>")
            .html("<img src='/img/wait.gif'/>")
            .addClass("wait_box")
            .css("top", pos.y+h/2)
            .css("left", pos.x+w/2-16)
            .width(32)
            .height(32)
            .appendTo("body")
        ;
    }
}

function jPopupRemovingOn()
{
    $("#site")
        .unbind("click").click(jPopupRemove)
        .unbind("keydown").keydown(jPopupRemove)
    ;
}

function jPopupRemovingOff()
{
    $("#site").unbind("click").unbind("keydown");
}

function jPopupRemove()
{
    $(".popup_error").remove();
    $(".hint").remove();
    $(".calendar").remove();
    
    if($.browser.msie)
        $("select[temporally_hidden=true]").css("visibility", "visible").removeAttr("temporally_hidden");
}

function jPopupError(attribute, error)
{
    if(trim(error) != "") {
        var attr = $("#"+attribute+"_attribute");
        if(attr) {
            jPopupRemovingOff();
        
            var pos = absPosition(attr[0]);
            var w = getinsideWindowWidth()-pos.x-50-26-getinsideWindowWidth()/8;
            
            if(w > 300)
              if(error.length < 60)
                  w = w/3;
              else if(error.length < 120)
                  w = 2*w/3;
                
            $("#"+attribute+"_error_box").remove();
            
            if($.browser.msie)
                var iframe = $("<iframe src=\"/blank.html\" border=0></iframe>")
                    .addClass("popup_error")
                    .css("position", "absolute")
                    .css("top", pos.y-15)
                    .css("left", pos.x+50)
                    .width(w+10)
                    .height(40)
                    .css("opacity", 0)
                    .appendTo("body")
                ;
            
            var div = $("<div id='"+attribute+"_error_box'></div>")
                .html(error)
                .addClass("popup_error")
                .css("position", "absolute")
                .css("top", pos.y-15)
                .css("left", pos.x+50)
                .width(w)
                .css("opacity", 0)
                .appendTo("body")
                .animate({opacity: "1"}, "fast", "", function(){jPopupRemovingOn();})
            ;
            
            var h = parseInt(div.css("height"))
               +parseInt(div.css("padding-top"))
               +parseInt(div.css("padding-bottom"))
               +parseInt(div.css("margin-top"))
               +parseInt(div.css("margin-bottom"))
            ;
            
            if(h && attr.css("height") == "0px")
                attr.css("height", h+"px");
        }
    }
}

function jPopupMessageRemove(designation)
{
    $("#"+designation).remove();
    $(".cover_box").remove();
}

function jPopupMessage(title, designation, message, buttons, captions)
{
    if(trim(message) != "") {
        jPopupRemovingOff();

        $("div#"+designation).remove();
        $(".cover_box").remove();

        attr = $("div#main-inner");
        
        if(attr) {
            var pos = absPosition(attr[0]);
            var w = attr.width();
            var h = attr.height();
            var yd = 0;
            
            if($.browser.msie) {
                yd = 9;
                var iframe = $("<iframe src=\"/blank.html\" border=0></iframe>")
                    .addClass("cover_box")
                    .css("position", "absolute")
                    .css("top", pos.y+yd)
                    .css("left", pos.x)
                    .width(w)
                    .height(h-yd)
                    .css("opacity", 0)
                    .appendTo("body")
                ;
            }
            
            $("<div></div>")
                .addClass("cover_box")
                .css("top", pos.y+yd)
                .css("left", pos.x)
                .width(w)
                .height(h-yd)
                .appendTo("body")
            ;
        }
        
        var div = $("<div id='"+designation+"'><div id=\"title\"></div><div id=\"message\"></div><div id=\"buttons\"></div></div>")
            .addClass("popup_message")
            .css("position", "absolute")
            .css("opacity", 0)
            .width(getinsideWindowWidth()/2)
            .appendTo("body")
        ;
        
        $("#title", div).html(title);
        $("#message", div).html(message);
        
        var buttons_arr  = splitValue(buttons);
        var captions_arr = splitValue(captions);
        var buttons_html = "";
        
        for(var i=0; i<buttons_arr.length; i++)
            buttons_html+= "<span class=\"popup_button\" id=\""+buttons_arr[i]+"\">"+captions_arr[i]+"</span>";
            
        $("#buttons", div).html(buttons_html);
    
        var x = getinsideWindowWidth()/2-div.width()/2;
        
        if(attr)
            var y = pos.y+h/2-div.height()/2;
        else
            var y = getinsideWindowHeight()/2-div.height()/2;
        
        div .css("top", y)
            .css("left", x)
            .css("opacity", 1)
        ;
    }
}

function jPopupHint(object, title, description)
{
    if(trim(description) != "") {
        if($(".hint")[0])
            jPopupRemove();
            
        jPopupRemovingOff();
            
        var pos = absPosition(object);
        
        if(pos.x < getinsideWindowWidth()/2) {
            var dx = -65;
            var top_class = "htopl";
        } else {
            var dx = -348+70;
            var top_class = "htopr";
        }
        
        if($.browser.msie)
            var iframe = $("<iframe src=\"/blank.html\" border=0></iframe>")
                .addClass("hint")
                .css("position", "absolute")
                .css("top", pos.y+15)
                .css("left", pos.x+dx+20)
                .width(348)
                .height(0)
                .css("opacity", 0)
                .appendTo("body")
            ;
        
        var div = $("<div></div>")
            .html("<div id=\""+top_class+"\"></div><div id=\"htitle\"><table><tr><td width=\"100%\">"+title+"</td><td><div id=\"hclose\" onclick=\"jPopupRemove();\"></div></td></tr></table></div><div id=\"hline\"><table><tr><td></td></tr></table></div><div id=\"hbody\">"+description+"</div><div id=\"hbottom\"></div>")
            .addClass("hint")
            .css("position", "absolute")
            .css("top", pos.y+15)
            .css("left", pos.x+dx+20)
            .width(348)
            .css("opacity", 0)
            .appendTo("body")
            .animate({opacity: "1"}, "fast", "", function(){jPopupRemovingOn();})
        ;
        
        if($.browser.msie)
            iframe.height(div.height());
    }
}

function jAmountKeyUp(object)
{
    var v = $(object).attr("value");
    if(v) {
        var s = new String(v);
        s = s.replace(/\./g, ",");                    
        
        var t = new String("0123456789,");
        var r = new String;
        for(i=0;i<s.length;i++)
            if(t.indexOf(s.substr(i,1)) >= 0)
                r += s.substr(i,1);
        s = r;            
        
        p = s.indexOf(",");
        if(p >= 0 && p < s.length-3)
            s = s.substr(0, s.length-1);
        
        i = s.indexOf(",")-1;
        if(i < 0)
            i = s.length-1;
        for(c=0;i>=0;i--,c++)
            if(c > 2) {
                s = s.substr(0, i+1)+" "+s.substr(i+1);
                c = 0;
            }
            
        if(s != v)
            $(object).attr("value", s);                
    }
}

function jAmountBlur(object)
{
    var v = $(object).attr("value");
    if(v) {
        var s = new String(v);  
        
        p = s.indexOf(",");
        if(p < 0)
            s += ",";
        p = 2-(s.length-s.indexOf(",")-1);
        for(i=0;i<p;i++)
            s += "0";
                
        if(s != v)
            $(object).attr("value", s);
    }
}

function jStartPing()
{
    ping = setTimeout("jOnPing()", 60000);
}

function jOnPing()
{
    clearTimeout(ping);
    $.post("/index.php", {_ping: "true"}, function(data){
        ping = setTimeout("jOnPing()", 60000);
    });
}

function jCalendarOnClick(inputId, selected, mode)
{
    $("#"+inputId).attr("value", stringDate(selected, mode)).focus().select();
    jPopupRemove();
    
    return false;
}

function jCalendarOnReload(inputId, selected, mode)
{
    $("div.calendar").html(jCalendarContent(inputId, selected, mode));
    
    return false;
}

function jCalendarContent(inputId, selected, mode)
{
    if(!mode)
        mode = 1;

    if(selected == undefined)
        selected = new Date();
    
    var now  = new Date();
    var d    = new Date(selected);    
    var html = new String();
    
    var prev_month = new Date(selected.getFullYear(), selected.getMonth()-1, selected.getDate());
    var next_month = new Date(selected.getFullYear(), selected.getMonth()+1, selected.getDate());
    var prev_year  = new Date(selected.getFullYear()-1, selected.getMonth(), selected.getDate());
    var next_year  = new Date(selected.getFullYear()+1, selected.getMonth(), selected.getDate());
    
    html += "<div id='monthyear'><table><tr>"+
            "<td><a href='#' onclick='return jCalendarOnReload(\""+inputId+"\", parseDate(\""+stringDate(prev_month)+"\"), "+mode+");'>&laquo;</a></td>"+
            "<td>"+getMonth(selected.getMonth())+"</td>"+
            "<td><a href='#' onclick='return jCalendarOnReload(\""+inputId+"\", parseDate(\""+stringDate(next_month)+"\"), "+mode+");'>&raquo;</a></td>"+
            "<td><a href='#' onclick='return jCalendarOnReload(\""+inputId+"\", parseDate(\""+stringDate(prev_year)+"\"), "+mode+");'>&laquo;</a></td>"+
            "<td>"+selected.getFullYear()+"</td>"+
            "<td><a href='#' onclick='return jCalendarOnReload(\""+inputId+"\", parseDate(\""+stringDate(next_year)+"\"), "+mode+");'>&raquo;</a></td>"+
            "</tr></table></div>"
    ;
    
    html += "<div id='week'><table><tr>";
    
    d.setDate(1);
    for(i=0;i<toRussianDay(d.getDay());i++)
        html += "<td></td>";
        
    for(m=d.getMonth(); m == d.getMonth(); d.setDate(d.getDate()+1)) {
        if(d.toDateString() == selected.toDateString())
            td = "<td id='selected'>";
        else if(d.toDateString() == now.toDateString())
            td = "<td id='now'>";
        else if(toRussianDay(d.getDay()) > 4)
            td = "<td id='holiday'>";
        else
            td = "<td>";
        
        html += td+"<a href='#' onclick='return jCalendarOnClick(\""+inputId+"\", parseDate(\""+stringDate(d)+"\"), "+mode+");'>"+d.getDate()+"</a></td>";
        
        if(toRussianDay(d.getDay()) == 6)
            html += "</tr><tr>";
    }    
        
    html += "</tr></table></div>";
    
    return html;
}

function jCalendar(j, selected, mode)
{
    if(!mode)
        mode = 1;

    var pos = absPosition(j[0]);
    
    jPopupRemove();
    jPopupRemovingOff();
    
    if($.browser.msie)
        var iframe = $("<iframe src=\"/blank.html\" border=0></iframe>")
            .addClass("calendar")
            .css("position", "absolute")
            .css("top", pos.y+j.height()+parseInt(j.css("border-top-width"))+parseInt(j.css("border-bottom-width"))+4)
            .css("left", pos.x)
            .width(150)
            .height(150)
            .css("opacity", 0)
            .appendTo("body")
        ;
        
    var div = $("<div></div>")
        .html(jCalendarContent(j.attr("id"), selected, mode))
        .addClass("calendar")
        .css("position", "absolute")
        .css("top", pos.y+j.height()+parseInt(j.css("border-top-width"))+parseInt(j.css("border-bottom-width"))+4)
        .css("left", pos.x)
        .width(150)
        .height(150)
        .css("opacity", 1)
        .appendTo("body")
        .animate({opacity: "1"}, "fast", "", function(){jPopupRemovingOn();})
    ;
}

function jRefreshAttribute(resource, attribute, get)
{
    var post = {};    
    
    post["mode"] = "header";
    post[attribute+"_mode"] = "body";
        
    $.post("/"+resource+get, post, function(data){
        if(data && $("#"+attribute)[0]) {
            setOuterHTML($("#"+attribute)[0], data);
        }
    });
}

function jPopupResource(url, height, width)
{
  var resource = url.replace(/^([^.?\/]+)([.?\/].+)?/, "$1");
  
  if(!$("#"+resource)[0]) {    
    if(!height) height = popup_height;
    if(!width)  width  = popup_width;
    
    var iframe = $("<iframe src=\"/blank.html\"></iframe>")
      .attr("id", resource)
      .attr("name", resource)
      .attr("frameborder", "no")
      .attr("scrolling", "no")
      .attr("src", "/"+url)
      .css("z-index", "10")
      .css("position", "fixed")
      .css("bottom", 0)
      .css("right", 0)
    ;
    
    if($.browser.msie)
      iframe.css("position", "absolute");
    
    if(width)
      iframe.width(width);
    if(height)
      iframe.height(height);
    
    iframe.appendTo("body");
    
    var n = popups.length;  
    popups[n] = [];
    popups[n]["resource"] = resource;
    popups[n]["height"] = height;
    popups[n]["width"] = width;
  }
}

function setOuterHTML(object, html)
{
    $(object).outerHTML(html);

    /*if (object.outerHTML)
        object.outerHTML = html; 
    else  { 
        range = document.createRange(); 
        range.setStartBefore(object); 
        docFrag = range.createContextualFragment(html); 
        object.parentNode.replaceChild(docFrag, object); 
    } */
}