/* =============================================================================
 copyright © 2006 Ivo Truxa, truXoft.com, all right reserved
 
 NO PARTS MAY BE REUSED WITHOUT PRIOR WRITTEN PERMISSION FROM THE AUTHOR
 
============================================================================= */ 

/* -----------------------------------------------------------------------------
  setting global variables (need to keep their values out of function scopes)
------------------------------------------------------------------------------*/
var msie = (navigator.userAgent.indexOf("MSIE")!=-1) ? parseFloat(navigator.appVersion.split("MSIE")[1]) : false;
var lastPopup = 0;
var lastMpObj = null;
var mpWrap, mpDiv, mpUrl, curMP, lastMedia;
var mpX = 392;
var mpY = 292;
var maximized = false;
var mpWrapTop;
var mpWrapLeft;
var mpWrapY;
var mpWrapX = 0;
var winY;
var lblTxt;
var noPopup = false;
var noMPwarning = false;
var srchMnu = document.getElementById('srchMnu');


/* -------- resizeScroll -------------------------------------------------------
  CSS L2 is insufficient for dynamic scroll areas with header and footer
  locked to the top and bottom of the window. JS re-assigning of the sizes
  is necessary
  
  first of all set the window.onresize() handle to execute our function
------------------------------------------------------------------------------*/
window.onresize = resizeScroll;

function resizeScroll()
{
  var win    = document.getElementById('scrollWin');
  var ftr    = document.getElementById('footer');
  var pg     = document.getElementById('page');
  var ed     = document.getElementById('editTraining');
  var img    = document.getElementById('pgImage');
  var mpWrap = document.getElementById('mediaPlayerWrap');
  var mpDiv  = document.getElementById('mediaPlayer'); 
  var tbl    = document.getElementById("scrollTbl");
  
  getWinSz();
  
  if (win && ftr && pg) {
    winY = ftr.offsetTop - (pg.offsetTop + win.offsetTop + 16);
    if (win.style.height) win.style.height =  winY + "px"; 
  }
  if (ed && ftr && pg) {
    winY = ftr.offsetTop - (pg.offsetTop + ed.offsetTop + 16);
    ed.style.height =  (winY-100) + "px"; 
  }
  if (mpWrap && mpDiv && maximized) {
      mpWrap.style.height = winY + 55 + "px";
      mpDiv.style.height  = winY - 25 + "px";
  }
  
  if (!msie && tbl) tbl.style.overflow = "auto";
  if (msie) document.body.scroll = (document.body.offsetHeight < 640) ? "yes" : "auto";
  if (img) hidePgImg(false);
} 


/* -------- hideSelects --------------------------------------------------------
  bypassing MSIE6 bug keeping select boxes visible even under upper laeyrs
------------------------------------------------------------------------------*/
function hideSelects(hide) {
  var myObjs = document.getElementsByTagName("select");
  for (var i=0; i<myObjs.length; i++) {
    var oElem = myObjs[i];
    if (!(oElem.id   && oElem.id.substring(0,4)   == '_po_') &&
        !(oElem.name && oElem.name.substring(0,4) == '_po_') ) 
      oElem.style.visibility = hide;
  }
}

/* -------- hi -----------------------------------------------------------------
  onMouseOver highilighting of table rows 
  (plain CSS :hover does not work with some browsers)
------------------------------------------------------------------------------*/
function hi(show,id)
{
 var rec = document.getElementById("rec"+id).style;
 if (rec)
   if (show==0) {
     rec.color = 'yellow';
     rec.backgroundColor = '#79b';
   } else {
     rec.color = 'black';
     rec.backgroundColor = show;
   }
}


/* -------- slctAll ------------------------------------------------------------
  selecting checkboxes at all checboxes in the catalogue table
------------------------------------------------------------------------------*/
function selAll(prefix){
  var mainChk = eval("document.mainForm." + prefix + "All");
  if (mainChk)
    for (var i=0; i<document.mainForm.length; i++)  
      if (document.mainForm.elements[i].name.search(prefix) == 0)
        document.mainForm.elements[i].checked = mainChk.checked;
}


/* -------- chkSlct ------------------------------------------------------------
  checking if at least one checkbox in the catalogue table was selected 
------------------------------------------------------------------------------*/
function chkSlct(prefix){
  var count = 0;
  for (var i=0; i < document.mainForm.length; i++)  
    if (document.mainForm.elements[i].name.search(prefix) != -1 && document.mainForm.elements[i].name.search(prefix+"All") == -1)
      if (document.mainForm.elements[i].checked) count++;
 return count;
}



/* -------- formUrl ------------------------------------------------------------
  temporary changing the form URL
------------------------------------------------------------------------------*/
var origAction;
function formUrl(url,target){
  origAction = document.mainForm.action;
  if (target) document.mainForm.target = target;
  if (url)    document.mainForm.action = url;
  setTimeout("document.mainForm.target='_self'; document.mainForm.action=origAction;",1000);
}

  
/* -------- pop ----------------------------------------------------------------
  showing / hiding the detail info popup cards 
  includes hiding other elelments, such as select boxes (MSIEg bug), 
  resizing images, and showing/hiding the media player
------------------------------------------------------------------------------*/
function pop(id)
{
  if (noPopup) 
    noPopup = false;
  else {
    srchMnu = document.getElementById('srchMnu');
    if (lastPopup > 0 || lastPopup==id) {
      playMedia(0,null,null);
      document.getElementById("pop"+lastPopup).style.display = "none";
      if (srchMnu) srchMnu.style.visibility = "visible";
      hideSelects("");
    }  
    if (id > 0 && lastPopup!=id) {
      if (msie && msie < 7) {
        if (srchMnu) srchMnu.style.visibility = "hidden";
        hideSelects("hidden");
      }
      document.getElementById("pop"+id).style.display = "block"; 
      lastPopup = id; 
      /* if no description (or originally empty with a max tag), zoom the picture */
      var oDesc = document.getElementById("desc"+id);
      if (oDesc && (oDesc.innerHTML.length <= 2 || oDesc.innerHTML.indexOf("<!-- max -->")!=-1)) {
        var oImg  = document.getElementById("img"+id);
        var oMpl  = document.getElementById("mp"+id);
        oDesc.innerHTML = '';
        if (oMpl && oMpl.onclick) {
          noMPwarning = true;
          oMpl.onclick();
          noMPwarning = false;
        } else if (oImg) {
          oImg.style.display = 'none'; 
          var oThmb = document.getElementById("thmb"+id);
          if (oThmb && oThmb.onclick) oThmb.onclick();
        }
      }
      return false;
    }
    lastPopup = 0;
  }
 return false;
}


/* -------- scale --------------------------------------------------------------
  scaling image to fit either the popup window size or the inner description
  box (at smaller images or when no description available)
------------------------------------------------------------------------------*/
function scale(obj,nr)
{
 if (obj) if (obj.width > 1 && obj.height > 1) {
    var env = document.getElementById('img'+nr);
    var oDesc = document.getElementById("desc"+nr);
    var fullSize = true;

    if (msie) obj.clearAttributes();
    if (oDesc && oDesc.innerHTML.length <= 2) fullSize = false;
    if (fullSize && obj.width < 1.2*obj.height && obj.height > 320) {
      if (obj.width>410)  {obj.removeAttribute("height"); obj.width=410;}
      if (obj.height>550) {obj.removeAttribute("width");  obj.height=550;}
      env.style.width  = '450px';
      env.style.height = '560px';
      env.style.top    = '0px';
      env.style.left   = '0px';
      obj.hspace = 10;
      obj.vspace = 10;
      return true;  // full resize (popup div)
    } else {
      if (obj.width>392)  {if (msie) obj.removeAttribute("height"); obj.width=392;}
      if (obj.height>292) {if (msie) obj.removeAttribute("width");  obj.height=292;}
      env.style.width  = '400px';
      env.style.height = '300px';
      env.style.top    = '159px';
      env.style.left   = '18px';
      obj.hspace = 4;
      obj.vspace = 4;
      var mediaPlayer = document.getElementById('mediaPlayer'+nr);
      if (mediaPlayer) mediaPlayer.style.display = "none";
      return false;  // smaller resize (in description div)
    }
  }
  return false;
}


/* -------- showImg ------------------------------------------------------------
  switching image size thumbnail / description box size / popup window size
  descr. box size used only at smaller images or when no description at all
------------------------------------------------------------------------------*/
function showImg(nr,file) 
{
  var oImg  = document.getElementById('img'+nr);
  var oPic  = document.getElementById('pic'+nr);
  var oDesc = document.getElementById('desc'+nr);
  
  if (oImg) {
    // image not visible - show it
    if (oImg.style.display != 'block') {
      playMedia(0,null,null);
      oImg.style.display = 'block'; 
      if (file.length) oPic.src = file;
      scale(oPic,nr);
    } else {
      // try maximizing the image
      if (oDesc && oDesc.innerHTML.length <= 2) {
        // at records with empty description, fill the descr. field
        // with a flag to allow maximizing in scale() and try it
        oDesc.innerHTML = "<br><!-- max -->";
        // if scaling succeeds (returns true) return immediately (no hiding)
        if (oPic && scale(oPic,nr)) return;
        // maximizing failed (org image too small) reset the description and 
        // continue with hiding the image
        oDesc.innerHTML = "";
      } else if (oDesc && oDesc.innerHTML.indexOf("<!-- max -->")!=-1) {
        // if originally empty description record already maximized, reset
        // the description and continue (hide the image)
        oDesc.innerHTML = "";
      }
      // normal behaviour - hiding image
      oImg.style.display = 'none'; 
    }
  }
}


/* -------- sortID -------------------------------------------------------------
  setting new sorting on the catalogue table
------------------------------------------------------------------------------*/
function sortID(val) {
  document.mainForm.sortTp.value = val;
  document.mainForm.submit();
  return false;
}


/* -------- submitSrch ---------------------------------------------------------
  resetting form variables while submitting the search form
------------------------------------------------------------------------------*/
function submitSrch(reset,expr) {
 document.mainForm.srchModeRst.value = reset;
 document.mainForm.search.value    = expr;
 document.mainForm.submit();
 return false;
}


/* -------- popFeed ------------------------------------------------------------
  displaying feed details on a popup window
------------------------------------------------------------------------------*/
function popFeed(cat,title,text) {
  var ttl    = document.getElementById(title);
  var txt    = document.getElementById(text);
  var popTtl = document.getElementById("feedPopTtl"+cat);
  var popTxt = document.getElementById("feedPopTxt"+cat);
  var pop    = document.getElementById("feedPop"+cat);
  if (ttl && popTtl) popTtl.innerHTML = ttl.innerHTML;
  if (txt && popTxt) popTxt.innerHTML = txt.innerHTML;
  if (pop) pop.style.display = "block";
}


/* -------- popTwitter ---------------------------------------------------------
  displaying twitter feed details on a popup window
------------------------------------------------------------------------------*/
function popTwitter(user,text) {
  var popTtl = document.getElementById("feedPopTtlTw");
  var popTxt = document.getElementById("feedPopTxtTw");
  var pop    = document.getElementById("feedPopTw");
  if (popTtl) popTtl.innerHTML  = user;
  if (popTxt) popTxt.innerHTML  = text;
  if (pop)    pop.style.display = "block";
}


/* -------- blurSelects --------------------------------------------------------
  just bypassing the stupid browser behavior to keep focus on a select element
  even if mouse is no more over them, and changing the options when the user
  uses the mouse wheel to navigate. Could be done very trivially with
  body.onmouseover=focus(), if one could easily avoid triggering when the window
  is in the background. Frustratingly complicate hack for a trivial inconvenience! 
------------------------------------------------------------------------------*/
var selectInFocus = false;
function setFocusOn() {selectInFocus=true;}
function setFocusOff(){selectInFocus=false;}
function blurSelect(){
  if (selectInFocus) {
//    document.getElementById("animHdr").focus();
    selectInFocus = false;
  }
}
function blurSelects(){
  var oSelectList = document.getElementsByTagName("select");
  for (var i=0; i<oSelectList.length; i++) {
     oSelectList[i].onfocus = setFocusOn;
     oSelectList[i].onblur  = setFocusOff; 
  }
}

/* -------- Media Player functions ---------------------------------------------
  Media player box including player switching, resizing, and oher properties
  copyright © 2006 Ivo Truxa, truXoft.com - all rights reerved 
  D O   N O T   R E - U S E    W I T H O U T   P E R M I S S I O N S !
------------------------------------------------------------------------------*/
function resizeMP() {
  mpWrap = document.getElementById('mediaPlayerWrap');
  mpDiv  = document.getElementById('mediaPlayer');  
  var lbl = document.getElementById('playerCtrl');
  if (mpWrap) {
    if (!maximized) {
      pop(0);
      srchMnu.style.visibility = "hidden";
      if (mpWrapX == 0) {
        mpWrapTop  = mpWrap.style.top;
        mpWrapLeft = mpWrap.style.left;
        mpWrapY    = mpWrap.style.height;
        mpWrapX    = mpWrap.style.width;
      }
      mpWrap.style.top = -10 + "px";
      mpWrap.style.left = 0;
      mpWrap.style.width = "100%";
      mpWrap.style.height = winY + 55 + "px";
      mpDiv.style.height  = winY + 25 + "px";
      lblTxt = lbl.innerHTML;
      lbl.innerHTML = "CLOSE";
      playMediaLauncher(0,null,0,null,curMP,mpUrl,mpWrap.style.width,mpDiv.style.height);
      maximized  = true;
    } else {
      playMedia(0,null,null);
      mpWrap.style.top    = mpWrapTop;
      mpWrap.style.left   = mpWrapLeft;
      mpWrap.style.height = mpWrapY;
      mpWrap.style.width  = mpWrapX;
      mpDiv.style.height  = mpY;
      lbl.innerHTML = lblTxt;
      srchMnu.style.visibility = "visible";
      maximized  = false;
    }
  }
 return false;
}


/* -----------------------------------------------------------------------------
  main Media Player functon and its different alternative caller functions
------------------------------------------------------------------------------*/
function changeMP(id) {if (maximized) resizeMP(); else playMedia(0,null,0,null,id,null);}
function playMedia(nr,obj,ask,domain,id,mediaUrl) {return (playMediaLauncher(nr,obj,ask,domain,id,mediaUrl,mpX,mpY))}
function playMediaLauncher(nr,obj,ask,domain,id,mediaUrl,x,y) 
{
 var img;
 var autoStart = "false";
 var mpWrap = document.getElementById('mediaPlayerWrap');
 var mpDiv = document.getElementById('mediaPlayer');
 
 // button label change and confirmation dialogue
 if (obj && !noMPwarning) {
   lastMpObj = obj;
   autoStart = "true";
   if (mpWrap && mpWrap.style.display == "none") {
     // starting video
     // confirmation dialogue only if media domain defined
     if (domain && (mediaUrl!=lastMedia)) {
       if (mediaUrl) lastMedia = mediaUrl;
       if (ask) {
         if (!confirm("This video will be played from an external source (" + domain + ").\nPlease visit the original website for more information. \nYou can choose now to visit the original website instead of viewing the media on this page. \n\nPlease click OK for starting the video here, or CANCEL for visiting the website hosting the media.\n\n(Video may load several seconds or minutes before starting)")){
           obj.target = "_blank";
           return true;
         }  
       } else {
         obj.target = "_self";
         alert("This video will be played from an external source (" + domain + ").\nPlease visit the original website for more information.\n\n\n(Video may load several seconds or minutes before starting)");
       }
     }
     // change the button label only after the dialogue
     obj.innerText = vidLbl2;
   } else {
     id = 0;                  // reset id - for closing the player below
     obj.innerText = vidLbl1; // closing video - no dialogue here
   }  
 }
   
 if (nr==0 && id>0 && ! mediaUrl && mpUrl) {
    mpDiv.innerHTML = "";
    mediaUrl = mpUrl;
 }
 
 if (id && mediaUrl) {
    if (nr) img = document.getElementById('img'+nr);
    mpUrl = mediaUrl;
    if (img) img.style.display = "none";
    if (mpDiv) { 
      curMP = id;
      mpWrap.style.display = 'block';
      switch (id) {
        case 9:  break; // for testing
        case 1:  if (mediaUrl.indexOf('.flv')!=-1 || mediaUrl.indexOf('.FLV')!=-1)     
                      mpDiv.innerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" type="application/x-shockwave-flash" data="FlowPlayer.swf" width="'+x+'" height="'+y+'"><param name="movie" value="FlowPlayer.swf"></param><param name="flashvars" value="videoFile=' + mediaUrl + '&autoPlay=' + autoStart + '"></param><param name="allowScriptAccess" value="sameDomain"></param><param name="quality" value="high"></param><param name="bgcolor" value="#eec"><param name="loop" value="false"><param name="wmode" value="transparent"></param><embed src="FlowPlayer.swf" flashvars="videoFile=' + mediaUrl + '" type="application/x-shockwave-flash" quality="high" bgcolor="#eec" width="'+x+'" height="'+y+'" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash"></embed></object>';
                 else mpDiv.innerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" width="'+x+'" height="'+y+'"><param name="movie" value="' + mediaUrl + '"></param><param name="quality" value="high"></param><param name="autostart" value="' + autoStart + '"></param><param name="flashvars" value="autoPlay=' + autoStart + '"></param><param name="bgcolor" value="#eec"></param><param name="loop" value="false"></param><embed src="' + mediaUrl + '" type="application/x-shockwave-flash" quality="high" bgcolor="#eec" width="'+x+'" height="'+y+'" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash"></embed></object>';
                 break;
        case 2:  mpDiv.innerHTML = '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" width="'+x+'" height="'+y+'" codebase="http://www.apple.com/qtactivex/qtplugin.cab"><param name="autoplay" value="' + autoStart + '"><param name="controller" value="true"><param name="loop" value="false"><param name="pluginspage" value="http://www.apple.com/quicktime/download/indext.html"><param name="target" value="myself"><param name="type" value="video/quicktime"><param name="src" value="' + mediaUrl + '"><param name="scale" value="aspect"><param name="bgcolor" value="#eeeecc"><embed src="' + mediaUrl + '" width="'+x+'" height="'+y+'" autoplay="' + autoStart + '" loop="false" controller="true" border="0" pluginspage="http://www.apple.com/quicktime/download/" target="myself" bgcolor="#eeeecc" scale="aspect"></embed></object>';
                 break;
        case 3:  mpDiv.innerHTML = '<object classid="clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA" width="'+x+'" height="'+(y-30)+'"><param name="src" value="' + mediaUrl + '"><param name="autostart" value="' + autoStart + '"><param name="console" value="video"><param name="controls" value="ImageWindow"><param name="loop" value="false"><embed src="' + mediaUrl + '" width="'+x+'" height="'+(y-30)+'" nojava="true" type="audio/x-pn-realaudio-plugin" controls="ImageWindow" console="video" autostart="' + autoStart + '" loop="false"></embed></object><object classid="clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA" width="'+x+'" height="30"><param name="src" value="'+mediaUrl+'"><param name="console" value="video"><param name="controls" value="ControlPanel"><param name="autostart" value="' + autoStart + '"><param name="loop" value="false"><embed src="'+mediaUrl+'" height="30" width="'+x+'" autostart="' + autoStart + '" loop="false" nojava="true" console="video" controls="ControlPanel"></embed><noembed><a href="http://realmedia.uic.edu/ramgen/itltv/bbtips.6feb02.smi">Play second clip</a></noembed></object>';
                 break;
        default: mpDiv.innerHTML = '<object classid="CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701" width="'+x+'" height="'+y+'" standby="Loading Microsoft Windows Media Player components..." type="application/x-oleobject"><param name="FileName" value="' + mediaUrl + '"><param name="TransparentAtStart" value="false"><param name="AutoStart" value="' + autoStart + '"><param name="AnimationatStart" value="false"><param name="ShowControls" value="true"><param name="loop" value="false"><param name="autoSize" value="true"><param name="displaySize" value="4"><embed src="' + mediaUrl + '" width="'+x+'" height="'+y+'" type="application/x-mplayer2" name="MediaPlayer" pluginspage="http://www.microsoft.com/Windows/MediaPlayer/" transparentAtStart="0" showdisplay="0" showstatusbar="-1" videoborder3d="-1" autostart="' + autoStart + '" animationAtStart="0" showcontrols="1" autosize="1" displaySize="4" designtimesp="5311" loop="false"></embed></object>';
      }  
     obj.innerText = vidLbl2;
    }
 } else  if (mpDiv) {
    // removing player, resetting play button
    if (lastMpObj) lastMpObj.innerText = vidLbl1;
    mpWrap.style.display = "none";
    mpDiv.innerHTML = "";
 } 
 return false;
}


/* -------- show_props ---------------------------------------------------------
  showing JS element/object properties - for debugging only
------------------------------------------------------------------------------*/
function show_props(obj, objName) {   
  document.write("</div><table style='position:absolute; background-color:white; top:10px; left:10px; z-index:1000; display:block' onDblClick='this.style.display=\"none\"'>\n");
  for (var i in obj) document.write(" <tr><td>" + objName + "." + i + "</td><td>" + obj[i] + "</td></tr>\n");
  document.write("</table>\n");
}


/* -------- usrPhoto -----------------------------------------------------------
  swapping user photo with PB info on the User Map
------------------------------------------------------------------------------*/
var usrPhotoTm = 0;
var running = 0;
function usrPhoto(id,on) {
 var nowTm = new Date();
 var photo = document.getElementById('usrPhoto'+id); 
 var info  = document.getElementById('usrInfo' +id);
 if (info && photo) {
   if (on == 0) {
     usrPhotoTm = nowTm.getTime();
     if (running != id){
       running = id;
       photo.style.display = "none";
       if (info.filters) info.filters[0].apply(); 
       info.style.display  = "block";
       if (info.filters) info.filters[0].play(); 
     }
   } else if ((nowTm.getTime() - usrPhotoTm) >= 1200) {
     info.style.display  = "none";
     if (photo.filters) photo.filters[0].apply(); 
     photo.style.display = "block";
     if (photo.filters) photo.filters[0].play();
     running = 0;
   } else {
     setTimeout("usrPhoto("+id+",1)",Math.max(100,Math.min(1300, nowTm.getTime() - usrPhotoTm)));
   } 
 } 
 if (photo) favBar(id,!on);
}


/* -------- fav ---------------------------------------------------------------
  setting of user favorits
------------------------------------------------------------------------------*/
  curFavID  = 0;
  curFavLvl = 0;
  function fav(favID,lvl){
    var orgFav = document.getElementById("orgFav"+favID);
    if (orgFav && (!curFavLvl || (favID != curFavID))) {
      curFavLvl = (orgFav)? orgFav.value : 0;
      curFavID  = favID;
    }
    var fav1 = document.getElementById("fav"+favID+"_1");
    var fav2 = document.getElementById("fav"+favID+"_2");
    var fav3 = document.getElementById("fav"+favID+"_3");
    if (fav1 && fav2 && fav3){
      if (lvl==-1) lvl = curFavLvl;
      fav1.src = "/pic/fav"+((lvl >= 1)?1:0)+".png";
      fav2.src = "/pic/fav"+((lvl >= 2)?1:0)+".png";
      fav3.src = "/pic/fav"+((lvl >= 3)?1:0)+".png";
    }
  }
  
/* -------- favBar ------------------------------------------------------------
  showing a popup div with fav icons
------------------------------------------------------------------------------*/
  function favBar(favID,show){
    var fav = document.getElementById("fav"+favID);
    if (fav) fav.style['visibility'] = (show==1) ? "visible" : "hidden";
  }

/* -------- sendFav -----------------------------------------------------------
  submitting favorite ranking to the server
------------------------------------------------------------------------------*/
  function sendFav(validUsr,favID,lvl){
     var orgFav = document.getElementById("orgFav"+favID);
     if (orgFav){
       orgFav.value = curFavLvl = lvl;
       if (validUsr) {
       } 
       else alert("Sorry! Only registered members can set their favorites!");
     }
   return false;
  }


/* -----------------------------------------------------------------------------
 showing full size image
------------------------------------------------------------------------------*/ 
var imgPopUpOn = false;
var imgs   = null;
var imgNr  = 0;
var imgOld = null;

function fmFullImg(img){
  var fmShowImg = document.getElementById("fmShowImg");
  var fmShowPic = document.getElementById("fmShowPic");
  if (fmShowPic && fmShowPic.src) {
    if (img && imgPopUpOn) img = null;
    var i = (img) ? 0 : 1;
    if (fmShowPic.filters && fmShowPic.filters[i]) fmShowPic.filters[i].apply(); 
    if (img || imgs){
      if ((!img && imgs) || (img && img[0] && (img[0].length > 1))) {
        if (imgs || (img == imgOld)) {
          imgNr  = ++imgNr % imgs.length;
          if (imgNr) {
            fmShowPic.src = imgs[imgNr];
            img = fmShowPic;
          } else {
            fmShowPic.src = "/pic/spc.gif";
            imgs = null;
            img  = null;
          }
        } else {
          imgs  = img;
          debugMsg("imgs.length = " + imgs.length + " imgs = " + imgs);
          imgNr = 0;
          fmShowPic.src = imgs[imgNr];
        }
      }
      else if (img && img.src) fmShowPic.src = img.src;
      else                     fmShowPic.src = img;
    } else                     fmShowPic.src = "/pic/spc.gif";
    fmShowImg.style.display = (img) ? "block" : "none";
    imgPopUpOn = img;
    if (fmShowPic.filters && fmShowPic.filters[i]) fmShowPic.filters[i].play(); 
    imgOld = img;
  }
}


/* -------- expressHint --------------------------------------------------------
  showing a popup info about Express Drag&Drop Submission
------------------------------------------------------------------------------*/
var expHintBlock = false;

function fnExpressHint(show) {   
  // Drag'n'drop currently works with MSIE only
  if (!msie) return;

  var oExpressHint = document.getElementById("expressHint");
  var xMouse = 0; 
  var yMouse = 0; 

  if (oExpressHint)
    switch (show) {
      case  2 : expHintBlock = true; break;
      case  0 : expHintBlock = false; 
                setTimeout("fnExpressHint(-1)",2500); 
                break;
      case -1 : if (!expHintBlock) 
                  oExpressHint.style.display = "none";  
                break;
      case  1 : expHintBlock = true; 
                if (document.all && window.event) {
                   xMouse = window.event.x; yMouse = window.event.y;
                } else if (document.getElementById) {
                   xMouse = e.pageX; yMouse = e.pageY;
                }
                if (xMouse>0 && yMouse>0) {
                  oExpressHint.style.left = (xMouse -  50) + "px";
                  oExpressHint.style.top  = (yMouse - 160) + "px";
                }
                oExpressHint.style.display = "block"; 
                break;
   }
}


/* -------- help popup ---------------------------------------------------------
  help popup
------------------------------------------------------------------------------*/
  var lastHelp = null;
  function showHelp(nr) {
    var help = document.getElementById("help"+nr);
    if (help) {
      if (lastHelp && lastHelp!=help) lastHelp["style"].display = "none";
      help["style"].display = (help["style"].display == "block") ? "none" : "block"; 
      lastHelp = help;
    }
  }
  

/* -------- top header banner animation ----------------------------------------
  animation of the title, subtitle, top image and advertisement block
------------------------------------------------------------------------------*/
var animNr   = 0;
var animBeg  = -700;
var animIncr = 25;
var animPos  = 0;
var animTm   = 20;

function animBanner(pos) {
 var animHdr  = document.getElementById('animHdr');
 var title    = document.getElementById('title');
 var subtitle = document.getElementById('subtitle');
 if (animHdr && title && subtitle && (pos || !pos && !animNr))
   {
    animHdr.style.right = ((animBeg   +   animNr <= animPos) ? animBeg   +   animNr : animPos) + "px";
    title.style.top     = ((animBeg/5 +   animNr <= animPos) ? animBeg/5 +   animNr : animPos) + "px";
    subtitle.style.left = ((animBeg/2 + 2*animNr <= animPos) ? animBeg/2 + 2*animNr : animPos) + "px";
    if ((animBeg + animNr) < animPos) {
      animNr = animNr + animIncr;
      setTimeout("animBanner("+animNr+")",animTm);
    }
    else animNr = 0;
   }
}


/* -----------------------------------------------------------------------------
 printing debug messages into the ad banner
------------------------------------------------------------------------------*/ 
function debugMsg(txt){
  var oDebug = document.getElementById('debug');
  if (oDebug) {
    oDebug.style.display = "block";
    oDebug.innerHTML = txt;
  }
}


/* -----------------------------------------------------------------------------
 password reset
------------------------------------------------------------------------------*/ 
function resetPwd(text1,text2){
 if (!text1 && !text2)
     document.mainForm.sendPass.value=0; 
 else if (document.mainForm.login.value || (document.mainForm.email && document.mainForm.email.value)) {
   if (confirm(text1)) {
     document.mainForm.sendPass.value=1; 
     document.mainForm.submit();
   }
 } else {alert(text2);}
 return false;
}


/* -----------------------------------------------------------------------------
 swapping ad banners
------------------------------------------------------------------------------*/ 
var adSlot = 0;
function swapAds(delay,cnt){
  var oldSlot = document.getElementById("adSlot"+(adSlot+1)); 
  adSlot = ++adSlot % cnt;
  var newSlot = document.getElementById("adSlot"+(adSlot+1));
  if (newSlot) {
    if (oldSlot) oldSlot.style.display = "none"; 
    if (adWidth) {
      document.getElementById("bannerImg").style.display = (adWidth[adSlot]>280) ? "none" : "block";
      document.getElementById("ad").style.width = adWidth[adSlot]+"px";
    }
    newSlot.style.display = "block"; 
  }
  setTimeout("swapAds("+delay+","+cnt+")",delay*1000); 
}

/* -----------------------------------------------------------------------------
 swapping Google Referer with Paypal donation buttons
------------------------------------------------------------------------------*/ 
var refSlot = false;
function swapGoogleRef(delay){
  refSlot = !refSlot;
  var Paypal = document.getElementById("donation"); 
  var Google = document.getElementById("googleRef");
  if (Google) {
    if (refSlot) {
      Paypal.style.display = "none"; 
      Google.style.display = "block"; 
    } else {
      Google.style.display = "none"; 
      Paypal.style.display = "block"; 
    }
  }
  setTimeout("swapGoogleRef("+delay+")",delay*1000); 
}


/* =============================================================================
  Functions from Microsoft's (®) MSDN Reference Manual - mofidied for our needs
  http://msdn.microsoft.com/workshop/author/datatransfer/overview.asp
============================================================================= */
/* -----------------------------------------------------------------------------
  fnNoDef() cancels the default action in ondragenter and ondragover so that 
  the copy cursor is displayed until the selection is dropped.
------------------------------------------------------------------------------*/ 
function fnNoDef(){
  if (window.event) window.event.returnValue = false; 
  var oData = window.event.dataTransfer;
  var oText = oData.getData("Text");
  var oUrl  = oData.getData("URL");
  if (!(oText && oText.length > 5 || oUrl && oUrl.length > 5)) 
     oData.dropEffect  = "none";
}

/* -----------------------------------------------------------------------------
  fnGetInfo() is called by the target object in the ondrop event. It cancels the 
  default action and sets the cursor to the system copy icon. Then it specifies 
  the data format to retrieve. Last, it sets the value property of oTarget 
  object to the information from getData. 
------------------------------------------------------------------------------*/ 
var dropDone = false;
function fnGetInfo() {
  if (!dropDone) {
    event.returnValue = false;                           
    // store page variable for the return
    if (document.mainForm.pageID.value != "txtADD") {
      document.mainForm.origPageID.value   = document.mainForm.pageID.value;
      document.mainForm.origLocation.value = self.location;
    }
    var tmp  = event.dataTransfer.getData("Text");
    if (tmp) {
      if (tmp.length <= 5) tmp = event.dataTransfer.getData("URL");
      if (tmp.length <= 5)
           alert('Sorry, it did not work! \nAn empty or an invalid URL was dragged and dropped here. \n\nYour URL: \"' + escape(tmp) + '\" \n\nPlease try again.');
      else if (tmp.indexOf("apnea.cz")==-1 && tmp.indexOf("apneabase.")==-1 && tmp.indexOf("cyrnea.")==-1 && tmp.indexOf("acfidesien.")==-1 && tmp.indexOf("avecousansbulles.")==-1 && tmp.indexOf("://")>=3 && tmp.indexOf("://")<=6) {
        document.mainForm.pageID.value = "txtADD";
        document.mainForm.url.value = tmp.split('\n')[0]; 
        document.mainForm.submit();
      }
    }
  }
}

function fnGetData() {
  dropDone = true;
  event.returnValue = false;                           
  var tmp  = event.dataTransfer.getData("Text");
  if (tmp.length < 5) tmp = event.dataTransfer.getData("URL");
  if (tmp.length >=5) return tmp;
}


// The  decode64() function was written by Tyler Akins and has been placed 
// in the public domain. -- http://rumkin.com
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
function decode64(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
   input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

   do {
      enc1 = keyStr.indexOf(input.charAt(i++));
      enc2 = keyStr.indexOf(input.charAt(i++));
      enc3 = keyStr.indexOf(input.charAt(i++));
      enc4 = keyStr.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output = output + String.fromCharCode(chr1);

      if (enc3 != 64) output = output + String.fromCharCode(chr2);
      if (enc4 != 64) output = output + String.fromCharCode(chr3);
   } while (i < input.length);

   return output;
 }

 // UTF-8 conversion function from 
 // http://aktuell.de.selfhtml.org/artikel/javascript/utf8b64/utf8.htm
 function decode_utf8(utftext) {
   var plaintext=""; var i=0; var c=c1=c2=0;
   while(i<utftext.length) {
     c = utftext.charCodeAt(i++);
     if (c<128) {
       plaintext += String.fromCharCode(c);
     } else if((c>191) && (c<224)) {
       c2 = utftext.charCodeAt(i++);
       plaintext += String.fromCharCode(((c&31)<<6) | (c2&63));
     } else {
       c2 = utftext.charCodeAt(i); c3 = utftext.charCodeAt(++i);
       plaintext += String.fromCharCode(((c&15)<<12) | ((c2&63)<<6) | (c3&63));
       i++;
     }
   }
   return plaintext;
 }

function fadeIt(obj,val,delay) {
 obj.filters.alpha.opacity = 100;
 setTimeout("document."+obj.name+".filters.alpha.opacity = "+val,1+delay*1000);
}


// Twitter functions
function twitterCallbackTx(twitters) {
  var statusHTML = [];
  for (var i=0; i<twitters.results.length; i++){
    var username = twitters.results[i].from_user;
    var text     = twitters.results[i].text;
    if (text.indexOf("Searched Twitter")==-1) {
      var status = text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
        return '<a href="'+url+'">'+url+'</a>';
      }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
        return reply.charAt(-1);
      });
      statusHTML.push('<li title="'+relative_time(twitters.results[i].created_at)+'" onMouseOver="popTwitter(\''+username+'\',\''+text.replace(/\'/g,"`")+'\')"><a href="http://twitter.com/'+username+'/statuses/'+twitters.results[i].id+'">'+username+'</a>: '+status+'</li>');
    }
  }
  if (statusHTML && statusHTML[0])
    document.getElementById('twitter_update_list').innerHTML = statusHTML.join('');
}

//  onMouseOver="popFeed(\'' $ l.cat $ '\',\'feed' $ Feed.d.recno $ 'Ttl\',\'feed' $ Feed.d.recno $ 'Txt\')"

function relative_time(time_value) {
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  delta = delta + (relative_to.getTimezoneOffset() * 60);

  if (delta < 60) {
    return 'less than a minute ago';
  } else if(delta < 120) {
    return 'about a minute ago';
  } else if(delta < (60*60)) {
    return (parseInt(delta / 60)).toString() + ' minutes ago';
  } else if(delta < (120*60)) {
    return 'about an hour ago';
  } else if(delta < (24*60*60)) {
    return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
  } else if(delta < (48*60*60)) {
    return '1 day ago';
  } else {
    return (parseInt(delta / 86400)).toString() + ' days ago';
  }
}


// HighSLide expnad call - suppressing gallery slideshow first
function hsExpand(obj){
  var pcsSlides = document.getElementById("pcsSlides");
  if (pcsSlides) pcsSlides.style.visibility = "hidden";
  return hs.expand(obj);
}


/* -----------------------------------------------------------------------------
  Zoom Slider Control
------------------------------------------------------------------------------*/
var zLastVal = 0;  // global var
var zObj = null;

function sliderZoom(val){
  var zLbl = document.getElementById('sliderLbl');
  var zVal = document.getElementById('galeryZoom');
  if (!zObj && document.styleSheets) for (var i in document.styleSheets){
    if (document.styleSheets[i].rules){
      if (document.styleSheets[i].rules[0].selectorText.toLowerCase() == "#picasa div.item"){
        zObj = document.styleSheets[i].rules[0];
        break;
      }
    }
  }
  if (zObj && (Math.abs(zLastVal - val) >= 10)){
    zLastVal = val;
    var tmp = (20 + Math.round(val/10));
    if (zVal) zVal.value     = tmp;
    if (zLbl) zLbl.innerHTML = tmp + '%';
    zObj.style.zoom          = tmp + '%'; 
  }
}
