var MainClass = new JS.Class({
    initialize: function(){
        this.xRequest = null;
        this.Categories = {};
        this.BindEvents();
        this.root = {};
    },
    BindEvents: function(){
        var self = this;
        $('#additional div').each(function(){
            $(this).bind('click',function(){
                self.AdditionalOptions(this);
            });
        });
//        $('a').live('click',function(e){
//            if( e.button == 0 ) {
//                if($(this).attr('ajax') == 'disabled'){
//                        //Handle dummy links
//                } else if(!$(this).attr('href')) {
//                        //Handle dummy links
//                        return false;
//                } else {
//                    window.location.hash = $(this).attr('href').replace(WWW_PATH.substring(0,WWW_PATH.length-1),'#');
//                    currentHash = window.location.hash;
//                    self.LoadPage($(this).attr('href'));
//                    return false;
//                }
//            }
//        });
    },
    LoadPage : function(u){
        if (u.search('\\?') == -1){
            u = u + '?ajax=true';
        } else {
            u = u + '&ajax=true';
        }
        $.ajax({
            type: "GET",
            url: u,
            async: true,
            success: function(msg){
                $('#primarycontainer').html(msg);
            }
        })
        return false;
    },
    AdditionalOptions: function(item){
        var c = $(item).attr('class');
        $('.' + c + 'Field').toggle('fast');
    },
    XClose: function(e){
        var o = $(e).parent();
        var self = this;
        o.slideUp('fast',function(){
            self.XCloseClear(o);
        })
    },
    XCloseClear: function(i){
    
    },
    validateForm : function (obj){
        var e = $(obj).find('#textField');
        if ($('.item_textField').css('display') == 'none'){
            $('.item_textField').remove();
        }
        if ($('.item_youtubeField').css('display') == 'none'){
            $('.item_youtubeField').remove();
        }
        if (e.val().length > 3 && e.val().length < 255){
            return true;
        } else {
            e.prev().find('span').css('display','block');
            return false;
        }
    },
    submitForm : function (obj){
        var i = $($(obj).find('#textField'));
        if (i.val() == i.attr('title')){
            i.focus();
            return false;
        }
        if (this.validateForm(obj)){
            $.ajax({
                type: "POST",
                url: WWW_PATH+"add.php",
                data : $(obj).serialize(),
                dataType: 'json',
                async: true,
                success: function(msg){
                    if (typeof msg.id != 'undefined'){
                        window.location="http://www.logovi.org/browse/"+msg.id;
                    }
                }
            });
        }
    },
    SetFaved: function(id,type,obj){
        var self = this;
        if (self.xRequest == null){
            $.ajax({
                type: "POST",
                url: WWW_PATH+"fave.php",
                data : ({
                    object_id : id,
                    type: type,
                    addFave : 1
                }),
                dataType: 'json',
                async: true,
                success: function(msg){
                    self.xRequest = null;
                    if (msg.response){
                        $(obj).parent().html(msg.link);
                    }
                }
            });
        } else {
            self.xRequest.abort();
        }
    },
    UnsetFave: function(id,type,obj){
        var self = this;
        if (self.xRequest == null){
            $.ajax({
                type: "POST",
                url: WWW_PATH+"fave.php",
                data : ({
                    object_id : id,
                    type: type,
                    delFave : 1
                }),
                dataType: 'json',
                async: true,
                success: function(msg){
                    self.xRequest = null;
                    if (msg.response){
                        $(obj).parent().html(msg.link);
                    }
                }
            });
        } else {
            self.xRequest.abort();
        }
    }
}) ;

//Adding editing and stuff with categories


var Categories = new JS.Class({
    initialize : function(){
        this.e = $('.selectCategory');
    },
    Display: function(){
        this.e.slideDown('fast');
    },
    HideDisplay: function(){
        this.e.slideUp();
    },
    AddCategory : function(id,obj){
        $('.clearASelected').find('a').removeClass('selected');
        $(obj).addClass('selected');
        $('#shareFormButton').css('display','block');
        //$('#textField').scrollTop($("#textField").offset().top);
        $('#textField').focus();
        $('#categoryInput').val(id);
        if ($(obj).attr('title').length == 0){
            $('#categoryText').html($(obj).html());
        } else {
            $('#categoryText').html($(obj).attr('title'));
        }
      
        this.HideDisplay();
    },
    ExpandTextArea: function(o){
        console.log($(o).scrollTop);
    }
});



(function($) {

	// jQuery plugin definition
	$.fn.TextAreaExpander = function(minHeight, maxHeight) {

		var hCheck = !($.browser.msie || $.browser.opera);

		// resize a textarea
		function ResizeTextarea(e) {

			// event or initialize element?
			e = e.target || e;

			// find content length and box width
			var vlen = e.value.length, ewidth = e.offsetWidth;
			if (vlen != e.valLength || ewidth != e.boxWidth) {

				if (hCheck && (vlen < e.valLength || ewidth != e.boxWidth)) e.style.height = "0px";
				var h = Math.max(e.expandMin, Math.min(e.scrollHeight, e.expandMax));

				e.style.overflow = (e.scrollHeight > h ? "auto" : "hidden");
				e.style.height = h + "px";

				e.valLength = vlen;
				e.boxWidth = ewidth;
			}

			return true;
		};

		// initialize
		this.each(function() {
			// is a textarea?
			if (this.nodeName.toLowerCase() != "textarea") return;

			// set height restrictions
			var p = this.className.match(/expand(\d+)\-*(\d+)*/i);
			this.expandMin = minHeight || (p ? parseInt('0'+p[1], 10) : 0);
			this.expandMax = maxHeight || (p ? parseInt('0'+p[2], 10) : 99999);

			// initial resize
			ResizeTextarea(this);

			// zero vertical padding and add events
			if (!this.Initialized) {
				this.Initialized = true;
				$(this).css("padding-top", 0).css("padding-bottom", 0);
				$(this).bind("keyup", ResizeTextarea).bind("focus", ResizeTextarea);
			}
		});

		return this;
	};

})(jQuery);


// initialize all expanding textareas
jQuery(document).ready(function() {
	jQuery("textarea[class*=expand]").TextAreaExpander();
});




var WIDBox = new JS.Singleton({
    initialize: function(){
        this.containerTop = '<div style="background-color: #FFFFFF;border: 4px solid #CCCCCC;display: block;left: 578px;padding: 15px;position: absolute;top: 176px;z-index: 20;" class="widBox"><div style="float:right;"><a href="javascript:void(0);" onclick="WIDBox.close(this)">Zatvori</a></div><div style="clear:both;"></div><br />';
        this.containerBottom = '</div>';
        this.backgroundContainer = '<div style="z-index:19;position:absolute;top:0;left:0;width:100%;height:100%;" class="widBoxBackground">&nbsp;</div>'
    },
    create: function(){

    },
    reveal: function(c,o,callback){
        var s = '';
        s += this.containerTop;
        s += c;
        s += this.containerBottom;
        $('body').prepend(s);
        this.calculate();
        if (typeof o != 'undefined' && o == true){
            this.createBckg();
        }
        if (typeof callback != 'undefined'){
            callback();
        }
        $(document).bind('keydown', function(e) {
            if (e.keyCode == 27) {
                WIDBox.close();
                e.stopPropagation();
                e.preventDefault();
                $(document).unbind('keydown');
            }
            return true;
        })
    },
    calculate: function(){
        var e = $('body .widBox');
        var wH = $(window).height();
        var wW = $(window).width();
        var eH = e.height();
        var eW = e.width();
        var top = wH/2 - eH/2 + e.offset().top;
        var left = wW/2 - eW/2;

        if (top < 50){
            top = 50;
        }
        e.css('top',top);
        e.css('left',left);

        e.css('display','block');
    },
    createBckg: function(){
        $('body .widBoxBackground').remove();
        $('body .widBox').after(this.backgroundContainer);
    },
    close: function(obj){
        if ($('body .widBox').length == 1){
            $('body .widBoxBackground').remove();
        }
        if (typeof obj == 'undefined'){
            $('.widBox').remove();
        } else {
            $(obj).parents('.widBox').remove();
        }

    }
})
