var foobar=1;

/* Log a sharing hit via ajax */
function logSharingHit( t, k ) { 
	$.post(
		"sharing_bar.cgi",
		{ "cmd": "log_hit", "type": t, "key": k },
		function(data) { 
		}
	);
}

function noop(v) { return v; }

function testit(ev, e) { 
   var pos = getMouseOffset(e, ev);
   var t=document.getElementById('testit');
   t.innerHTML = 'x='+pos.x+', y='+pos.y;
}

// When the mouse goes over the stars, update them as the user slides
function updateRatingStars(ev, e) { 
   var pos = getMouseOffset(e, ev);
   var n = getStarCount(ev,e);
   e.src = '/images/hotstar'+n+'.png';

   // Set a div with some data on our usage.
   //var t=document.getElementById('testit');
   //t.innerHTML = 'x='+pos.x+', y='+pos.y+'<br>n='+n;
}
// Find which star based on position inside the click
// Each star is 1/5th of the image.  
function getStarCount(ev, e) {
   var pos = getMouseOffset(e, ev);

   // This assumes a particular image size.
   //var n = Math.round( (pos.x/18) );

   // Instead, assume little padding and uniform star sizes
   var star_size = Math.round( e.width / 5 );
   var n = Math.round( (pos.x / star_size) + 0.50 );

   if (n < 1 ) { n = 1; }
   if (n > 5 ) { n = 5; }
   return n;
}

// When the mouse leaves the stars, reset to the current average 
function resetRatingStars(e, n) { 
   e.src = '/images/hotstar'+n+'.png';
}

// When the stars are clicked, record the rating and update the 
// stars image to be static/already rated.
function rateResource(ev, e, pkg_type, resource_id, url) {
   // The div element containing the images, so we can replace it.
   var rating_e = document.getElementById('rating_stars');
   var rating_e_ie = document.getElementById('rating_stars_ie');

   // Get the rating selected
   var n = getStarCount(ev,e);

   // The name of the cookie to test for already-rated
   var cookie_name = 'rate_'+pkg_type+'_'+resource_id;

   // A test div to write data to
   //var t=document.getElementById('testit');
   //t.innerHTML = 'Set rate='+n;

   // Has this user already rated this resource?
   var cookie_val = getCookie(cookie_name);
   if (cookie_val) { 
      //alert("You've already rated this resource.");    
      parent.Shadowbox.open({
         content: '<div style="background-color:#fff;padding:25px;color:#000;height:50px;border:2px solid black;">You have already rated this resource.</div>',
         player: 'html',
         title: '',
         animate: false,
         height: 120,
         width: 220,
         handleOversize: 'none'
      }); 

      t.innerHTML = 'Already rated.';
      return;
   }


   // Post it to the server
   $.post(
		"sharing_bar.cgi",
		{ "cmd": "rate",
          "p": pkg_type,
          "i": resource_id,
          "u": url,
          "stars": n,
          "ajax": 1
        },
		function(data) { 
           if (data >= 1 && data <= 5) { 
              // Replace the image with a "cold" one, with the right rating.
		      //rating_e.innerHTML = '<a href="javascript:return noop(false);"><img src="/images/coldstar'+data+'.png" width=92 height=16></a>';

              // Display cold stars with the user's rating, not the new avg
              if (rating_e) { rating_e.innerHTML = '<a href="javascript:return noop(false);"><img src="/images/coldstar'+n+'.png" width=92 height=16></a>'; }
		      if (rating_e_ie) { rating_e_ie.innerHTML = '<a href="javascript:return noop(false);"><img src="/images/coldstar'+n+'.png" width=92 height=16></a>';}

              // Set cookie to disallow re-rating.
              setCookie(cookie_name, 1, 1);
           }
		}
	);

}


// Get the Coordinates of the mouse 
function mouseCoords(ev){
    // Different browsers work differently. 
    // Firefox uses event.pageX and event.pageY for event coordinates - 
    // relative to the document.
    // MSIE uses clientX and clientY, and they're relative to the window,
    // not the document.  MSIE also put a small border around the window.
    if(ev.pageX || ev.pageY){
        return {x:ev.pageX, y:ev.pageY};
    }
    return {
        x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
        y:ev.clientY + document.body.scrollTop  - document.body.clientTop
    };
}

// Get the mouse coordinates relative to a target (e.g. an image)
// Subtract the coordinates of the target from those of the event.
function getMouseOffset(target, ev){
    ev = ev || window.event;

    var docPos    = getPosition(target);
    var mousePos  = mouseCoords(ev);
    return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
}


// Get the position of an element.
function getPosition(e){
    var left = 0;
    var top  = 0;

    // Work our way up the element tree adding in the left/top pieces
    // of each one.
    while (e.offsetParent){
        left += e.offsetLeft;
        top  += e.offsetTop;
        e     = e.offsetParent;
    }

    left += e.offsetLeft;
    top  += e.offsetTop;

    return {x:left, y:top};
}

// Set a cookie to a value (to track ratings via XHTML etc)
function setCookie (cookieName,cookieValue,nDays) {
   var today  = new Date();
   var expire = new Date();
   if (nDays==null || nDays==0) { nDays=1; }

   expire.setTime(today.getTime() + 3600000*24*nDays);

   document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString();

}

// Get the value of a cookie
function getCookie (cookieName) {
   var theCookie=""+document.cookie;
   var ind=theCookie.indexOf(cookieName+'=');
   if (ind==-1 || cookieName=="") return ""; 
   var ind1=theCookie.indexOf(';',ind);
   if (ind1==-1) ind1=theCookie.length; 
   return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}

// The Rate & Share feature in the search-result tables pops up a 
// shadow-box with the same rating/sharing content as the external 
// redirect interstitial page.
function rateAndShare(pkg,rid,url) {

	$.post('sharing_bar.cgi',
		{ "cmd": "rateshare", "p": pkg, "i": rid, "u": url },
		function(data){ 

			parent.Shadowbox.open({
				content: data,
				player: 'html',
				title: '',
				animate: false,
				height: 450,
				width: 650,
				handleOversize: 'none'
			}); 

		}
	);
}

// Within the Rate & Share box, we have an Email function. This function
// in other contexts opens a shadowbox for the email function. Since it's
// being called from within a Shadowbox, making it work there is complex.
// For now, just open a new window.
function emailWindow( pkg_type, resource_id, url) { 
   var open_url = '/sharing_bar.cgi?cmd=email&w=1&p='+pkg_type+'&i='+resource_id+'&u='+escape(url);
   top.window.open( open_url, 'Share by Email', 'width=600,height=400' );
}

function click_facebook() { 
    logSharingHit( 'facebook', '::shortcut_key::' );

    // This doesn't work... it kills the href being followed for some
    // reason. If we need to close the shadowbox when facebook is clicked,
    // then we need to manually open the new browser window.
    //parent.Shadowbox.close();

    return true;
}
function click_twitter() { 
    logSharingHit( 'twitter', '::shortcut_key::' );

    // This doesn't work... it kills the href being followed for some
    // reason. If we need to close the shadowbox when twitter is clicked,
    // then we need to manually open the new browser window.
    //parent.Shadowbox.close();

    return true;
}
function click_delicious() { 
    logSharingHit( 'delicious', '::shortcut_key::' );

    // This doesn't work... it kills the href being followed for some
    // reason. If we need to close the shadowbox when delicious is clicked,
    // then we need to manually open the new browser window.
    //parent.Shadowbox.close();

    return true;
}

function click_diigo() { 
    logSharingHit( 'diigo', '::shortcut_key::' );

    // This doesn't work... it kills the href being followed for some
    // reason. If we need to close the shadowbox when delicious is clicked,
    // then we need to manually open the new browser window.
    //parent.Shadowbox.close();

    return true;
}


