delayID = 0;
delayID2 = 0;
worktoset = 0; /* flag: worktosetvalue tells which work to set */
dynadir = "_dyna/";
seek_init_waiting = 0;

function CheckFind()
{ var txt = document.MainForm.seeker.value;
  if(txt == "")
    return false;
  else
  { if(document.MainForm.composer.selectedIndex == 0)
      location.href = "index.php?f=find&a="+txt;
    else
      location.href = "index.php?f=find&a="+txt+"&c="+cleanstring(document.MainForm.composer.options[document.MainForm.composer.selectedIndex].text);
  }
}

function bookmarkpage(obj)
{ url = document.URL;
  parts = url.split('#');
  if(parts.length > 1) 
  { if (parts[1] != '')
      url="http://www.opusfinder.com/index.php?"+parts[1];
    else
      url = parts[0];
  }
  title = document.title;
  if (window.sidebar) { // Mozilla Firefox Bookmark
	window.sidebar.addPanel(title, url,"");
  } else if( window.external ) { // IE Favorite
	window.external.AddFavorite( url, title); 
  } else if (window.opera && document.createElement) {
        obj.setAttribute('rel','sidebar');
        obj.setAttribute('href',url);
        obj.setAttribute('title',title);
	return true; }
  else alert('Problem');
}

function ShowComposer(origin)
{ if(document.MainForm.composer.selectedIndex == 0) return;
  if(origin == 0) // clicked view button
  { document.MainForm.worknames.selectedIndex = 0;
    WC(document.MainForm.worknames);
  }
  clearTimeout(delayID2);
  var composer = document.MainForm.composer.options[document.MainForm.composer.selectedIndex].text;
  var composerx = cleanstring(composer);
  delayurl = "/comp.php?c="+composerx;
  delayID2 = setTimeout("LoadPage(delayurl,dynamo8)",200);
  location.replace("#c="+composerx+"&f=info");
  document.title = composer+' info - OpusFinder'

}

function ShowWork()
{ if(document.MainForm.composer.selectedIndex == 0) return; 
  if(document.MainForm.worknames.selectedIndex == 0) { ShowComposer(1); return; }
  clearTimeout(delayID2);
  worka = getWorkID();
  var composer = document.MainForm.composer.options[document.MainForm.composer.selectedIndex].text;
  var composerx = cleanstring(composer);
  delayurl = "/work.php?c="+composerx+"&w="+worka;
  delayID2 = setTimeout("LoadPage(delayurl,dynamo8)",200);
  location.replace("#c="+composer+"&w="+worka);
  document.title = composer+': '+document.MainForm.worknames.options[document.MainForm.worknames.selectedIndex].text+' - OpusFinder'
}

function ShowPerflinks(num)
{ if((document.MainForm.composer.selectedIndex == 0) && (num < 3))
    return;
  if((document.MainForm.worka.selectedIndex == 0) && (num==2))
    return;
  if((document.MainForm.performer.selectedIndex == 0) && (num==3))
    return;
  if((document.MainForm.category.selectedIndex == 0) && (num==4))
    return;
  if((document.MainForm.genre.selectedIndex == 0) && (num==5))
    return;
  var composer = document.MainForm.composer.options[document.MainForm.composer.selectedIndex].text;
  var work = document.MainForm.worka.options[document.MainForm.worka.selectedIndex].text;
  var performer = document.MainForm.performer.options[document.MainForm.performer.selectedIndex].text;
  var category = document.MainForm.category.options[document.MainForm.category.selectedIndex].text;
  var genre = document.MainForm.genre.options[document.MainForm.genre.selectedIndex].text;
  if(num==1)
    window.open('/_php/showperflinks.php?composer='+escape(composer),"", "resizable,scrollbars,location,menubar,status,toolbar");
  else if(num==2)
    window.open('/_php/showperflinks.php?composer='+escape(composer)+'&work='+escape(work),"", "resizable,scrollbars,location,menubar,status,toolbar");
  else if(num==3)
    window.open('/_php/showperflinks.php?performer='+escape(performer),"", "resizable,scrollbars,location,menubar,status,toolbar");
  else if(num==4)
    window.open('/_php/showperflinks.php?category='+escape(category),"", "resizable,scrollbars,location,menubar,status,toolbar");
  else if(num==5)
    window.open('/_php/showperflinks.php?genre='+escape(genre),"", "resizable,scrollbars,location,menubar,status,toolbar");
}

function ShowWorklist(field)
{ var composer = cleanstring(document.MainForm.composer.options[document.MainForm.composer.selectedIndex].text);
  var wlurl = "/index.php#f=worklist&c="+composer;
  clearTimeout(delayID2);
  delayurl = "/worklist.php?c="+composer;
//  LoadPage(delayurl,dynamo8);
  location.href = "index.php?f=worklist&c="+composer;
}

function ShowWorklist_dyna(field)
{ var composer = cleanstring(document.MainForm.composer.options[document.MainForm.composer.selectedIndex].text);
  var wlurl = "/index.php#f=worklist&c="+composer;
  clearTimeout(delayID2);
  delayurl = "/worklist.php?c="+composer;
  LoadPage(delayurl,dynamo8);
  location.replace("#f=worklist&c="+composer);
}

function getWorkID()
{ if(document.MainForm.composer.selectedIndex==0) return "";
  var work = "";
  if((document.MainForm.worka) && (document.MainForm.worka.length > 0) &&(document.MainForm.worka.options[document.MainForm.worka.selectedIndex].text != ""))
    work = document.MainForm.worka.options[document.MainForm.worka.selectedIndex].text;
  else if (document.MainForm.worknames.selectedIndex != 0) /* only workname */
  { work = document.MainForm.worknames.options[document.MainForm.worknames.selectedIndex].getAttribute("p").toLowerCase(); /* IE creates here uppercase */
    work = work.replace("#","`");
  }
  return work;
}

function seek()
{ var argm = encodeURIComponent(document.MainForm.seeker.value);
  var base = document.MainForm.composer;
  var composer = cleanstring(base.options[base.selectedIndex].text);
  if(base.selectedIndex == 0)
    composer = '';
  if(document.MainForm.newwin.checked == true)
    window.open('/index.php?func=find&argm='+argm+'&composer='+composer ,'', 'resizable,scrollbars=yes,location=yes,menubar=yes,status=yes,titlebar=yes,toolbar=yes');
  else
  { delayurl = 'seek.php?argm='+argm+'&composer='+composer;
//    delayID2 = setTimeout("LoadPage(delayurl,dynamo8)",200);
    location.href = "index.php?c="+composer+"&f=find&a="+argm;
  }
  seek_init_waiting = 1;
}

function ComposerChange()
{ var base = document.MainForm.composer;
  var composer = base.options[base.selectedIndex].text;
  dyna_insert(htmlize(composer));
  ShowComposer(2);
}

/* cleanstring is derived from php */
function cleanstring(source)
{ source = StripAccents(source, "");
  source = source.toLowerCase();
  source = source.replace(/[+|&]/g,"and"); 
  source = source.replace(/[!\?()/,\".':]/g,"");
  return source.replace(/ /g, "_");
}


function WC(el)
{ var n,p,q,r;
  if(el.name != "worknames")
  { n = el.options[el.selectedIndex].getAttribute("n");
    if(!n) return; /* empty line */
    document.MainForm.worknames.options[n].selected=1;
  }
  base = document.MainForm.worknames;
// alert("WWW "+base.innerHTML);
  for(cat=0; cat<catcount; cat++)
  { var atchar = chr(112+cat); /* attribute character */
    attr = base.options[base.selectedIndex].getAttribute(atchar);
    target = eval("document.MainForm.work"+chr(97+cat));
// alert("MMM "+attr+' '+atchar);
    if(isNaN(attr))
{     target.options[catnums[cat]].selected=1; /* empty line */
}
    else
    { target.options[attr].selected=1;
    }
  }
  ShowWork();
}

// ATTN: use urls starting with / for the url !!!
function LoadPage(url, callback)
{ var request =  new XMLHttpRequest();
  request.open("GET", url, true); /* delaypage must be a global var; changed from POST to GET */
  request.onreadystatechange = function() 
  { if (request.readyState == 4 && request.status == 404) /* done = 4, ok = 200 */
	alert("ERROR "+request.status+" "+request.responseText) 
    if (request.readyState == 4 && request.status == 200) /* done = 4, ok = 200 */
    { if (request.responseText) 
        callback(request.responseText);
    };
  }
  request.send(null);
}

/* inserts the composer (like Bach) specific file into the iframe */
function dyna_insert(dfile) 
{ if(document.MainForm.worka)
    document.MainForm.worka.length = 0;
  var target=document.getElementById("work1");
  target.innerHTML = "";
  target=document.getElementById("work2");
  target.innerHTML = "";
  target=document.getElementById("work3");
  target.innerHTML = "";
  target=document.getElementById("work4");
  target.innerHTML = "";
  target=document.getElementById("work5");
  target.innerHTML = "";
  target=document.getElementById("work6");
  target.innerHTML = "";
  target=document.getElementById("work7");
  target.innerHTML = "";
  target=document.getElementById("cname1");
  target.innerHTML = "";
  target=document.getElementById("cname2");
  target.innerHTML = "";
  target=document.getElementById("cname3");
  target.innerHTML = "";
  target=document.getElementById("cname4");
  target.innerHTML = "";
  target=document.getElementById("cname5");
  target.innerHTML = "";
  target=document.getElementById("cname6");
  target.innerHTML = "";
  target=document.getElementById("cname7");
  target.innerHTML = "";
  target=document.getElementById("workns");
  target.innerHTML = "";
  target=document.getElementById("workviewbutton");
  target.style.display = "none";
  clearTimeout(delayID);
  if(dfile != 'select_a_composer')
  { delaypage = "/"+dynadir+htmlize(dfile)+'.htm';
    delayID = setTimeout("LoadPage(delaypage,dynamo7)",200);
  }
//   tank.location.href = dynadir+htmlize(dfile)+".htm"; /* must be .htm for Mozilla */
  return false;
}

function dynamo6(ppp)
{ alert("dsa "+ppp);
}

function dynamo7(dytext)  /* Opusfinder inserted file */
{ // alert("sasa");
  matches = dytext.match(/<body onload=\'parent.dynamo6\(\"([^\"]*)\"\)\'>/);
//  if(matches == null) alert("NOT Found");
  catblocks = matches[1];
  catnums = new Array();
  catnames = new Array();
  catcount = 0;
  if(catblocks != "")
  { target=document.getElementById("workt"); /handle typer field */
    if(target)
      target.innerHTML = "<input id=typer size=5 onKeyUp=TyperChange()>";
    var catsegs = catblocks.split(";");
    catcount = catsegs.length;
    for(var cat=0; cat< catcount; cat++) 
    { var tmp = catsegs[cat].split(",");
      catnames[cat] = tmp[0];
      if(tmp[1])
        catnums[cat] = tmp[1];
      tmp = "work"+(cat+1);
      if(!document.getElementById(tmp)) /* if html doesn't support more fields */
      { break;
      }
      var target=document.getElementById(tmp);
      var pos = dytext.search("<div id=content"+chr(97+cat)+">");
      dytext = dytext.substr(pos+17);
      var pos = dytext.search("</div>");
      datax = dytext.substr(0,pos);

      var expres = /</g;
      datax = datax.replace(expres,'</option><option n=');
      if(catnums[cat])
        datax += '<option></option>';
      target.innerHTML = '<select name=work'+chr(97+cat)+' onChange=WC(this)><option n=0>'+catnames[cat]+datax+'</select>';
      tmp = "cname"+(cat+1);
      var target=document.getElementById(tmp);
      target.innerHTML = "<b>"+catnames[cat]+"</b>";
    }
  } 
/* now the names */
  target=document.getElementById("workns");
//  var src = frames.tank.document.getElementById("content2");
//  var datax = src.innerHTML;  /* Mozilla supports innerText not */
  var pos = dytext.search("<div id=content2>");
  dytext = dytext.substr(pos+17);
  var pos = dytext.search("</div>");
  datax = dytext.substr(0,pos);

  datax = datax.replace(/\{/g,'<'); /* the "{" at the beginning was introduced for Mozilla as it produced closing tags for the non-numeric tags: so "<ttr>concerto" resulted in "<option p=ttr>concerto</ttr>" what resulted in extra empty lines in the select box */
  datax = datax.replace('/^<[^>]+>/','');
  datax = datax.replace('/<[^>]+>$/','');
  expres = /</g;
  datax = datax.replace(expres,'</option><option p=');
  expres = /&gt;/g; /* innerHTML garbles the <> if content is numeric */
  datax = datax.replace(expres,'>');
  expres = /&lt;/g;
  datax = datax.replace(expres,'</option><option p='); 
  expres = /flu=l/g; /* lost work */
  datax = datax.replace(expres,'style="background-color:<?php echo $FLU_LOST_COLOR; ?>"');
  expres = /flu=u/g; /* unfinished */
  datax = datax.replace(expres,'style="background-color:<?php echo $FLU_UNFINISHED_COLOR; ?>"');
  expres = /flu=f/g; /* fragment */
  datax = datax.replace(expres,'style="background-color:<?php echo $FLU_FRAGMENT_COLOR; ?>"');
  expres = /flu=s/g; /* sketch */
  datax = datax.replace(expres,'style="background-color:<?php echo $FLU_SKETCH_COLOR; ?>"');

//  alert('XXX'+datax);

  zeroes = '';
  if(catcount > 0)
    zeroes = 'p=0 ';
  for(cat=1; cat<catcount; cat++) 
  { zeroes += chr(112+cat)+"=0 ";
    var expres1 = /(=[^\|]*)\|/g
    var datax = datax.replace(expres1,"$1 "+chr(112+cat)+"=");
  }
//  alert("MAMAM "+datax) 
  target.innerHTML = "<select name=worknames onChange=WC(this)><option "+zeroes+">select a workname"+datax+"</select>";
  /* now look if work must be set */
  if(worktoset == '1')
  { setWorkID(worktosetvalue);
    worktoset=0;
  }
}

function dynamo8(dytext)  /* called from the dyna_inserted file */
{ var target=document.getElementById("maintext");
if(target==null) alert("TOTO");
//  var src = frames.park.document.getElementById("content").innerHTML;
//  var expres1 = /</g;
//  xx = src.replace(expres1,'&lt;');
  target.innerHTML = dytext;
}

function setComposer(value) 
{ var length = document.MainForm.composer.length;
  var base = document.MainForm.composer;
  var h = length, l = -1, m;
  var xvalue = value.replace("_", " "); /* necessary for Wolf-ferrari vs Wolf ascii(_)=95; ascii( )=32 */
  while(h - l > 1) 
  { mtext = cleanstring(base.options[m = h + l >> 1].text);
    if(mtext.replace("_", " ") < xvalue) l = m;
      else h = m;
  }
  if(cleanstring(base.options[h].text) == value) 
    idx = h;
  else if(cleanstring(base.options[l].text) == value) 
    idx = l;
  else alert("COMPOSER NOT FOUND "+h+" "+l+" - "+cleanstring(base.options[l].text)+" "+cleanstring(base.options[h].text)+" = "+value );
  base.selectedIndex = idx;
  ComposerChange();
}

function SetSelect(field, value) 
{ base = eval('document.MainForm.'+field);
  regexp = /^ +| +$/g
  var value = value.replace(regexp,'',value); /* simulate the trim() function */
  regexp = / +/g
  value = value.replace(regexp,' ',value); /* replace multiple spaces by one to repair innerHTML bug */
  value = StripAccents(value);
  for(i=0; i<base.length; i++)
  { if(base.options[i].text == value)
    { base.selectedIndex = i;
      break;
    }
  }
}

function setWorkID(value) 
{ value = value.replace(/^ +/, '');
  if(((value.charCodeAt(0) >=48) && (value.charCodeAt(0) <=57)) || ((value.charCodeAt(0) >=65) && (value.charCodeAt(0) <=90)))
  { SetSelect('worka',value); /* adapted for Tarrega Gp:27 */
    WC(document.MainForm.worka);
  }
  else
  { trunk = eval('document.MainForm.worknames');
    value = value.replace("`","#");
    for(i=1; i<trunk.length; i++)
    { if(trunk.options[i].getAttribute("p").toLowerCase() == value.toLowerCase())
      { trunk.selectedIndex = i;
        break;
      }
    }
    WC(document.MainForm.worknames);
  }
}

function AddToList()
{ if(document.MainForm.composer.selectedIndex == 0) return;
  var composer = document.MainForm.composer.options[document.MainForm.composer.selectedIndex].text;
  if(document.MainForm.worknames.selectedIndex == 0)
  { var itemtype = "Composer";
    var workname = "";
  }
  else
  { var itemtype = "Work";
    var workname = document.MainForm.worknames.options[document.MainForm.worknames.selectedIndex].text;
    var work = getWorkID();
  }
  var url = window.location.href.replace('#','?');
  
  var list = document.getElementById("MemList");
  list.innerHTML += '<b>'+itemtype+'</b><br><a href='+url+'>'+composer+' '+workname+'</a>';
 
}

function getUrlSuffix(url)
{ if(url.indexOf("#") > 0)
    var tmp = url.split('#');
  else return "";
  return tmp[1];
}

function init()
{ // Provide the XMLHttpRequest class for IE 5.x-6.x:
  if( typeof XMLHttpRequest == "undefined" ) 
    XMLHttpRequest = function() {
  try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) {}
  try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) {}
  try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {}
  try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
  throw new Error( "This browser does not support XMLHttpRequest." )
  };
  var url = unescape(window.location.href);

  var suffix = getUrlSuffix(url)
  if(window.catcount)
  { catnums = new Array();
    for(var cat=0; cat<catcount; cat++)
    { var temp = eval("document.MainForm.work"+chr(97+cat));
      catnums[cat] = temp.length - 1;
    }
  }
  if(suffix.length > 0)
  { var func = '';
    var argm = '';
    var sufs = suffix.split('&');
    for(i=0; i<sufs.length; i++)
    { if(sufs[i].substring(0,2) == "c=")
        composer = sufs[i].substring(2);
      if(sufs[i].substring(0,2) == "w=")
      { worktosetvalue = sufs[i].substring(2);
        worktoset = '1';
      }
      if(sufs[i].substring(0,2) == "a=")
        argm = sufs[i].substring(2);
      if(sufs[i].substring(0,2) == "f=")
        func = sufs[i].substring(2);
    }
    if(func == 'worklist')
    { SetSelect('composer',composer);
      clearTimeout(delayID2);
      delayurl = "/worklist.php?c="+composer;
      LoadPage(delayurl,dynamo8);
    }
    else if(func == 'info')
    { SetSelect('composer',composer);
      clearTimeout(delayID2);
      delayurl = "/comp.php?c="+composer;
      LoadPage(delayurl,dynamo8);
    }
    else if(func == 'find')
    { if(!window.composer)
        composer = '';
      else
	SetSelect('composer',composer);
      delayurl = 'seek.php?argm='+argm+'&composer='+composer;
      LoadPage(delayurl,dynamo8);
      seek_init_waiting = 1;
    }
    else if(window.composer && (composer.length > 0) && (worktoset == '1'))
      setComposer(composer);
  }
}

