//<![CDATA[
/*!
@file    basic.js
@short   basic javascript functions for composer.rowy.net
@date    28-okt-2008
@author  Jo-Anne Steenbeeke

@version 01.01  28-okt-2008  JSt  Initial release
*/
agt       = navigator.userAgent.toLowerCase();
is_ie     = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
is_opera  = (agt.indexOf("opera") != -1);
is_mac    = (agt.indexOf("mac") != -1);
is_mac_ie = (is_ie && is_mac);
is_win_ie = (is_ie && !is_mac);
is_gecko  = (navigator.product == "Gecko");

var hideHref4moronicIE = new Array();
var screenH = 0;
var screenW = 0;
var MouseX = 0;
var MouseY = 0;
var newWindow = false;

/* The variable http will hold our new XMLHttpRequest object. */
var http = createRequestObject();

function getScreen()
{
    if( ! is_ie ) {        //Non-IE
        screenW = new Number(window.innerWidth);
        screenH = new Number(window.innerHeight);
    } else {                                            // In IE
        if (document.documentElement.clientHeight) {    // IE 6.0+ 'standards compliant mode'
            screenW  = new Number(document.documentElement.clientWidth);
            screenH  = new Number(document.documentElement.clientHeight);
        } else {                                        // other IE
            screenW = new Number(document.body.clientWidth);
            screenH = new Number(document.body.clientHeight);
        }
    }
}

function getMouseXY(e)
{
  getScreen();
  if (is_ie)
  { // grab the x-y pos.s if browser is IE
    MouseX = event.clientX + document.body.scrollLeft
    MouseY = event.clientY + document.body.scrollTop
  } else {  // grab the x-y pos.s if browser is NS
    MouseX = e.pageX
    MouseY = e.pageY
  }
  // catch possible negative values in NS4
  if (MouseX < 0){MouseX = 0}
  if (MouseY < 0){MouseY = 0}
  // show the position values in the form named Show
  // in the text fields named MouseX and MouseY
  // window.status = "mouseX : "+ MouseX + " mouseY : "+ MouseY+" screenH : "+screenH+" screenW : "+screenW;
}

if (!is_ie) document.captureEvents(Event.MOUSEMOVE)
document.onmousemove = getMouseXY;

function NewUrlWindow(url,x,y,p,d)
{
  opts = ( p == '' || p == null ) ? 1 : p;
  doel = ( d == '' || d == null ) ? 'newWindow' : d;
  if (x < 100 || y < 20)
  {
    getScreen();
    var h = parseInt(screenH * 0.8);
    var w = parseInt(screenW * 0.8);
  }
  if (x >= 100 ) w=x;
  if (y >= 20 ) h=y;

  opties = 'width='+w+
    ',height='+h+
    ',left=30,'+
    'top=10';

  opties += (opts &  1) ? ',scrollbars=yes'   : ',scrollbars=no';
  opties += (opts &  2) ? ',resizable=yes'    : ',resizable=no';
  opties += (opts &  4) ? ',menubar=yes'      : ',menubar=no';
  opties += (opts &  8) ? ',personalbar=yes'  : ',personalbar=no';
  opties += (opts & 16) ? ',toolbar=yes'      : ',toolbar=no';
  opties += (opts & 32) ? ',titlebar=yes'     : ',titlebar=no';

  var newWindow = window.open(url,doel,opties);
  newWindow.focus();
  return
}

function bookmarksite ( MetName, url )
{
  if ( url == '' || ! url )
  {
    url = "http://"+window.location.hostname;
  }

	if(document.all)
  {
		window.external.AddFavorite(url, MetName);
	}
  else if (window.sidebar)
  {
		window.sidebar.addPanel(MetName, url, "");
	}
}
/*
   Behaviour v1.1 by Ben Nolan, June 2005. Based largely on the work
   of Simon Willison (see comments by Simon below).
   More information:
   	http://ripcord.co.nz/behaviour/
*/
var Behaviour = {
	list : new Array,

	register : function(sheet){
		Behaviour.list.push(sheet);
	},

	start : function(){
		Behaviour.addLoadEvent(function(){
			Behaviour.apply();
		});
	},

	apply : function(){
		for (h=0;sheet=Behaviour.list[h];h++){
			for (selector in sheet){
				list = document.getElementsBySelector(selector);

				if (!list){
					continue;
				}

				for (i=0;element=list[i];i++){
					sheet[selector](element);
				}
			}
		}
	},

	addLoadEvent : function(func){
		var oldonload = window.onload;

		if (typeof window.onload != 'function') {
			window.onload = func;
		} else {
			window.onload = function() {
				oldonload();
				func();
			}
		}
	}
}

Behaviour.start();

/*
   The following code is Copyright (C) Simon Willison 2004.
*/

function getAllChildren(e) {
  // Returns all children of element. Workaround required for IE5/Windows. Ugh.
  return e.all ? e.all : e.getElementsByTagName('*');
}

document.getElementsBySelector = function(selector) {
  // Attempt to fail gracefully in lesser browsers
  if (!document.getElementsByTagName) {
    return new Array();
  }
  // Split selector in to tokens
  var tokens = selector.split(' ');
  var currentContext = new Array(document);
  for (var i = 0; i < tokens.length; i++) {
    token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');;
    if (token.indexOf('#') > -1) {
      // Token is an ID selector
      var bits = token.split('#');
      var tagName = bits[0];
      var id = bits[1];
      var element = document.getElementById(id);

      // Added by JSt 02-mar-2006 Element must be an object
      if (!element)
      {
         continue;
      }
      // End addition JSt 02-mar-2006

      if (tagName && element.nodeName.toLowerCase() != tagName) {
        // tag with that ID not found, return false
        return new Array();
      }
      // Set currentContext to contain just this element
      currentContext = new Array(element);
      continue; // Skip to next token
    }
    if (token.indexOf('.') > -1) {
      // Token contains a class selector
      var bits = token.split('.');
      var tagName = bits[0];
      var className = bits[1];
      if (!tagName) {
        tagName = '*';
      }
      // Get elements matching tag, filter them for class selector
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      continue; // Skip to next token
    }
    // Code to deal with attribute selectors
    if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
      var tagName = RegExp.$1;
      var attrName = RegExp.$2;
      var attrOperator = RegExp.$3;
      var attrValue = RegExp.$4;
      if (!tagName) {
        tagName = '*';
      }
      // Grab all of the tagName elements within current context
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      var checkFunction; // This function will be used to filter the elements
      switch (attrOperator) {
        case '=': // Equality
          checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
          break;
        case '~': // Match one of space seperated words
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
          break;
        case '|': // Match start with value followed by optional hyphen
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
          break;
        case '^': // Match starts with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
          break;
        case '$': // Match ends with value - fails with "Warning" in Opera 7
          checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
          break;
        case '*': // Match ends with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
          break;
        default :
          // Just test for existence of attribute
          checkFunction = function(e) { return e.getAttribute(attrName); };
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (checkFunction(found[k])) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
      continue; // Skip to next token
    }

    if (!currentContext[0]){
    	return;
    }

    // If we get here, token is JUST an element (not a class or ID selector)
    tagName = token;
    var found = new Array;
    var foundCount = 0;
    for (var h = 0; h < currentContext.length; h++) {
      var elements = currentContext[h].getElementsByTagName(tagName);
      for (var j = 0; j < elements.length; j++) {
        found[foundCount++] = elements[j];
      }
    }
    currentContext = found;
  }
  return currentContext;
}

/* The following function creates an XMLHttpRequest object... */
function createRequestObject()
{
	var request_o; //declare the variable to hold the object.
	if(window.XMLHttpRequest)
	{
		/* Create the object using other browser's method */
		request_o = new XMLHttpRequest();
	}
	else if (window.ActiveXObject)
	{
		/* Create the object using MSIE's method */
		request_o = new ActiveXObject("Microsoft.XMLHTTP");
	}
	else
	{
		alert("Oh crap! Your browser doesn't support AJAX");
		return false;
	}
	return request_o; //return the object
}

// ---== function to handle event of clicking either a pdf-score (: 1) or a sound-byte (: 2) ==--->
function listn2This( url )
{
  var Opts = 'left=50,top=100,resizable=yes';
  var newWindow = window.open('','newWindow', 'height=50px,width=200px,' + Opts);
  newWindow.location.href=url;
  newWindow.focus();
  return;
}
function logMe( elm )
{
//  if ( ! confirm( 'Url : ' + elm.pathname + "\n wordt -nog niet- gelogged. Okay ? " ) ){ return false; }
  opdracht="/pscripts/handleClick.php?actie=log&link="+elm.pathname;
  http.open('get',opdracht);
  http.onreadystatechange = dummyHandleClk;
  http.send(null);

  var classNm = new String( elm.className );

  rExpPop = /pop/g;
  if ( classNm.search(rExpPop) > -1 )
  {
    clEx( elm );
  }

  rExpPop = /mp3/g;
  if ( classNm.search(rExpPop) > -1 )
  {
    clSnd( elm );
  }
  return false;
}
function dummyHandleClk()
{
  if(http.readyState == 4)
  {
//   alert("Done..." );
//   alert("Result "+http.responseText);
  }
}
// ---++--->
function clEx(elm)
{
  NewUrlWindow( elm.pathname, 764, 500, 3 )
}
// ---++--->
function clSnd(elm)
{
  NewUrlWindow( elm.pathname, 250, 50, 3 )
}

// ---==--->
// Define rules for handling above wanted actions per element
var effects = {
 'a.mp3' : function(element) {
       element.onclick = function() {
            clSnd(this);   // Show a small pop-up to open sound, and
            return false;  // don't allow browser to follow location.href
    }
  },
 'a.pop' : function(element) {
       element.onclick = function() {
            clEx(this);    // Show the full Example picture
            return false;  // and don't allow browser to follow location.href
    }
  },
 'a.log' : function(element) {
       element.onclick = function() {
            logMe(this);    // Log this link has been clicked
            return false;  // and don't allow browser to follow location.href
    }
  }
}
Behaviour.register( effects );
// ]]>
