jQuery(function(){

    jQuery.fn.exists = function() { return (this.length > 0); };
    
    jQuery.fn.total_width = function() {
        
        var el = $(this);
        var total_width = el.width();
        
        total_width += parseInt(el.css("padding-left"), 10) + parseInt(el.css("padding-right"), 10); //Total Padding Width
        total_width += parseInt(el.css("margin-left"), 10) + parseInt(el.css("margin-right"), 10); //Total Margin Width
        total_width += parseInt(el.css("borderLeftWidth"), 10) + parseInt(el.css("borderRightWidth"), 10); //Total Border Width
        
        return total_width;
    }
    
    jQuery.fn.total_height = function() {
        
        var el = $(this);
        var total_height = el.height();
        
        total_height += parseInt(el.css("padding-top"), 10) + parseInt(el.css("padding-bottom"), 10); //Total Padding Width
        total_height += parseInt(el.css("margin-top"), 10) + parseInt(el.css("margin-bottom"), 10); //Total Margin Width
        total_height += parseInt(el.css("borderTopWidth"), 10) + parseInt(el.css("borderBottomWidth"), 10); //Total Border Width
        
        return total_height;
    }
    
});

function getLocation() {
    
    var location = window.location.toString();
    if(location.indexOf('#') != -1) {
    
        location = location.substr(0, location.indexOf('#'));
    }
    if(location.indexOf('?') != -1) {
    
        location = location.substr(0, location.indexOf('?'));
    }
    if(location.indexOf('&') != -1) {
    
        location = location.substr(0, location.indexOf('&'));
    }
    if(location.charAt(location.length-1)!='/') {
        
        location += '/';
    }
    
    return location;    
}

function getPanel(name, content, id, cclass, draggable) {
    
    var panel = $('<div class="panel'+(cclass?' '+cclass:'')+'" '+(id?' id="'+id+'"':'')+'><div class="panel-header" ><h2>'+name+'</h2></div><div class="top-left"></div><div class="top-middle"></div><div class="top-right"></div><div class="middle-left"></div><div class="panel-copy">'+content+'</div><div class="middle-right"></div><div class="bottom-left"></div><div class="bottom-middle"></div><div class="bottom-right"></div></div>');        
    
    if(draggable) {
        
        panel.draggable({
            
            cursor: 'move',
            handle: '.panel-header'
        });
    }
    
    return panel;
}

function max(val1, val2) {
    
    return (val1<val2)?val2:val1;
}

function min(val1, val2) {
    
    return (val1>val2)?val2:val1;
}

function rand(n) {
    return(Math.floor(Math.random()*n+1));
}

function ucwords(str) {

    return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
        return $1.toUpperCase();
    });
} 

// Display notices
function showNotice(elem, fadeTimeout, isIframe) {
    
    var e = window;
    
    if(isIframe) {
        
        e = window.parent;
    }
    
    elem.fadeIn(500,function() {
        
        e.setTimeout(function() {
            
            elem.fadeOut(1000, 
            function() {           
                
                if($(this).next().exists())
                    showNotice($(this).next(), fadeTimeout, isIframe);
                    
                $(this).remove();
            });
            
        }, fadeTimeout);
        
    });
}

function addNoticeHTML(data, fadeOut, isIframe) {
    
    var e = document;
    
    if(isIframe) {
        
        e = window.parent.document;
    }
    
    if(!$('#notices', e).exists()) {
        
        $('#framework', e).prepend('<div id="notices"></div>');
    }
    
    if(typeof fadeOut == 'undefined' || fadeOut===false) {
        
        fadeOut = 5000;
    }
    
    var html = $(data);
    html.hide();
    
    $('#notices', e).append(html);
    
    if($('#notices .notice', e).length==1) {
    
        showNotice(html, fadeOut, isIframe);
        
    } else {
        
        html.fadeIn(500);
    }
}

function addNotice(text, type, fadeOut, isIframe) {
    
    if(typeof type == 'undefined' || type===false) {
        
        type = 'error';
    }
    
    if(typeof fadeOut == 'undefined' || fadeOut===false) {
        
        fadeOut = 5000;
    }
    
    var html = '<div class="notice '+type+'">'+text+'</div>';
    addNoticeHTML(html, fadeOut, isIframe);
}

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/admin/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

function getTemplateItem(type,name,value,data,ob_id,editable,handlerFunction) {
    
    if(typeof(handleTemplateResult)=='function' && !handlerFunction)
        handlerFunction = handleTemplateResult; 
    if(typeof(handlerFunction)=='function') {
        
        $.post('/admin/media/context/admin-context.php',
        {
            action: 'templateItem',
            type: type,
            name: name,
            value: value, 
            data: data, 
            ob_id: ob_id,
            editable: editable    
        },
        handlerFunction,
        "json"); 
        return true;  
    } 
    return false;
}

function popUp(URL, Opts) {
    //alert(URL);
    //alert(Opts);
    day = new Date();
    id = day.getTime();
    if(!Opts)
        Opts = 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width=800,height=640';
        
    eval("page" + id + " = window.open(URL, '" + id + "', '"+Opts+"');");
}

function addSpinner(el, append) {
    
    var spinner = $('<div class="spinner"><div class="spinner-inside">&nbsp;</div></div>');
    var parentEl = null;
    
    if(!$.isPlainObject(el)) {
     
        el = $(el);   
    }
    
    if(append) {
        
        el.append(spinner); // Pastes it inside the element
        parentEl = el;
        
    } else {
        
        el.after(spinner); // Pastes it after the element
        parentEl = el.parent();
    }
    
    //parentEl.data('position', parentEl.css('position'));
    //parentEl.data('height', parentEl.css('height'));
    //parentEl.data('width', parentEl.css('width'));
    parentEl.css('position', 'relative');
    
    resizeSpinner(parentEl);
    parentEl.resize(function(){
        
       resizeSpinner(this);
    });
    
    return spinner;
}

function removeSpinner(el, appended) {
    
    var parentEl = null;
    
    if(!$.isPlainObject(el)) {
     
        el = $(el);   
    }
    
    if(appended) {
        
        parentEl = el;
        
    } else {
        
        parentEl = el.parent();
    }

    parentEl.find('.spinner').remove(); 
    parentEl.css('position', '');    
    parentEl.css('height', '');    
    parentEl.css('width', '');    
    
    //parentEl.css('position', parentEl.data('position'));    
    //parentEl.css('height', parentEl.data('height'));    
    //parentEl.css('width', parentEl.data('width'));    
}

function resizeSpinner(el) {
    
    if(el) {
    
        if(!$.isPlainObject(el)) {
         
            el = $(el);   
        }
        
        if(el.height() < el.find('.spinner .spinner-inside').height()) {
            
            el.height(el.find('.spinner .spinner-inside').height()+20);
        }
        
        if(el.width() < el.find('.spinner .spinner-inside').width()) {
            
            el.width(el.find('.spinner .spinner-inside').width()+20);
        }
        
        el.find('.spinner')
        .width(el.total_width())
        .height(el.total_height());
        
        var top = (el.total_height() - el.find('.spinner .spinner-inside').height())/2;        
        el.find('.spinner .spinner-inside').css('top', top+'px'); 
    }   
}

function appendScript(document, scriptSrc) {
    
    var script   = document.createElement("script");
    script.type  = "text/javascript";
    script.src   = scriptSrc;
    document.body.appendChild(script);    
}
