// Store some "global" state flags
var oldpane;
var oldtab;
var page_pane_id='';

// Display the selected "pane" of Tips info
function show_pane(pane_id) { 
   var pane = document.getElementById('tip_pane_'+pane_id);
   var tab  = document.getElementById('tip_tab_'+pane_id);

   if (!oldpane)   { oldpane=document.getElementById('tip_pane_resource');}
   if (!oldtab)    { oldtab=document.getElementById('tip_tab_resource');}

   pane.style.display='block'; 
   if (oldpane != pane) { 
      if (oldpane) {
         oldpane.style.display='none';
      }
      oldpane=pane;
   }

   if (tab) { 
      tab.className = 'tip_tab_active';
      if (oldtab != tab) { 
         if (oldtab) {
            oldtab.className = 'tip_tab';
         }
         oldtab=tab;
      }
   }

   if (page_pane_id != pane_id) { 
      //These don't work... "old" version gets corrupted somehow
      //MM_swapImgRestore();
      //MM_swapImage('tab_img_'+pane_id,'','images/tab-'+pane_id+'-on.gif');
      //Manually turn on/off new/old images
      if (page_pane_id) { 
         var oldimg = document.getElementById('tab_img_'+page_pane_id);
         if (oldimg) {
            oldimg.src = 'images/tab-'+page_pane_id+'-off.gif';
         }
      }
      var img = document.getElementById('tab_img_'+pane_id);
      if (img) { 
         img.src = 'images/tab-'+pane_id+'-on.gif';
      }
      page_pane_id = pane_id;
   }
}

function tip_swapImage(this_pane,img,empty,newsrc) {
   if (this_pane != page_pane_id) {
      MM_swapImage(img,empty,newsrc);
   }
}
function tip_swapImgRestore(this_pane) {
   if (this_pane != page_pane_id) {
      MM_swapImgRestore();
   }
}

function new_tip(){
   document.tip_form.tip_id.value = 0;
   document.tip_form.action.value = "new";
   document.tip_form.submit();
}

function reply_to(id,p) { 
   document.tip_form.tip_id.value = id;
   document.tip_form.action.value = "new";
   document.tip_form.p.value = p;
   document.tip_form.submit();
}

function email_tip(id,p) { 
   document.tip_form.tip_id.value = id;
   document.tip_form.action.value = "email";
   document.tip_form.p.value = p;
   document.tip_form.submit();
}

function request_tip(id,p) { 
   document.tip_form.tip_id.value = id;
   document.tip_form.action.value = "request";
   document.tip_form.p.value = p;
   document.tip_form.submit();
}

function show_more(pane_id,id) {
   var e = document.getElementById('tip_text_'+id+'_'+pane_id);
   if (e) {
      var xmlHTTP = getXMLHTTP();
      var geturl = 'tip.cgi?action=text&i='+id+'&p='+pane_id;
      if (xmlHTTP) { 
       // Do things synchronously.
       document.body.style.cursor='wait';
       xmlHTTP.open("GET",geturl,false);
       xmlHTTP.send(null);
       document.body.style.cursor='auto';
       data=xmlHTTP.responseText;
       e.innerHTML = data;
      }
   }
}

function show_hover(event, pane_id) {

   var h = document.getElementById('hover_box');
   var xy = mouseCoords(event);
   h.style.left = (xy.x+ 20) + 'px';
   h.style.top  = (xy.y+ 30) + 'px';
   h.innerHTML = document.getElementById('hover_box_'+pane_id).innerHTML;
   h.style.display='block';
}

function hide_hover() {

   var h = document.getElementById('hover_box');
   h.style.display='none';
   h.innerHTML = '';

}

// Some global state flags for rating hovers
var hover_on=new Array();

// Rating stars have a pop-up/hover that says "View this resource before
// rating it".  We want to link to that resource, so each hover box is
// different...
// The page should have a div id=rating_hover, even if it starts empty.
function rating_hover(event,pkg_type,resource_id,odd,url,new_window,hide_stars) {

   // don't show pop-up if the user has already rated item
   var cookie_name = 'rate_'+pkg_type+'_'+resource_id;
   var cookie_val = getCookie(cookie_name);
   if (cookie_val) { 
      alert("You have already rated this resource."); 
      return;
   }

   // don't show pop-up if the rating stars are already displayed because
   // the user has visited the link.
   if (hover_on[cookie_name]) { 
      return;
   } 

   var h = document.getElementById('rating_hover');
   var xy = mouseCoords(event);
   h.style.left = (xy.x - 200) + 'px';
   h.style.top  = (xy.y - 10) + 'px';

   new_html = "";
   if (new_window) { target=" target='_blank' ";}  else { target=""; }
   if (hide_stars) { show=""; } 
   else { show="showEntryRating("+pkg_type+","+resource_id+",'"+odd+"');"; }

   new_html = "Please view <a href='"+url+"'"+target+" onClick=\""+show+"close_rating_hover();\">this resource</a> before rating. ";

   h.innerHTML = new_html;
   h.innerHTML += " (<a href=\"javascript:close_rating_hover();\">Close</a>) ";
   h.style.display='block';
}

function close_rating_hover() { 
   var h = document.getElementById('rating_hover');
   h.style.display='none';
}

function close_div(div_id) {
   var h = document.getElementById(div_id);
   h.style.display='none';
}

// Re-use a single div and place it in place over the table row.
// This displays the Rating pop-up with the active stars for the user
// to select a rating.
function showEntryRating(pkg_type,resource_id,odd) {

   // don't show pop-up if the user has already rated item
   // don't display error here... just don't display pop-up. User can
   // revisit resource.
   var cookie_name = 'rate_'+pkg_type+'_'+resource_id;
   var cookie_val = getCookie(cookie_name);
   if (cookie_val) { 
      //alert("You have already rated this resource."); 
      return;
   }

   // Signed-in only
   var user_cookie_val = getCookie('teachingbooks');
   if (user_cookie_val.indexOf('division_id') < 0) { 
      return;
   }

   // Mark this box as on
   hover_on[cookie_name] = 1;

   var code = pkg_type+'_'+resource_id;
   var e = document.getElementById('table_rating_overlay');

   // Position block over table row
   var target = document.getElementById('entry_'+code);
   var rowPos = getPosition(target);

   e.style.left = rowPos.x+150+'px'; 
   e.style.top=rowPos.y+4+'px';

   // Insides of element are new form
   var html = '';
   html += '<form id="rating_form_'+code+'" name="rating_form_'+code+'" action="rate.cgi" method="GET">';


   html += '<input type=hidden name="action" value="rate">';
   html += '<input type=hidden name="r" value="'+pkg_type+'">';
   html += '<input type=hidden name="i" value="'+resource_id+'">';
   html += '<input type=hidden id="s_'+code+'" name="s" value="">';
   html += '<img id="rating_stars_'+code+'" ';
     html += 'onMouseMove="update_stars(event,\'rating_stars_'+code+'\',\'s_'+code+'\');" ';
     html += 'onMouseUp="send_rating(event,document.rating_form_'+code+',\'table_rating_overlay\',\'star_img_'+code+'\',\''+odd+'\')" ';
     html += 'src="/images/rate0.gif" align=right>';

   html += "<b>Please rate this resource:</b><br>\n";
   html += '<a href="javascript:hideEntryRating('+pkg_type+','+resource_id+');">Close</a>';

   html += '</form>';

   e.innerHTML = html;

   // Make block appear
   e.style.display = 'block';
}

function hideEntryRating(pkg_type,resource_id) {
   var code = pkg_type+'_'+resource_id;
   var e = document.getElementById('table_rating_overlay');
   if (!e) { return; }
   e.style.display = 'none';

   // Note that the box is no longer on
   var cookie_name = 'rate_'+pkg_type+'_'+resource_id;
   hover_on[cookie_name] = 0;
}

// Show Rating stars pop-up/overlay on Readings or AP page
function showPageRating(id) { 

   // don't show pop-up if the user has already rated item

   var pkg_type = 0;
   var resource_id = 0;
  
   pkg_type    = document.rating_form.r.value;
   resource_id = document.rating_form.i.value;

   var cookie_name = 'rate_'+pkg_type+'_'+resource_id;
   var cookie_val = getCookie(cookie_name);
   if (cookie_val) { 
      alert("You have already rated this resource."); 
      return;
   }

   // HTML pre-built on pages; just turn it on.
   show_overlay(id);
}

// Hide away the Rating stars pop-up/overlay on Readings or AP page
function hidePageRating(id) {

   // HTML pre-built on pages; just turn it off.
   hide_overlay(id);

}


// Update the stars image based on the relative location of the cursor
function update_stars(ev,img_id,form_id) { 

   // Get location of mouse inside image
   var img = document.getElementById(img_id);
   var pos = getMouseOffset(img,ev);
   
   // Get x position on scale of 1-5
   var n = Math.round((pos.x / 141) * 5+0.4);
   if (n < 1) { n = 1; }
   if (n > 5) { n = 5; }

   // Update stars image accordingly
   //img.src="/images/"+n+"stars.gif";
   img.src="/images/rate"+n+".gif";
  
   // If we also have a form element, set the value
   if (form_id) { 
      var item = document.getElementById(form_id);
      item.value = n;
   }

}

// Send a new rating to the db for saving, then close the rating window
function send_rating (ev, data, div_id, img_id, odd) { 

   var r = data.r.value;
   var i = data.i.value;
   var s = data.s.value;

   var cookie_name = 'rate_'+r+'_'+i;
   var cookie_val = getCookie(cookie_name);
   if (cookie_val) { 
      alert("You've already rated this resource.");
   } else {

      var xmlHTTP = getXMLHTTP();
      var geturl = 'rate.cgi?action=rate&i='+i+'&r='+r+'&s='+s;
      if (xmlHTTP) { 
         // Do things synchronously.
         document.body.style.cursor='wait';
         xmlHTTP.open("GET",geturl,false);
         xmlHTTP.send(null);
         document.body.style.cursor='auto';
         data=xmlHTTP.responseText;
         var new_rate = data.split(',');
         var new_count = new_rate[0];         
         var new_total = new_rate[1];         
         var new_avg   = Math.round(new_total / new_count);

         if (img_id) { 
            var img = document.getElementById(img_id);
            if (img) { 
               img.src="/images/"+new_avg+"stars"+odd+".gif";
            }
         }
         var count = document.getElementById("rc_"+r+"_"+i);
         if (count) { 
            count.innerHTML = "("+new_count+")";
         }
         setCookie(cookie_name, 1, 1);
         //alert("Thank you for rating this resource.");
         var d= document.getElementById(div_id);
         if(d) { 
            var h = '<p>Thank you for rating this resource.';
            h += " (<a href=\"javascript:close_div('"+div_id+"');\">Close</a>) ";

            // We need to keep the hidden form elements around for later
            // already-rated pop-up code
            h += "<form id='rating_form' name='rating_form'>";
            h += "<input type='hidden' name='r' id='rating_form_r' value='"+r+"'>";
            h += "<input type='hidden' name='i' id='rating_form_i' value='"+i+"'>";
            h += "</form>";


            d.innerHTML = h;
         }
      }
   }

   //var d = document.getElementById(div_id);
   //if (d) { d.style.display = 'none'; }
}



// 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));
}

// Halve the size of an image
function shrinkImage( img, frac ) { 
   if (!frac) { frac = 0.5 }
   w=img.width;
   h=img.height;
   img.width  = w * frac;
   img.height = h * frac;
}


function show_overlay(id) {
   var e = document.getElementById(id);
   e.style.display = 'block';
}

function hide_overlay(id) {
   var e = document.getElementById(id);
   e.style.display = 'none';
}

function testalert(str) {
   alert(str);
}

function show_author_tips(mid) { 
   if (!mid) { return; }
   var e = document.getElementById('tips_mid_'+mid);
   if (!e) { return; }

   if (e.style.display != 'block') { 
      e.style.display = 'block';
   } else {
      e.style.display = 'none';
   }

}

function show_user_profile( ev, uid ) { 

   var e;

   // Get/create div to hold profile
   e = document.getElementById("user_profile");
   if (!e) { 
      e = document.createElement("div");
      e.className = "user_profile_hover";
      e.id        = "user_profile";
      document.body.appendChild(e);
   }
   if (!e) { return; }

   // Position at mouse
    var mousePos  = mouseCoords(ev);
    e.style.left = mousePos.x+50+'px';
    e.style.top  = mousePos.y-100+'px';


   // Fill with proper content
   //html = "<p>User profile for "+uid+"</p>";
   //html += "<a href='javascript:close_user_profile()'>Close</a>";

   var xmlHTTP = getXMLHTTP();
   var geturl = 'tip.cgi?action=user&u='+uid;
   if (xmlHTTP) { 
      // Do things synchronously.
      document.body.style.cursor='wait';
      xmlHTTP.open("GET",geturl,false);
      xmlHTTP.send(null);
      document.body.style.cursor='auto';
      data=xmlHTTP.responseText;
      e.innerHTML = data;
   }

   // Display
   e.style.display='block';

}

function close_user_profile() { 
   var e = document.getElementById("user_profile");
   if (e) { 
      e.style.display = 'none';
   }
}

function show_user_tips( uid ) { 

   var e;

   // Get div to hold tip list
   e = document.getElementById("user_profile");
   if (!e) { return; }


   // Fill with proper content
   var xmlHTTP = getXMLHTTP();
   var geturl = 'tip.cgi?action=user_tips&u='+uid;
   if (xmlHTTP) { 
      // Do things synchronously.
      document.body.style.cursor='wait';
      xmlHTTP.open("GET",geturl,false);
      xmlHTTP.send(null);
      document.body.style.cursor='auto';
      data=xmlHTTP.responseText;
      e.innerHTML = data;
   }

   // Display
   e.style.display='block';

}

function toggle_print_menu(pane_id,tip_id) { 
   var e = document.getElementById("printmenu_"+pane_id+"_"+tip_id);
   if (e) { 
      if (e.style.display == "none") {
         e.style.display = 'block';
      } else {
         e.style.display = 'none';
      }
   }
}


