//url manipulation (anchor)
function get_anchor(){
    anchor = url.split('#')[1];
    
    if (typeof(anchor) != 'undifined'){
        return anchor;
    } else {
        return false;            
    }
}
function set_anchor(str){
    url = url.split('#');
    url = url[0] + '#' + str;
    
    document.location = url;
}

//set contect height to body height
function set_height(){
    var vp_height = $(page).getSize().y;
    var margin = 40;
    var wraper = $$('div.wraper');
    var panel = $$('div#panel');
    var ch = header.getSize().y + footer.getSize().y; //content height
    
    if(vp_height - margin > ch){
        wraper.setStyle('height', vp_height - margin);
        panel.setStyles({
            position: 'fixed',
            height: wraper.getSize()[0].y
        });
        $$('div.bar').show();
    } else {
        wraper.setStyle('height', ch + margin); 
        panel.setStyles({
            position: 'absolute',
            height: wraper.getSize()[0].y
        });
        $$('div.bar').hide();
    }
}

function getScrollBarWidth (){
    var inner = document.createElement('p');
    inner.style.width = '100%';
    inner.style.height = '200px';
    
    var outer = document.createElement('div');
    outer.style.position = 'absolute';
    outer.style.top = '0px';
    outer.style.left = '0px';
    outer.style.visibility = 'hidden';
    outer.style.width = '200px';
    outer.style.height = '150px';
    outer.style.overflow = 'hidden';
    outer.appendChild (inner);
    
    document.body.appendChild (outer);
    var w1 = inner.offsetWidth;
    outer.style.overflow = 'scroll';
    var w2 = inner.offsetWidth;
    if (w1 == w2) w2 = outer.clientWidth;
    
    document.body.removeChild (outer);
    
    return (w1 - w2);
};

/* adds fancybox to an element
  el    the element (just one element at this time)
  type  image of content(iframe)
*/
function set_fancybox(el, type){
    var el = $(el);
    
    switch(type){
        case 'image':
            el.fancybox({
                'padding': 0,
                'zoomOpacity': true,
                'zoomSpeedIn': 600,
                'zoomSpeedOut': 400,
                'hideOnContentClick': true,
                'overlayShow': false
            });
            break;
        
        case 'content':
            el.fancybox({
                'padding': 0,
                'frameWidth': 650,
                'frameHeight': 500,
                'hideOnContentClick': true,
                'overlayShow': false
            });
            break;
    }
}

/* inserts file from iframe to parent page
  ID        file id (file_###)
  type      file type (image, reqular)
  name      file name
*/
inserted_files = new Array();
removed_files = new Array();
function insert_file(id, type, name){
    var ID = id.split('_')[1];
    var check = $.inArray(id, inserted_files);
    if(check == -1){
        var UL = $('ul.files');
        LI ='<li class="' + type + '" id="file_' + ID + '">' +
                '<span class="actions">' +
                    //'<a href="' + weburl + 'admin/file/delete/' + ID + '" rel="file_' + ID + '" title="Delete this file" class="file delete hide-text">Delete</a>' +
                    '<a href="' + weburl + 'admin/file/edit/' + ID + '" title="Edit this file" class="file edit hide-text">Edit</a>' +
                    '<a rel="'+ id +'" title="Remove this file" class="file remove hide-text">Remove</a>' +
                '</span>' +
                '<a class="' + type + '" href="' + weburl + 'files/' + name + '"><img src="' + weburl + 'files/t' + name + '" alt="' + name.substr('-4') + '"/></a>' +
            '</li>';
        //insert code
        UL.append(LI);
        //add to array
        inserted_files.push(id);
        
        //set events! :c
        if(type == 'image') set_fancybox('li#'+ id +' a.image', 'image');
        
        remove_button($('li#'+ id +' a.file.remove'));
        /*$('li#'+ id +' a.file.remove').click(function(){
            $('li#'+ id).fadeOut('normal', function(){
                $(this).remove();
            });
            if($.inArray(id, inserted_files) == -1){
                alert(id);
                //remove from page and add id to remover_files array
                //removed_files.push(id);
            } else {
                remove_items(inserted_files, id);                
            }
        });*/
    }
}

function remove_button(items){
    $(items).each(function(){
        var id = $(this).attr('rel');
        $(this).click(function(){
            $('li#'+ id).fadeOut('normal', function(){
                $(this).remove();
            });
            
            if($.inArray(id, inserted_files) == -1){
                removed_files.push(id);
            } else {
                remove_items(inserted_files, id);                
            }
        });
    });
}

function add_button(items, type){
    switch(type){
        case 'insert':
            $(items).each(function(){
                var img_url = $(this).parent().next().attr('href');
                $(this).click(function(){
                    var URL = img_url;
                    var win = tinyMCEPopup.getWindowArg("window");
                    
                    // insert information now
                    win.document.getElementById(tinyMCEPopup.getWindowArg("input")).value = URL;
                    
                    // are we an image browser
                    if (typeof(win.ImageDialog) != "undefined") {
                        // we are, so update image dimensions...
                        if (win.ImageDialog.getImageData)
                            win.ImageDialog.getImageData();
                            
                        // ... and preview if necessary
                        if (win.ImageDialog.showPreviewImage)
                            win.ImageDialog.showPreviewImage(URL);
                    }
                        
                    // close popup window
                    tinyMCEPopup.close();
                    
                });
            });
            break;
        case 'add':
            $(items).each(function(){
                var rel = $(this).attr('rel').split('|');
                var ID = rel[0];
                var type = rel[1];
                var name= rel[2];
                
                $(this).click(function(){
                    top.window.insert_file(ID, type, name);
                });
            });
            break;
    }
}

function add_hidden(form){
    var hidden = '';
    $(inserted_files).each(function(){
        hidden += '<input type="hidden" name="add_files[]" value="' + this.split('_')[1] + '" />';
    });
    
    $(removed_files).each(function(){
        hidden += '<input type="hidden" name="rem_files[]" value="' + this.split('_')[1] + '" />';
    });

    $(form).append(hidden);    
    return true;
}

//delete items
function del(href, el){
    var URL = href + ajax_bc;
    
    if(confirm('Are you sure you want to delete this item?')){
        $.ajax({
            type: "GET",
            url: URL,
            timeout: "7000",
            dataType: 'json',
            error: function(xhr, desc) {
                //alert(xhr.responseText);
            },
            success: function(msg){
                if(msg['error'] == 'false'){
                    if(el){
                        $(el).fadeOut(function(){
                            $(this).remove();
                        });
                    } else {
                        $("tr:has(a[href=" + href +"])").fadeOut(function(){
                            $(this).remove();
                        });   
                    }    
                }else{
                    alert(msg['msg']);   
                }
            }
        });
    }
}

//textbox list autocomplete
function input_list_ac(input, list, short_list){
    var type = $(input).attr('name');
    var input = new TextboxList(input, {unique: true, inBetweenEditableBits: false, plugins: {autocomplete: {placeholder: false}}});
    
    input.plugins['autocomplete'].setValues(list);
    input.addEvent('bitBoxRemove', function(x){
        if($.inArray(x.value[1], short_list) != -1) { //if this item is in db
            //add to new array
            var rem = eval('rem_' + type);
            rem.push(x.value[1]);
        }
    });
}

//removes given item from array
function remove_items(array, item) {
    var i = 0;
    while (i < array.length) {
        if (array[i] == item) {
            array.splice(i, 1);
        } else {
            i++;
        }
    }
    return array;
}

function is_defined(variable){
    return (typeof(variable) == "undefined")?  false: true;
}

//load more content
function load_more(handle, url, container){
    var pn = 0;
    var base_url = url;
    
    handle.addEvent('click', function(){
        var more_ajax = new Request.HTML({
            onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript){
                pn++;
                container.adopt(responseTree);
                var lis = $$('li.p_' + pn);
                lis.slide('hide').slide('in');
                //lis.fade('hide').fade('in');
                
                share_events($$('li.p_' + pn + ' a.share'), $$('li.p_' + pn + ' ul.share'));
                
                if(pn == pages){ //if this is the last page
                    handle.fade('out').destroy();
                }
            }
        });
        
        var url = base_url + (pn+1) + ajax_bc;
        more_ajax.get(url);
        
        return false;
    });
}

function share_events(button, layer){
    layer.show().fade('hide');
    button.addEvent('mouseover', function(e){
		e.stop();
		var layer = this.getParent().getNext('ul.share');
		layer.fade('in');
	});
    
	layer.addEvent('mouseleave', function(){
		this.fade('out');
	});
}

window.addEvent('domready', function(){
    //cool custom event from: http://mcarthurgfx.com/blog/article/one-time-custom-mootools-events
    Element.Events.oneClick = {
        base: 'click',
        condition: function(event) {
            var fire = !this._oneClicked;
            this._oneClicked = true;		
            return fire;
        },
        onAdd: function(fn) {
            if(this._oneClicked) {
                fn.call(this);
            }
        }
    };

});

var log = function() {
	if(window.console && console.log) {
		for(var i = 0; i < arguments.length; i++) {
			console.log(arguments[i]);
		}
	}
}