/* Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Version: 1.2
 * Requires: jQuery 1.2+
 */
(function($){
	
    $.dimensions = {
        version: '1.2'
    };

    // Create innerHeight, innerWidth, outerHeight and outerWidth methods
    $.each( [ 'Height', 'Width' ], function(i, name){
        // innerHeight and innerWidth
        $.fn[ 'inner' + name ] = function() {
            if (!this[0]) return;
		
            var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
            borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right
		
            return this.is(':visible') ? this[0]['client' + name] : num( this, name.toLowerCase() ) + num(this, 'padding' + torl) + num(this, 'padding' + borr);
        };
        // outerHeight and outerWidth
        $.fn[ 'outer' + name ] = function(options) {
            if (!this[0]) return;
		
            var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
            borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right
		
            options = $.extend({
                margin: false
            }, options || {});
		
            var val = this.is(':visible') ?
            this[0]['offset' + name] :
            num( this, name.toLowerCase() )
            + num(this, 'border' + torl + 'Width') + num(this, 'border' + borr + 'Width')
            + num(this, 'padding' + torl) + num(this, 'padding' + borr);
		
            return val + (options.margin ? (num(this, 'margin' + torl) + num(this, 'margin' + borr)) : 0);
        };
    });

    // Create scrollLeft and scrollTop methods
    $.each( ['Left', 'Top'], function(i, name) {
        $.fn[ 'scroll' + name ] = function(val) {
            if (!this[0]) return;
		
            return val != undefined ?
		
            // Set the scroll offset
            this.each(function() {
                this == window || this == document ?
                window.scrollTo(
                    name == 'Left' ? val : $(window)[ 'scrollLeft' ](),
                    name == 'Top'  ? val : $(window)[ 'scrollTop'  ]()
                    ) :
                this[ 'scroll' + name ] = val;
            }) :
			
            // Return the scroll offset
            this[0] == window || this[0] == document ?
            self[ (name == 'Left' ? 'pageXOffset' : 'pageYOffset') ] ||
            $.boxModel && document.documentElement[ 'scroll' + name ] ||
            document.body[ 'scroll' + name ] :
            this[0][ 'scroll' + name ];
        };
    });

    $.fn.extend({
        position: function() {
            var left = 0, top = 0, elem = this[0], offset, parentOffset, offsetParent, results;
		
            if (elem) {
                // Get *real* offsetParent
                offsetParent = this.offsetParent();
			
                // Get correct offsets
                offset       = this.offset();
                parentOffset = offsetParent.offset();
			
                // Subtract element margins
                offset.top  -= num(elem, 'marginTop');
                offset.left -= num(elem, 'marginLeft');
			
                // Add offsetParent borders
                parentOffset.top  += num(offsetParent, 'borderTopWidth');
                parentOffset.left += num(offsetParent, 'borderLeftWidth');
			
                // Subtract the two offsets
                results = {
                    top:  offset.top  - parentOffset.top,
                    left: offset.left - parentOffset.left
                };
            }
            return results;
        },
	
        offsetParent: function() {
            var offsetParent = this[0].offsetParent;
            while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && $.css(offsetParent, 'position') == 'static') )
                offsetParent = offsetParent.offsetParent;
            return $(offsetParent);
        }
    });

    function num(el, prop) {
        return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0;
    };
})(jQuery);

/*
 * Copyright (c) 2008 Denis Zenkovich (denis.zenkovich@gmail.com)
 */
jQuery.fn.extend({
    draggable: function(Options)
    {
        if (!this[0])
            return this;
        //TODO add droppables
        var Obj = this;
        var _SelEventName = jQuery.browser == "msie" ? "selectstart" : "mousedown";
        var _start = function(E)
        {
            if (typeof(Obj.Drag.Options.onStart) == "function")
                Obj.Drag.Options.onStart(E, Obj);
            var scr = {
                X: jQuery(document).scrollLeft(),
                Y: jQuery(document).scrollTop()
            };
            Obj.Drag.Mouse.Start = {
                X: E.clientX + scr.X,
                Y: E.clientY + scr.Y
            };
            Obj.Drag.Offset = Obj.offset(Obj.parent());
            Obj.Drag.El = Obj;
            if (Obj.Drag.Options.Droppables)
                _calcCoords();
            _updateDocScroll();
            jQuery(document).mousemove(_move).mouseup(_stop).scroll(_updateDocScroll).bind(_SelEventName, _dontselect);
            return false;
        };
        var _updateDocScroll = function()
        {
            Obj.Drag.Scr = {
                X: jQuery(document).scrollLeft(),
                Y: jQuery(document).scrollTop()
            };
        };
        var _move = function(E)
        {
            Obj.Drag.Mouse.Now = {
                X: E.clientX + Obj.Drag.Scr.X,
                Y: E.clientY + Obj.Drag.Scr.Y
            };
            if (Obj.Drag.Options.Snap)
            {
                var Delta = {
                    X: Obj.Drag.Mouse.Now.X - Obj.Drag.Mouse.Start.X,
                    Y: Obj.Drag.Mouse.Now.Y - Obj.Drag.Mouse.Start.Y
                };
                if (Obj.Drag.Options.Snap > Math.max(Math.abs(Delta.X), Math.abs(Delta.Y)))
                    return;
                if (!Obj.Drag.SnapPassed)
                {
                    if (typeof(Obj.Drag.Options.onSnap) == "function")
                    {
                        Obj.Drag.Options.onSnap(E, Obj);
                    }
                    Obj.Drag.SnapPassed = true;
                }
            }
            if (Obj.Drag.Options.Droppables)
            {
                if (Obj.Drag.OverDrop)
                {
                    if (!_isOverDrop(Obj.Drag.Mouse.Now, Obj.Drag.OverDrop))
                    {
                        Obj.Drag.OverDrop.trigger('leave', [Obj, Obj.Drag.OverDrop]);
                        Obj.Drag.OverDrop = null;
                    }
                }
                if (!Obj.Drag.OverDrop)
                {
                    var Over = null;
                    for (var I = 0; I < Obj.Drag.Droppables.length; I++)
                    {
                        var Drop = Obj.Drag.Droppables[I];
                        if (_isOverDrop(Obj.Drag.Mouse.Now, Drop))
                            Over = Drop;
                    }
                    if(Over)
                    {
                        Over.trigger('over', [Obj, Over]);
                        Obj.Drag.OverDrop = Over;
                    }
                }
            }
            if (typeof(Obj.Drag.Options.onDrag) == "function")
                Obj.Drag.Options.onDrag(E, Obj);
            else
            {
                var t = Obj.Drag.Offset.top + Delta.Y;
                var l = Obj.Drag.Offset.left + Delta.X;
                Obj.Drag.El.css({
                    "top": t,
                    "left": l
                });
            }
            return false;
        };
        var _stop = function(E)
        {
            jQuery(document).unbind("mousemove", _move).unbind("mouseup", _stop).unbind(_SelEventName, _dontselect);
            //TODO unbind droppables
            if (Obj.Drag.Options.Snap && !Obj.Drag.SnapPassed)
                return;
            if (typeof(Obj.Drag.Options.onComplete) == "function")
                Obj.Drag.Options.onComplete(E, Obj);
            if (Obj.Drag.Droppables.length)
            {
                try
                {
                    if (!Obj.Drag.OverDrop)
                        throw 'empty';
                    if (typeof(Obj.Drag.Options.onBeforeDrop) == "function" && !Obj.Drag.Options.onBeforeDrop(E, Obj, Obj.Drag.OverDrop))
                        throw 'empty';
                    Obj.Drag.OverDrop.trigger('drop', [Obj, Obj.Drag.OverDrop]);
                    Obj.Drag.OverDrop.trigger('leave', [Obj, Obj.Drag.OverDrop]);
                }
                catch(Ex)
                {
                    if (typeof(Obj.Drag.Options.onEmpty) == "function")
                        Obj.Drag.Options.onEmpty(E, Obj);
                }
            }
            Obj.Drag.SnapPassed = false;
            return false;
        };
        var _isOverDrop = function(Mouse, Drop)
        {
            return (Mouse.X > Drop.Coords.L && Mouse.X < Drop.Coords.R && Mouse.Y > Drop.Coords.T && Mouse.Y < Drop.Coords.B);
        };
        var _dontselect = function()
        {
            return false;
        };
        var _calcCoords = function()
        {
            Obj.Drag.Droppables = [];
            for (var I = 0; I < Obj.Drag.Options.Droppables.length; I++)
            {
                var Drop = Obj.Drag.Options.Droppables[I];
                var Ps = Drop.offset();
                Drop.Coords = {
                    T: Ps.top,
                    R: Ps.left + Drop.width(),
                    B: Ps.top + Drop.height(),
                    L: Ps.left
                };
                Obj.Drag.Droppables.push(Drop);
            }
        }
        Obj.Drag = {
            Options: Options,
            start: function(E)
            {
                _start(E)
            },
            Mouse: {
                Start: null,
                Now: null
            },
            SnapPassed: false,
            Droppables: [],
            recalcCoords: function(){
                _calcCoords()
            }
        };
        Obj.mousedown(_start);
        return this;
    },
    getClass: function()
    {
        if (this.get(0))
            return this.get(0).className;
    }
});
jQuery.extend({
    arrayRemove: function(Item, Array)
    {
        for (var I = 0; I < Array.length; I++)
            if (Array[I] === Item)
                Array.splice(I, 1);
        return Array;
    },
    arrayInclude: function(Item, Array)
    {
        if(this.inArray(Item, Array) == -1)
            Array.push(Item);
        return Array;
    },
    winSize: function()
    {
        var S = {};
        //dimensions
        if (window.innerWidth)
            S.Sz = {
                X: document.documentElement.clientWidth,
                Y: window.innerHeight
            };
        else if (document.documentElement && document.documentElement.clientWidth)
            S.Sz = {
                X: document.documentElement.clientWidth,
                Y: document.documentElement.clientHeight
            };
        else if (document.body)
            S.Sz = {
                X: document.body.clientWidth,
                Y: document.body.clientHeight
            };
        //scroll height
        var Srcx = document.documentElement.scrollWidth == document.documentElement.offsetWidth ? S.Sz.X : document.documentElement.scrollWidth;
        S.Scrsz = {
            X: Srcx,
            Y: document.documentElement.scrollHeight
        };
        //scroll offset
        if (typeof(window.pageYOffset) == 'number') //Safari/Netscape compliant
            S.Scr = {
                X: window.pageXOffset,
                Y: window.pageYOffset
            };
        else //FF/IE and rest
            S.Scr = {
                X: document.documentElement.scrollLeft,
                Y: document.documentElement.scrollTop
            };
        //largest size
        S.Bsz = {
            X: Math.max(S.Scrsz.X, S.Sz.X),
            Y: Math.max(S.Scrsz.Y, S.Sz.Y)
        }
        return S;
    },
    ajaxIco: function(Obj, Css)
    {
        var Ico = jQuery('<img src="/img/ajax.gif" />');
        if(!Obj)
            return Ico;
        if(!Obj.jquery)
            Obj = jQuery(Obj);
        var Par = Obj.parent();
        if(Css)
        {
            Ico.css(Css);
        }
        else
        {
            var Pos = Obj.position();
            var Pars = {
                Yc: 2,
                Xc: 10
            }
            Ico.css({
                position: "absolute",
                top: Pos.top+Pars.Yc,
                left: Pos.left+Obj.width()+Pars.Xc
                });
        }
        Par.append(Ico);
        return Ico;
    },
    formatDate: function(Format, Date){
        var MonthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', '	August', 'September', 'October', 'November', 'December'];
        var YeN = Date.getFullYear();
        var MoN = Date.getMonth();
        var DaN = Date.getDate();
        var HoN = Date.getHours();
        var MiN = Date.getMinutes();
        var A = 'am';
        var HoN12 = HoN;
        if(HoN==0){ A = 'am'; HoN12 = 12; }
        if(HoN>12){ A = 'pm'; HoN12 = HoN-12; }
        if(HoN==12) A = 'pm';
        var run = function(C){
            //Year
            if(C == 'Y') return YeN; //Year full
            if(C == 'y') return YeN%100<10?'0'+YeN%100:YeN%100; //Year short
            //Month
            if(C == 'n') return (MoN+1); //Month num
            if(C == 'm') return MoN<9?'0'+(MoN+1):(MoN+1); //Month num with zero
            if(C == 'F') return MonthNames[MoN]; //Month full
            if(C == 'M') return MonthNames[MoN].substr(0, 3); //Month 3 chars
            //Date
            if(C == 'd') return DaN<10?'0'+DaN:DaN; //Date with zero
            if(C == 'j') return DaN; //Date
            //Hours
            if(C == 'H') return HoN<10?'0'+HoN:HoN; //24 Hours with zero
            if(C == 'G') return HoN; //24 Hours
            if(C == 'h') return HoN12<10?'0'+HoN12:HoN12; //12 Hours with zero
            if(C == 'g') return HoN12; //12 Hours
            if(C == 'a') return A; //am/pm
            if(C == 'A') return A=='pm'?'PM':'AM'; //AM/PM
            //Minutes
            if(C == 'i') return MiN<10?'0'+MiN:MiN; //Minutes with zero
            return C;
        }
        var Str = '';
        for(var I=0; I<Format.length; I++){
            Str+= run(Format.substr(I, 1));
        }
        return Str;
    }
});

