jQuery.namespace = function() {
    var a=arguments, o=null, i, j, d;
    for (i=0; i<a.length; i=i+1) {
        d=a[i].split(".");
        o=window;
        for (j=0; j<d.length; j=j+1) {
            o[d[j]]=o[d[j]] || {};
            o=o[d[j]];
        }
    }
    return o;
};

jQuery.namespace('PBS.socialbookmarks');

$(document).ready(function() {
    PBS.socialbookmarks.setup_widget();

    // detects if dtd exists
    function detect_dtd(){
        var re=/(\w+).dt/;
        var res=false;
        if(typeof document.namespaces != "undefined")
            res=document.all[0].nodeType==8 ? re.test(document.all[0].nodeValue) : false;
        else
            res=document.doctype != null ? re.test(document.doctype.publicId) : false;

        if(res) return RegExp.$1;

        return null;
    }

    // checks ie version
    // version 6 and 7 still render non-standards mode
    function msie_version()
    {
        var ua = window.navigator.userAgent;
        var msie = ua.indexOf("MSIE");

        if ( msie > 0 )      // If Internet Explorer, return version number
            return parseInt (ua.substring (msie+5, ua.indexOf (".", msie )));
        else                 // If another browser, return 0
            return 0;
    }

    // if ie and no dtd
    // add an aditional stylesheet to fix the issues
    if (msie_version() && detect_dtd() == null)
    {
        var nonstandard_css_url = PBS.socialbookmarks.bookmark_hostname + "/includes/javascript/lib/pbs/sbw_trunk/socialbookmarks_ie_nonstandard.css";
        //var nonstandard_css_url = "socialbookmarks_ie_nonstandard.css";
        $('head').append('<link rel="stylesheet" href="' + nonstandard_css_url + '" type="text/css" />');
    }

});

PBS.socialbookmarks.bookmark_hostname = "http://www.pbs.org";
PBS.socialbookmarks.default_links = ["google","facebook","delicious","digg","mixx","newsvine","stumbleupon","yahoo", "vodpod", "newstrust"];
PBS.socialbookmarks.img_path_ui = PBS.socialbookmarks.bookmark_hostname+"/includes/javascript/lib/pbs/sbw_trunk/images/ui/";
PBS.socialbookmarks.img_path_logo = PBS.socialbookmarks.bookmark_hostname+"/includes/javascript/lib/pbs/sbw_trunk/images/logos/";
PBS.socialbookmarks.pbsBmarkingPageUrl = "";
PBS.socialbookmarks.pbsBmarkingDocTitle = "";

PBS.socialbookmarks.init_color_scheme = { "gray" : {"button": "bttn-gry.png",
                                                    "header": "tp-gry-grdnt.gif",
                                                    "footer": "btm-gry-grdnt.gif"},
                                          "blue" : {"button": "bttn-blu.png",
                                                    "header": "tp-blu-grdnt.gif",
                                                    "footer": "btm-blu-grdnt.gif"},
                                          "green" : {"button": "bttn-grn.png",
                                                     "header": "tp-grn-grdnt.gif",
                                                     "footer": "btm-grn-grdnt.gif"},
                                          "purple" : {"button": "bttn-prpl.png",
                                                      "header": "tp-prpl-grdnt.gif",
                                                      "footer": "btm-prpl-grdnt.gif"}
                                        };

PBS.socialbookmarks.init_bookmark_links = function() {

    $('.pbs_bookmarking_container a#pbs_bookmarking').each(function() {
        PBS.socialbookmarks.pbsBmarkingPageUrl = this.href;
        PBS.socialbookmarks.pbsBmarkingDocTitle = this.title;
    });

    if (!PBS.socialbookmarks.pbsBmarkingPageUrl) {
        PBS.socialbookmarks.pbsBmarkingPageUrl = location.href;
    }

    if (!PBS.socialbookmarks.pbsBmarkingDocTitle)
        PBS.socialbookmarks.pbsBmarkingDocTitle = document.title;

    links = { "google": {"text": "Google",
                                   "href": "http://www.google.com/bookmarks/mark?op=edit&output=popup&bkmk="+encodeURIComponent(PBS.socialbookmarks.pbsBmarkingPageUrl)+'&title='+encodeURIComponent(PBS.socialbookmarks.pbsBmarkingDocTitle),
                                   "alt": "google",
                                   "img": "google.png"},
                      "facebook": {"text": "Facebook",
                                   "href": "http://www.facebook.com/share.php?u="+encodeURIComponent(PBS.socialbookmarks.pbsBmarkingPageUrl)+"&t="+encodeURIComponent(PBS.socialbookmarks.pbsBmarkingDocTitle),
                                   "alt": "Share on Facebook",
                                   "img": "facebook.png"},
                      "delicious": {"text": "Delicious",
                                    "href": "http://del.icio.us/post?v=4&noui&jump=close&url="+encodeURIComponent(PBS.socialbookmarks.pbsBmarkingPageUrl)+"&title="+encodeURIComponent(PBS.socialbookmarks.pbsBmarkingDocTitle),
                                    "alt": "del.icio.us",
                                    "img": "delicious.png"},
                      "digg": {"text": "Digg",
                               "href": "http://digg.com/submit?phase=2&url="+encodeURIComponent(PBS.socialbookmarks.pbsBmarkingPageUrl)+"&title="+encodeURIComponent(PBS.socialbookmarks.pbsBmarkingDocTitle)+"&topic=television",
                               "alt": "Digg!",
                               "img": "digg.png"},
                      "yahoo": {"text": "Yahoo Buzz",
                                "href": "http://buzz.yahoo.com/submit/?"+encodeURIComponent(PBS.socialbookmarks.pbsBmarkingPageUrl),
                                "alt": "Yahoo! Buzz",
                                "img": "buzz.png"},
                      "mixx": {"text": "Mixx",
                               "href": "http://www.mixx.com/submit?page_url="+encodeURIComponent(PBS.socialbookmarks.pbsBmarkingPageUrl),
                               "alt": "Mixx",
                               "img": "mixx.png"},
                      "stumbleupon": {"text": "Stumbleupon",
                                      "href": "http://www.stumbleupon.com/submit?url="+encodeURIComponent(PBS.socialbookmarks.pbsBmarkingPageUrl)+"&title="+encodeURIComponent(PBS.socialbookmarks.pbsBmarkingDocTitle),
                                      "alt": "Stumbleupon",
                                      "img": "stumble.png"},
                      "newsvine": { "text" : "NewsVine",
                                    "href" : "http://www.newsvine.com/_wine/save?aff=pbs&u="+encodeURIComponent(PBS.socialbookmarks.pbsBmarkingPageUrl)+"&h="+encodeURIComponent(PBS.socialbookmarks.pbsBmarkingDocTitle),
                                    "img" : "newsvine.png",
                                    "alt" : "NewsVine"},
                      "vodpod": { "text" : "VodPod",
                                  "href" : "http://vodpod.com/account/add_video_page?p="+encodeURIComponent(PBS.socialbookmarks.pbsBmarkingPageUrl),
                                  "img" : "vodpod.png",
                                  "alt" : "Vodpod"},
                      "newstrust": { "text" : "NewsTrust",
                                    "href" : "http://newstrust.net/submit?ref=pbs&url="+encodeURIComponent(PBS.socialbookmarks.pbsBmarkingPageUrl)+"&title="+encodeURIComponent(PBS.socialbookmarks.pbsBmarkingDocTitle),
                                    "img" : "news-trust.png",
                                    "alt" : "NewsTrust"}
    };

    return links;
};

PBS.socialbookmarks.set_color_scheme = function() {
    if (typeof( window[ 'pbsbookmarking_color' ] ) == "undefined" || !pbsbookmarking_color) {
        return PBS.socialbookmarks.init_color_scheme["gray"];
    } else {

        //TODO: if pbsbookmarking_color value exists in init_color_scheme set.
        return PBS.socialbookmarks.init_color_scheme[pbsbookmarking_color];
    }
};

PBS.socialbookmarks.bookmark_page = function() {
    var url = PBS.socialbookmarks.pbsBmarkingPageUrl;
    var title = PBS.socialbookmarks.pbsBmarkingDocTitle;

    if (window.sidebar && window.sidebar.addPanel) { // firefox
        window.sidebar.addPanel(title, url,"");
    } else if( document.all ) { //MSIE
        window.external.AddFavorite( url, title);
    } else {
        alert('If you are using Safari, press apple-d to save this link.');
    }

    return;
};

PBS.socialbookmarks.init_email_form = function() {

    var img_path_logo = PBS.socialbookmarks.img_path_logo;
    var img_path_ui = PBS.socialbookmarks.img_path_ui;
    var scheme = PBS.socialbookmarks.set_color_scheme();

    //SET CSS VARIBLES
    email_header = {"z-index":"1",
                    "background":"url("+ img_path_ui + scheme.header +") repeat-x 0% 0%"};

    email_footer = {"z-index":"1",
                    "background":"url("+ img_path_ui + scheme.footer +") repeat-x 0% 0%"};

    //INSERT EMAIL DRAWER
    $('#pbs_bookmarking_button').after('<div class="pbs_bookmarking_email_div"></div>');

    //CREATE EMAIL HEADER
    $('.pbs_bookmarking_email_div').prepend('<div class="pbs_bookmarking_email_header"><span><img\> Email to a friend</span></div>');
    $('.pbs_bookmarking_email_header').css(email_header);

    $('.pbs_bookmarking_email_header img').attr({
        src: img_path_logo + "email.png",
        border: "0"
    });

    $('.pbs_bookmarking_email_div').append('<div class="pbs_bookmarking_email_form"></div>');

    //INSERT EMAIL FORM
    $('.pbs_bookmarking_email_form').append('<form method="post" action="'+PBS.socialbookmarks.bookmark_hostname+'/cgi-registry/SBMW_tell_a_friend.cgi" id=pbs_bookmarking_email_form>\
                            <ul class="pbs_bookmarking_form_ul"> \
                            <li class=pbs_bookmarking_email_li><label for="recipent">To:</label>\
                            <input type="text" name="recipient" id="to" size="26"\></li>\
                            <li class=pbs_bookmarking_email_li><label for="note">Note:</label>\
                            <textarea cols="28" rows="3" name="content" id="pbs_bookmarking_content"\></textarea></li>\
                            <li class=pbs_bookmarking_btn_li><div><input type="submit" name="submit" value="send" id="pbs_bookmarking_form_button"\>\
                            or <a href="javascript:void(0);" onclick="javascript:PBS.socialbookmarks.cancel_email_form()">cancel</a></div></li>\
                            </ul>\
                            <input type=hidden name=subjectline value="PBS Send to a friend"> \
                            <INPUT TYPE=hidden NAME="location" VALUE="'+PBS.socialbookmarks.pbsBmarkingPageUrl+'"> \
                            </form>');

    $('.pbs_bookmarking_email_div').append('<div class="pbs_bookmarking_email_footer"><span><a href="http://www.pbs.org/engage">Powered by PBS Engage</a></span></div>');
    $('.pbs_bookmarking_email_footer').css(email_footer);

    //HIDE EMAIL DRAWER
    $('.pbs_bookmarking_email_div').hide();

    //MOUSE LEAVE HIDE EMAIL DRAWER
    $('.pbs_bookmarking_email_div').bind("mouseleave",function () {
        $(this).hide();
    });

    PBS.socialbookmarks.validate_email_address();

};

PBS.socialbookmarks.validate_email_address = function() {
    $("#pbs_bookmarking_form_button").click(function () {
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        if(reg.test($('#to').val()) == false) {
            $('#to').css({"border":"1px solid red"});
            alert('Invalid Email Address');
            return false;
        }
        PBS.socialbookmarks.format_email_message();
    });
};

PBS.socialbookmarks.format_email_message = function() {

    var url = PBS.socialbookmarks.pbsBmarkingPageUrl;
    var personal_msg = 'Personal Message:\n'+$('#pbs_bookmarking_content').val()+'\n\n';
    var link = 'Link:\n'+url+'\n\n';
    var email_disclaimer = "\nPlease do not reply to No-Reply-PBSCommunity@pbs.org, as we are not able to respond to messages sent to this address. If you would like to respond to this message please visit our feedback page at http://www.pbs.org/aboutsite/aboutsite_feedback.html";
    var pbs_msg = "Hello,\n\nA friend has sent you a link from PBS.  Check it out and pass it along to more friends.  Be sure to explore what else PBS has to offer while you are at it.\n\n";
    $('#pbs_bookmarking_content').val(pbs_msg+personal_msg+link+email_disclaimer);

};

PBS.socialbookmarks.cancel_email_form =  function() {
    $('#to').val("");
    $('#pbs_bookmarking_content').val("");
    $('.pbs_bookmarking_email_div').hide();
};

PBS.socialbookmarks.show_email_form =  function() {
    $('.pbs_bookmarking_links_div').hide();
    $('.pbs_bookmarking_email_div').show();
};

PBS.socialbookmarks.init_bookmark_container = function() {

    //INITALIZE LOCAL VARIBLES
    var links = PBS.socialbookmarks.init_bookmark_links();
    var img_path_logo = PBS.socialbookmarks.img_path_logo;
    var img_path_ui = PBS.socialbookmarks.img_path_ui;
    var scheme = PBS.socialbookmarks.set_color_scheme();
    var link_list = "";

    //SET CSS VARIBLES
    li_footer = {"z-index":"0",
                 "background":"url("+ img_path_ui + scheme.footer +") repeat-x left bottom"};

    li_header = {"z-index":"0",
                 "background":"url("+ img_path_ui + scheme.header +") repeat-x left top"};

    //LOOP THUR LINKS, BUILD LINK LIST
    if (typeof( window[ 'pbsbookmarking_links' ] ) == "undefined" || !pbsbookmarking_links) {
        pbsbookmarking_links = PBS.socialbookmarks.default_links;
    }

    $.each(pbsbookmarking_links, function() {
        link = links[this];

        link_list += '<li class="pbs_bookmarking_links_li">\
                     <a title=" '+ link.alt +' " href="' + link.href + '" onclick="javascript:pageTracker._trackEvent(\'Social Bookmarks\', \'' + link.text +'\', \''+ location.href  +'\');" target="_blank"><img src="' + img_path_logo + link.img + '"/>' + link.text +'</a>\
                     </li>';
    });
    link_list += '<li class="pbs_bookmarking_links_li_footer"></li><li class="pbs_bookmarking_links_li_footer"><span><a href="http://www.pbs.org/engage">Powered by PBS Engage</a></span></li>';

    // CREATE LINKS CONTAINER DIV
    $('#pbs_bookmarking_button').after('<div class="pbs_bookmarking_links_div"></div>')

    // INSERT UNORDERED LIST OF LINKS INTO CONTAINER DIV
    $('.pbs_bookmarking_links_div').prepend('<ul class="pbs_bookmarking_links_ul">\
        <li class="pbs_bookmarking_links_li_header">\
        <a href=javascript:void(0); onclick=\"javascript:PBS.socialbookmarks.bookmark_page(); pageTracker._trackEvent(\'Social Bookmarks\', \'Favorites\', \''+ location.href  +'\'); return false;" class="favorites"><img\> Favorites</a></li>\
        <li class="pbs_bookmarking_links_li_header">\
        <a href="javascript:void(0);" onclick="javascript:PBS.socialbookmarks.show_email_form();pageTracker._trackEvent(\'Social Bookmarks\', \'Email\', \''+ location.href  +'\'); return false;" class="email"><img\> Email</a>\
        </li>'
        + link_list +
        '</ul>');

    //ASSIGN ATTRIBUTES TO IMG TAGS FOR EMAIL AND FAVORITE LINKS
    $('.favorites img').attr({
        src: img_path_logo + "star.png"
    });

    $('.email img').attr({
        src: img_path_logo + "email.png"
    });

    //APPLY STYLE TO BOOKMARKING ELEMENTS
    $('.pbs_bookmarking_links_li_header').css(li_header);
    $('.pbs_bookmarking_links_li_footer').css(li_footer);
    $('.pbs_bookmarking_links_div').hide();
};

PBS.socialbookmarks.setup_widget = function() {

    //INTIALIZE LOCAL VARIBLES
    scheme = PBS.socialbookmarks.set_color_scheme();
    img_path_ui = PBS.socialbookmarks.img_path_ui;

    //INSERT DIV AND UL TAGS
    $('.pbs_bookmarking_container').prepend('<ul class="pbs_bookmarking_main_ul"></ul>');
    $('.pbs_bookmarking_main_ul').prepend('<li class="pbs_bookmarking_main_li"></li>');
    $('.pbs_bookmarking_main_li').prepend('<img />');

    //ASSIGN ATTRIBUTES TO BUTTON IMG
    $('.pbs_bookmarking_main_li img').attr({
          src: img_path_ui + scheme['button'],
          alt: "PBS Social Bookmarking button",
          id: "pbs_bookmarking_button"
    }).css({"border":"0"});

    //INSERT LINKS/EMAIL CONTAINERS
    PBS.socialbookmarks.init_bookmark_container();
    PBS.socialbookmarks.init_email_form();

    //INITIALIZE HOVER EVENT
    $('li.pbs_bookmarking_main_li').hover(
    //  function() { $('.pbs_bookmarking_links_div', this).show(); },
        function() {

            // get the div we're going to show
            var linksdiv = $(".pbs_bookmarking_links");
            var x = $(".pbs_bookmarking_container").offset().left;
            var y = $(".pbs_bookmarking_container").offset().top;
            // get the scroll offsets
            var scroll = {top: $(window).scrollTop(), left: $(window).scrollLeft()};
            var pos = {top: 16, left: 0}; // add padding
            var screen = {right: scroll.left + $("body").width(), bottom: scroll.top + $(window).height()};
            // if we're going to be off the screen, adjust the position
            if( x + 252 > screen.right ){
                // don't move past most right of screen
                pos.left = screen.right - 252;
            }
            if( y + 158 > screen.bottom ){
                // don't move past most right of screen
                pos.top = pos.top - 158;
            }
            // position the
            $('.pbs_bookmarking_links_div').css(pos);
            $('.pbs_bookmarking_links_div').show();
        },
        function() { $('.pbs_bookmarking_links_div', this).hide(); });
};
