// JavaScript Document

$(function(){
    
    $.fn.centerOnTop = function( target , offsets){
        if(!offsets) var offsets={};
        
        var targetHeight = $(target).height();  // + (offsets.Y ? offsets.Y : 0);
        var targetWidth = $(target).width();    // + (offsets.X ? offsets.X : 0);
        var pos = $(target).offset();
        
        var height = $(this).height();
        var width = this.width();
        
        this.css({
            position:"absolute",
            left:((pos.left + (offsets.X ? offsets.X : 0)) - parseFloat(((width - targetWidth)/2))) + "px",
            top:((pos.top + (offsets.Y ? offsets.Y : 0)) - parseFloat(((height -targetHeight)/2))) + "px"
        });
        
        if(this.css('display')=='none'){
            trace('frig');
        }
    }
    
    //this will add a dropshadow to a container with distance based on z-index
    $.fn.hasShadow = function(){
        var height = $(this).outerHeight();
        var width = $(this).outerWidth();
        var zindex = $(this).css("z-index");
        var parent = $(this).parent();
        var pos = $(this).position();
        var distance = zindex*5;
        var borderRadius = $(this).hasClass("roundedEdges")? "10px" : "0px";
        var dropShadow = $("<div class='dropShadow' owner='"+$(this).attr("id")+"' />").css({"z-index":zindex-1, "height":height, "width":width, "position":"absolute", "top":pos.top+distance+"px", "left":pos.left+distance+"px", "background":"black", "opacity":".15", "-moz-border-radius":borderRadius, "border-radius":borderRadius, "filter":"Alpha(opacity=15)"});
        $(parent).append(dropShadow);
        $(this).addClass("hasDropShadow");
    }
    
    //remove the dropshadow meant to be used in tandem with .hide() or .remove()
    $.fn.killShadow = function(){
        var thisID = $(this).attr("id");
        $(".dropShadow").each(function(){
            if($(this).attr("owner")==thisID){
                $(this).remove();   
            }
        });
    }
    
    //center a div on the screen
    $.fn.screenCenter = function(){
        this.css("position","absolute");
        this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
        this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
        this.addClass('screenCentered');
        if(this.height()>$(window).height()){
            this.css("top",0);  
        }
        $(window).resize(function(){
            $('.screenCentered').screenCenter();
        });
        return this;
    }
    
    //center the object in the center of it's parent
    $.fn.centerInParent = function(){
        this.css("position","absolute");
        this.css("top", ( $(this).parent().height() - this.height() ) / 2 + "px");
        this.css("left", ( $(this).parent().width() - this.width() ) / 2 + "px");
        return this;
    }

    $.fn.getSelectedText = function() {
        var el = $(this).get(0);
        el.focus();
        // IE Support
        if (document.selection) {
            el.focus();
            var Sel = document.selection.createRange();
            var SelLength = document.selection.createRange().text.length;
            Sel.moveStart('character', -el.value.length);
            return { start: (Sel.text.length - SelLength), end:"not supported", text:"not supported" };
        }
        // Firefox support
        else if (el.selectionStart || el.selectionStart == '0')
            return { start: el.selectionStart, stop: el.selectionEnd, text: (el.value.substr(el.selectionStart, (el.selectionEnd - el.selectionStart)))  };
    }



});
//remove unneeded Pop-ups
closePU =function(target, leaveShroud ){
    if(!target) target = '.generalPU';
    if($(target).hasClass("hasDropShadow")){
        $(target).killShadow(); 
    }
    $(target).remove();
    if(!leaveShroud){
        $('#shroud').remove();
        if(window.shroudInterval){
            clearInterval(window.shroudInterval);
        }
    }
}

//General pop up for the site
function popUp ( url , attributes, callBack ){
    var defaults = {
        "boxWidth": "300px",
        "boxHeight": "",
        "closeBtn": true,
        "closeBtnTxt": "x",
        "titleBar": false,
        "xscrollbar": false,
        "yscrollbar": false,
        "addClasses":false,
        "contextClasses":false,
        "zIndex":22,
        "dropShadow":true,
        "shroud":false,
        "modal":false
    };
    if( attributes && typeof(attributes) == "function"  ) var callBack = attributes;
    else if(attributes) $.extend(defaults, attributes);
    
    if(!defaults.modal){
        $('.generalPU, .dropShadow').remove();
    }

    $.ajax({
        url: url,
        dataType:"html",
        success: function(data) {
            
            html = '<div class="generalPU'+classString(defaults.addClasses)+'" style=" width:'+defaults.boxWidth+'; height:'+defaults.boxHeight+'; z-index:'+defaults.zIndex+';">'
                +(defaults.closeBtn?'<a href="javascript:;" class="closeButton">' +defaults.closeBtnTxt + '</a>':'')
                +(defaults.titleBar!=false?'<div class="PUheader">'+defaults.titleBar+'</div>':'')
                +'<div class="PUbody'+classString(defaults.contextClasses)+'" style="'
                +(defaults.xscrollbar?'overflow-x:auto;':'overflow-x:hidden;')
                +(defaults.yscrollbar?'overflow-y:auto;':'overflow-y:hidden;')
                +'">'
                    +data
                +'</div>'
            +'</div>';
                
            
            //add the data to the page and center it
            $(html).appendTo("body").screenCenter();
            if(defaults.dropShadow) $(".generalPU").hasShadow();
            if(!defaults.closeBtn) $(".generalPU .closeButton").hide();
            else {
                if(defaults.modal){
                    $(".generalPU .closeButton").click(function(){closePU($(this).parent(), true);});   
                } else {
                    $(".generalPU .closeButton").click(function(){closePU($(this).parent());}); 
                }
            }
            if(defaults.shroud){
               var shroud =  $('<div id="shroud" />');
               $('body').prepend(shroud);
               if(!window.shroudInterval){
                   window.shroudInterval = 
                       setInterval(' $("#shroud").height( $(document).height() ).width($(document).width() ); ' , 10 );
               }
            }
            if(callBack) callBack();
        }
        
    });
    
    
    
     
}

function classString( variable ){
    var string = "";
    
    if(!variable) return '';
    
    if(typeof(variable)=="object"){
        for( i in variable ){
            string += " " + variable[i];    
        }
    } else {
        string = " " + variable;
    }
    
    return string;
}

//firebug specific messaging
trace = function(message, value){
    if (typeof console != 'undefined') {
        if( typeof message == "object" || typeof value == "object" ){
            console.log(message);
            if(value){
                console.log(value);
            }
        } else {
            console.log(message + ( value === undefined ? "" : " : " +value ));   
        }
    }
}

function trim(ogg) {
    ogg.value = ogg.value.replace(/^ *(.+) *$/, "$1");
} 

function raiseError( error ){
        console && console.warn(error);
}

String.prototype.uc_first = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

function setCookie(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=/";
}

function getCookie(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 deleteCookie(name) {
        setCookie(name,"",-1);
}
//FUNCTION loadFile( filename, filetype  )
//=========================================================================================================================
// This loads up a file using javascript
// @filename: This is the name of the file that you want to load up
// @filetype:  This is the type that you wish the file to be represented as
// @return: void
function loadFile( filename, filetype){
    if(filetype=='js'){
        var fileref=document.createElement('script');
        fileref.setAttribute('type','text//javascript');
        fileref.setAttribute('src',filename);
    } else if( filetype=='css' ){
        var fileref=document.createElement('link');
        fileref.setAttribute('rel','stylesheet');
        fileref.setAttribute('type','text/css');
        fileref.setAttribute('href',filename);
    }
    if(typeof fileref != 'undefined'){
        document.write(fileref);
    }
}
 function _GET( varToGet ){
    var string = window.location.toString();
    string = string.split('?');
    if(string[1]) string = string[1].split('&');
    for(i in string){
        var thisVar = string[i].split('=');
        if(thisVar[0] == varToGet) return thisVar[1];
    }
    return '';
 }
function pageReload(){
    location.reload();
}

