var dD = document;
if(navigator.appName == "Microsoft Internet Explorer") {
  ajax = new ActiveXObject("Microsoft.XMLHTTP");
} else {
  ajax = new XMLHttpRequest();
}

/**
 * Share functions
 *
 * Adds share box into <div id="share-jokes"></div>
 */
var sT; // Share title
var sU; // Share url
var oT; // Unencoded share title

var sS = Array(
        Array('Twitter', 'tw'),
        Array('Facebook', 'fb'),
//        Array('MySpace', 'ms'),
        Array('StumbleUpon', 'su'),
//        Array('Delicious', 'dl'),
        Array('Digg', 'dg'),
        Array('Email', 'email'),
//        Array('Bookmark', 'bmark'),
        Array('More Share Options', 'more')
    );

function share_joke(id, t, u) {
    oT = t;
    sT = encodeURIComponent(t);  //.replace(/\'/g,'\\\'');  // .replace is used to add Slashes around single quotes
    sU = encodeURIComponent(u);
    var o = '<div style="background:#333;margin-left:24px;margin-bottom:4px;padding-bottom:6px"><div style="margin:0 0 6px 6px;height:16px> '+gen_static_stars(4.5)+'</div><div class="Dirty" style="margin-left:24px">&nbsp;</div></div>\
    <ul><b style="color:#336633">Share</b><hr style="margin:0 0 4px 0;line-height:1px">';
        for(var i=0; i<sS.length; i++) {
            o+= '<li class="s_'+sS[i][1]+'" onclick="sW(\''+sS[i][1]+'\')" title="'+sS[i][0]+'">'+sS[i][0]+'</li>';
            if (i==3) o+= '<hr>';
        }
    o+= '</ul>\
    <div id="fb_like" style="text-align:right"></div>';   // REMOVED: margin-right:-10px
    dD.getElementById(id).innerHTML = o;
}

function gen_static_stars(r) {  // r is rating	// Used at the top of the page
    var c = 'smlStr1';  // Gold image class
    var o = '<ul>';
    for (var i=0; i<6; i++) {
        if (r<i) {
            c = 'smlStr3'; // Grey image class
            if (r<=(i-.5)) c = 'smlStr2'; // Half image class
        }
        o += '<li class="'+c+'" style="list-style:none;float:left">&nbsp;</li>';
    }
    o += '</ul>\
    <div class="clr"></div>';
    return o;
}

function sW(s) {  // Open a share window for the relevant site, s is site to open
    var wW = 800;   // window height
    var wH = 600;   // window width
    var wS = 1;       // Scrollbars on or off
    var wU;           // URL to open in window

    switch(s) {
        case 'tw':
            wU = 'http://twitter.com/home?status=Check%20out%20this%20joke%20%22'+sT+'%22 at '+sU+' via @thejokeyard';
        break;

        case 'fb':
            wU = 'http://www.facebook.com/sharer.php?u='+sU+'&t='+sT;
            wW = 626;wH = 436;wS = 0;
        break;

//        case 'ms':
//            wU = 'http://www.myspace.com/Modules/PostTo/Pages/?L=2&U='+sU+'&T='+sT+'&C=Check out this joke %22'+sT+'%22 from www.thejokeyard.com';
//            wW = 626; wH = 436; wS = 0;
//        break;

        case 'su':
            wU = 'http://www.stumbleupon.com/submit?url='+sU+'&title='+sT;
        break;

//        case 'dl':
//            wU = 'http://delicious.com/save?v=5&noui&jump=close&url='+sU+'&title='+sT;
//        break;

        case 'dg':
            wU = 'http://digg.com/submit?url='+sU+'&title=Joke:%20'+sT+'&media=news&topic=comedy';
            wW = 920;
        break;

        case 'email':
            wU = 'http://api.addthis.com/oexchange/0.8/forward/email/offer?url='+sU+'&title='+sT+'&username=thejokeyard&lng=en-us';
        break;

        case 'more':
            wU = 'http://www.addthis.com/bookmark.php?username=thejokeyard&title='+sT+'&url='+sU;
        break;

    }

    window.open(wU, s+'sharer', 'toolbar=0,status=0,width='+wW+',height='+wH+',scrollbars='+wS);
}


/**
 * Facebook Like Function
 *
 */

function fbLike(id,u) {
    window.onload = function(){
        u = 'https://www.facebook.com/pages/TheJokeYard/126780427370838';
        dD.getElementById(id).innerHTML = '<div id="twsh" style="margin:0 -16px 4px 0"></div><div style="margin:0 -14px 4px 0"><g:plusone size="medium" href="http://www.thejokeyard.com/"></g:plusone></div><iframe src="http://www.facebook.com/plugins/like.php?href='+u+'&amp;layout=button_count&amp;show_faces=false&amp;width=80&amp;action=like&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:80px; height:21px;" allowTransparency="true"></iframe>';  // the 1st div adds holder for twitter share button
        twShr('twsh');
        goShr();
        sTwiBtn('twi');
    }
    
}

function twShr(id) {  // Twitter share button, id is div to place button in
    //window.onload = function(){    // Not needed because fbLike is in onload event
        dD.getElementById(id).innerHTML = '<a href="http://twitter.com/share" class="twitter-share-button" data-text="Check out this joke &quot;'+oT+'&quot; at " data-count="horizontal" data-via="thejokeyard">Tweet</a>';
        var s = dD.createElement("script");
        s.setAttribute('src', 'http://platform.twitter.com/widgets.js');
        dD.getElementById(id).appendChild(s);
    //}
}

function goShr() {  // Google +1 share button, id is div to place button in
        var s = dD.createElement("script");
        s.setAttribute('src', 'https://apis.google.com/js/plusone.js');
        dD.body.appendChild(s);
}


//function btmBan() {  // Banner layer across bottom of page
//    if ( !navigator.cookieEnabled || (getCookie('bt1-stop') == 1) || (screen.height < 600) ) return;  // dont show if no cookies or cookie is set or screen is too small
//    var b = dD.getElementsByTagName("body")[0];
//    var d = dD.createElement("div");
//    d.setAttribute("id", "btmban");
//    b.appendChild(d);
//       
//    // By now we've added a div with id btmban to end of body
//    dD.getElementById("btmban").innerHTML = '\
//    <div style="z-index:5;width:100%;height:44px;background:#996600;border-top:2px solid #663300">\
//      <div style="z-index:15;float:right;position:relative;text-align:right;top:2px;right:10px;font-size:10px;font-weight:bold;"><a onClick="hideBtmBan();return true;" style="color:#663300;cursor:pointer;">Close &amp; Don\'t Show Again</a></div>\
//      <div style="position:relative;overflow:visible;font-weight:bold;font-size:20px;text-align:center;padding-top:8px">Get our daily joke or funny video, <a href="http://www.twitter.com/thejokeyard" target="_blank" rel="nofollow"><img src="/img/foltwi.png" style="border:0;height:68px;width:120px;position:absolute;top:-22px"></a><span style="display:inline-block;width:120px"></span> OR &nbsp; <iframe src="http://www.facebook.com/plugins/like.php?href=https://www.facebook.com/pages/TheJokeYard/126780427370838&amp;layout=button_count&amp;show_faces=false&amp;width=80&amp;action=like&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:80px; height:21px;" allowTransparency="true"></iframe></div>\
//   </div>\
//    ';
//}
//function hideBtmBan() {
//    dD.getElementById("btmban").style.display="none";
//    setCookie('bt1-stop',1,30);
//}
//
//
//function setCookie(n,v,ex) {  // Cookie name, value and expires days
//    var exd=new Date();
//    exd.setDate(exd.getDate() + ex);
//    var cv=escape(v) + ((ex==null) ? "" : "; expires="+exd.toUTCString());
//    dD.cookie=n + "=" + cv + ';path=/;domain=thejokeyard.com';
//}
//
//function getCookie(n) {  // n = cookie name
//    var i,x,y,ac=dD.cookie.split(";");  // ac = array of cookies
//    for (i=0;i<ac.length;i++) {
//        x=ac[i].substr(0,ac[i].indexOf("="));
//        y=ac[i].substr(ac[i].indexOf("=")+1);
//        x=x.replace(/^\s+|\s+$/g,"");
//        if (x==n) return unescape(y);
//    }
//}



function sTwiBtn(id) {	// Show Twitter Button
	dD.getElementById(id).innerHTML = '<a href="http://www.twitter.com/thejokeyard" target="_blank" rel="nofollow"><img src="/img/twi.png" height="80" width="160"></a>';
}







/**
 * Rate function
 *
 * Call using: setStars(<element-id>, <num-stars>);
 *
 */
var set = 0;
var sC1 = "star-grey";  // Sprite class name 1, used initially
var sC2 = "star-gold";  // Sprite class name 2, used on hover
var sC3 = "star-blue";  // Sprite class name 3, used on flash when submitted
var jid;				// Joke id
function getClasses(x) {
    return x.getAttribute('class').split(" ");  // Retrieve class list, c[0] Should give star1, star2 etc
}
function getElements() {
    return dD.getElementById("star-rate").getElementsByTagName('li');     // Grab all elements within given id, and having given tag type
}
function getStarNum(c) {  // Takes class name like star5 and returns 5
    if (c[0].length>5) var n = parseInt(c[0].substr(c[0].length-2));
    else var n = c[0][c[0].length-1];
    return n;
}
function hoverStars(x) {
    if (set) return;
    nav = true;
    var c = getClasses(x);
    var n = getStarNum(c);  // Star number. ie 1 2

    var t = '1 Star';if (n>1) t = n+" Stars";
    dD.getElementById('starTxt').innerHTML = t;

    var elem = getElements();
    for (var i=0; i<elem.length; i++) {
        c = elem[i].className.split(" ");  // Split found classes like "star1 star-grey"
        y = getStarNum(c);  // Star number of this element
        if (y > n) {  // Unset this star
            elem[i].setAttribute("class", c[0]+" "+sC1);
        }
        else elem[i].setAttribute("class", c[0]+" "+sC2);
    }
}
function resetStars() {
    if (set) return;
    var elem = getElements();
    for (var i=0; i<elem.length; i++) {
        c = elem[i].className.split(" ");
        elem[i].setAttribute("class", c[0]+" "+sC1);
    }
    dD.getElementById('starTxt').innerHTML = "Choose a star";
}
function submitStars() {
    if (set) return;
    set = 1;  // Locks the stars
    var elem = getElements();
    var n=0;
    for (var i=0; i<elem.length; i++) {
        c = elem[i].className.split(" ");
        if (c[1] == sC2) n++;
    }
    flashStars(1);
    dD.getElementById('starTxt').innerHTML = "Thank You";

    n=n*2;  // double because we're using 5 stars and not 10
    ajax.open("GET", "/v4/tools/rate/?id="+jid+"&rating="+n);
    ajax.send(null);
}
function flashStars(n) {
    var elem = getElements();
    for (var i=0; i<elem.length; i++) {
        c = elem[i].className.split(" ");
        if (c[1] == sC2) elem[i].setAttribute("class", c[0]+" "+sC3+" starset");
        else if (c[2] == 'starset') elem[i].setAttribute("class", c[0]+" "+sC2+" starset");
    }
    if (n<4) setTimeout("flashStars("+(n+1)+")",300);
}
function setStars(id, n, j) {
    jid=j; // joke id
    var o = '<b style="color:#666666">Rate this Joke</b>\
    <ul style="margin-left:40px" onclick="submitStars()" onmouseout="resetStars()">';
    for (var i=1; i<=n; i++) {
        o += '<li class="star'+i+' star-grey" onmouseover="hoverStars(this)">&nbsp;</li>';
    }
    o += '</ul>\
    <div class="clr"></div>\
    <div id="starTxt" style="font-size:9px;text-align:center">Choose a star</div>';
    dD.getElementById(id).innerHTML = o;
}
