var menu_items = new Array('1','2','3','4','5','6');

function rotate_menu(item_val)
{
	document.getElementById('tab_menu_items').innerHTML = '';

	var low_values = new Array();
	var hi_values = new Array();
	var rotated_menu = new Array();
	
	for(ctr=1;ctr<item_val;ctr++){
		low_values.push(ctr);
	}
	for(ctr=item_val+1;ctr<=7;ctr++){
		hi_values.push(ctr);	
	}	
	
	rotated_menu = hi_values.concat(low_values);	

	for(ctr=0;ctr<rotated_menu.length+1;ctr++){
		if(ctr < 2){		
			menu_items[ctr] = rotated_menu[ctr];				
		}else if(ctr == 2){
			menu_items[ctr] = item_val;			
		}else{
			menu_items[ctr] = rotated_menu[ctr-1];				
		}
		
	}
    
	for(ctr=0;ctr<menu_items.length;ctr++)	
	{
		
		document.getElementById('tab_menu_items').innerHTML += '<li id="menu'+(ctr+1)+'"><a href="javascript:void(0)" onclick="rotate_menu('+menu_items[ctr]+')"><img src="/img/ntv/tab_items_'+(ctr!=2?'in':'')+'active_'+menu_items[ctr]+'.png" /></a></li>';	
	}
	
	//reset all contents
	for (ctr=1;ctr<=menu_items.length;ctr++)
	{	
		if (ctr != item_val) {
			document.getElementById('cat_thumbnails'+ctr).style.display='none';
		}
		else if (ctr == item_val) {
			document.getElementById('cat_thumbnails'+item_val).style.display = '';
		}
	}
	
}

var ntv_targets = new Array(); 

function ntvSend(url,target) 
 { 
  // native XMLHttpRequest object 
  //document.getElementById(target).innerHTML = '<div align="center">&nbsp;</div>'; 
  document.getElementById(target).innerHTML = ''; 
  if (window.XMLHttpRequest) 
   { 
    var idx = ntv_targets.length; 
    ntv_targets[idx] = new XMLHttpRequest(); 
    ntv_targets[idx].onreadystatechange = function() {ntvDone(target, idx);}; 
    ntv_targets[idx].open("GET", url, true); 
    ntv_targets[idx].send(null); 
    // IE/Windows ActiveX version 
   } 
  else if (window.ActiveXObject) 
   { 
    ntv_targets[idx] = new ActiveXObject("Microsoft.XMLHTTP"); 
    if (ntv_targets[idx]) 
     { 
      ntv_targets[idx].onreadystatechange = function() {ntvDone(target,idx);}; 
      ntv_targets[idx].open("GET", url, true); 
      ntv_targets[idx].send(); 
     } 
   } 
 } 

function ntvDone(target, idx) 
 { 
  // only if req is "loaded" 
  if (ntv_targets[idx].readyState == 4) 
   { 
    // only if "OK" 
    if (ntv_targets[idx].status == 200) 
     { 
      results = ntv_targets[idx].responseText; 
      document.getElementById(target).innerHTML = results; 
     }
    else 
     { 
      document.getElementById(target).innerHTML="Error:\n" + 
      ntv_targets[idx].statusText + " (status=" + 
      ntv_targets[idx].status + ", readyState=" + 
      ntv_targets[idx].readyState + ")"; 
     } 
   } 
 }
 


 function create_http_handle(TYPE){

	var http_handle = false;

	if (window.XMLHttpRequest){

		http_handle = new XMLHttpRequest();

		if (http_handle.overrideMimeType){

			if (TYPE == "XML"){

				http_handle.overrideMimeType('text/xml');

			} else {

				http_handle.overrideMimeType('text/html');

			}

		}

	} else if (window.ActiveXObject){

		try {

			http_handle = new ActiveXObject("Msxml2.XMLHTTP");

		} catch (e) {

			try {

				http_handle = new ActiveXObject("Microsoft.XMLHTTP");

			} catch (e) {}

		}

	}

	if (!http_handle){

		alert("We are sorry but you are using an outdated browser.  To view this site you must update your browser.");

		return false;

	} else {

		return http_handle;

	}

}



function sendHTTPrequest(URL, PARAMETERS, ONCHANGE, METHOD, TYPE){

	if (TYPE == "")TYPE = "HTML";

	http = create_http_handle(TYPE);

	

	http.onreadystatechange = function() {

		if(http.readyState == 4 && http.status == 200) {

			//eval(ONCHANGE + '();');
			//alert(http.responseText);
			results = http.responseText; 
      		//alert(results);
      		document.getElementById(ONCHANGE).innerHTML = results; 
		}

	}

	

	//Kill the Cache problem in IE.

	//var now = "upid=" + new Date().getTime();

	//PARAMETERS += (PARAMETERS.indexOf("?")+1) ? "&" : "?";

	//PARAMETERS += now;

	

	if (METHOD == "POST"){

		http.open('POST', URL , true);

		http.setRequestHeader("Content-type", "application/x-www-form-URLencoded");

		http.setRequestHeader("Content-length", PARAMETERS.length);

		http.setRequestHeader("Connection", "close");

		http.send(PARAMETERS);

	} else {

		http.open('GET', URL + PARAMETERS, true);

		http.send(null);

	}

}



/*
   Behaviour v1.1 
*/   

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();


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);
      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;
}

/* That revolting regular expression explained 
/^(\w+)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/
  \---/  \---/\-------------/    \-------/
    |      |         |               |
    |      |         |           The value
    |      |    ~,|,^,$,* or =
    |   Attribute 
   Tag
*/


/*
Rating
*/

var xmlhttp
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	  try {
	  xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")
	 } catch (e) {
	  try {
	    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
	  } catch (E) {
	   xmlhttp=false
	  }
	 }
	@else
	 xmlhttp=false
	@end @*/
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
	 try {
	  xmlhttp = new XMLHttpRequest();
	 } catch (e) {
	  xmlhttp=false
	 }
	}
	function myXMLHttpRequest() {
	  var xmlhttplocal;
	  try {
	    xmlhttplocal= new ActiveXObject("Msxml2.XMLHTTP")
	 } catch (e) {
	  try {
	    xmlhttplocal= new ActiveXObject("Microsoft.XMLHTTP")
	  } catch (E) {
	    xmlhttplocal=false;
	  }
	 }

	if (!xmlhttplocal && typeof XMLHttpRequest!='undefined') {
	 try {
	  var xmlhttplocal = new XMLHttpRequest();
	 } catch (e) {
	  var xmlhttplocal=false;
	  alert('couldn\'t create xmlhttp object');
	 }
	}
	return(xmlhttplocal);
}

function sndReq(vote,id_num,ip_num,units) {
	var theUL = document.getElementById('unit_ul'+id_num); // the UL
	
	// switch UL with a loading div
	theUL.innerHTML = '<div class="loading"></div>';
	
    xmlhttp.open('get', 'rpc.php?j='+vote+'&q='+id_num+'&t='+ip_num+'&c='+units);
    xmlhttp.onreadystatechange = handleResponse;
    xmlhttp.send(null);	
}

function handleResponse() {
  if(xmlhttp.readyState == 4){
		if (xmlhttp.status == 200){
       	
        var response = xmlhttp.responseText;
        var update = new Array();

        if(response.indexOf('|') != -1) {
            update = response.split('|');
            changeText(update[0], update[1]);
        }
		}
    }
}

function changeText( div2show, text ) {
    // Detect Browser
    var IE = (document.all) ? 1 : 0;
    var DOM = 0; 
    if (parseInt(navigator.appVersion) >=5) {DOM=1};

    // Grab the content from the requested "div" and show it in the "container"
    if (DOM) {
        var viewer = document.getElementById(div2show);
        viewer.innerHTML = text;
    }  else if(IE) {
        document.all[div2show].innerHTML = text;
    }
}

/* =============================================================== */
var ratingAction = {
		'a.rater' : function(element){
			element.onclick = function(){

			var parameterString = this.href.replace(/.*\?(.*)/, "$1"); // onclick="sndReq('j=1&q=2&t=127.0.0.1&c=5');
			var parameterTokens = parameterString.split("&"); // onclick="sndReq('j=1,q=2,t=127.0.0.1,c=5');
			var parameterList = new Array();

			for (j = 0; j < parameterTokens.length; j++) {
				var parameterName = parameterTokens[j].replace(/(.*)=.*/, "$1"); // j
				var parameterValue = parameterTokens[j].replace(/.*=(.*)/, "$1"); // 1
				parameterList[parameterName] = parameterValue;
			}
			var theratingID = parameterList['q'];
			var theVote = parameterList['j'];
			var theuserIP = parameterList['t'];
			var theunits = parameterList['c'];
			
			//for testing	alert('sndReq('+theVote+','+theratingID+','+theuserIP+','+theunits+')'); return false;
			sndReq(theVote,theratingID,theuserIP,theunits); return false;		
			}
		}
		
	};
Behaviour.register(ratingAction);

//Textcounter for posting reactions
function textCounter(field,cntfield,maxlimit) {
if (field.value.length > maxlimit) { 
// if too long...trim it!
field.value = field.value.substring(0, maxlimit);
// otherwise, update 'characters left' counter 
}
else {
cntfield.innerHTML = maxlimit - field.value.length;

}
}

function isset(  ) {
    
    var a=arguments, l=a.length, i=0;
    
    if (l===0) {
        throw new Error('Empty isset'); 
    }
    
    while (i!==l) {
        if (typeof(a[i])=='undefined' || a[i]===null) { 
            return false; 
        } else { 
            i++; 
        }
    }
    return true;
}




/*
 * created by: Fred Timajo, OOiP Manila
 * */

var NTV = {
	loopHandler : null,
	selectCategory : function(cat_id)
	{
		var category_name = cat_id=='top'?'top_thumbnails':'cat_thumbnails'+cat_id;
		if(category = document.getElementById(category_name))
		{
			NTV.resetCategory();
			NTV.resetPages(cat_id);
			category.style.display = 'block';
			NTV.gotoPage(cat_id, 1);
			if(cat_button = document.getElementById('cat_button'+cat_id))
			{
				cat_button.className+= ' active';
			}
		}
	},
	resetCategory : function()
	{
		if(cat_thumbnails = document.getElementById('video_container'))
		{
			cat_thumbnails = cat_thumbnails.childNodes;
			for(var i=0; i<cat_thumbnails.length; i++)
			{
				if(cat_thumbnails[i].nodeType == 1)
				{
					if(cat_thumbnails[i].style.display == 'block')
						cat_thumbnails[i].style.display = 'none';
				}
			}
		}
		if(cat_buttons = document.getElementById('main_links'))
		{
			cat_buttons = cat_buttons.childNodes;
			for(var i=0; i<cat_buttons.length; i++)
			{
				if(cat_buttons[i].nodeType == 1)
				{
					if(/active/.test(cat_buttons[i].className))
						cat_buttons[i].className = cat_buttons[i].className.replace(/[ ]*active/,'');
					if(/flash/.test(cat_buttons[i].className))
						cat_buttons[i].className = cat_buttons[i].className.replace(/[ ]*flash/,'');
				}
			}
		}
	},
	gotoPage : function(cat_id, page_id)
	{
		if(page = document.getElementById('page_'+cat_id+'_'+page_id))
		{
			NTV.resetPages(cat_id);
			page.style.display = 'block';
			window['thumbnail_cat'+cat_id+'_page'] = page_id;
			
			if(pagenum = document.getElementById('pagenum_'+cat_id+'_'+page_id))
				pagenum.className = 'active';
			
			if(pagenumtop = document.getElementById('pagenum_'+cat_id+'_'+page_id+'_top'))
				pagenumtop.className = 'active';
		}
	},
	resetPages : function(cat_id)
	{
		var category = (cat_id=='top')?'top_thumbnails':'cat_thumbnails'+cat_id
		if(pages = document.getElementById(category))
		{
			pages = pages.childNodes;
			for(var i=0; i<pages.length; i++)
			{
				if((pages[i].nodeType == 1) && (pages[i].nodeName.toLowerCase() == 'div'))
				{
					if(pages[i].style.display == 'block')
						pages[i].style.display = 'none';
				}
			}
		}
		// page nums
		if(pagenums = document.getElementById('pagenum_'+cat_id))
		{
			pagenums = pagenums.childNodes;
			for(var i=0; i<pagenums.length; i++)
			{
				if(pagenums[i].nodeType == 1)
				{
					var a = pagenums[i].childNodes[0];
					if(a.className == 'active')
						a.className = '';
				}
			}
		}
		// page nums top
		if(pagenumstop = document.getElementById('pagenum_'+cat_id+'_top'))
		{
			pagenumstop = pagenumstop.childNodes;
			for(var i=0; i<pagenumstop.length; i++)
			{
				if(pagenumstop[i].nodeType == 1)
				{
					var a = pagenumstop[i].childNodes[0];
					if(a.className == 'active')
						a.className = '';
				}
			}
		}
	},
	flashIndex : 0,
	loop : function()
	{
		if(buttons = document.getElementById('main_links'))
		{
			buttons = buttons.childNodes;
			var prevIndex = NTV.flashIndex;
			if(prevIndex < 0)
				prevIndex = buttons.length-1;
			if(buttons[prevIndex].className)
				buttons[prevIndex].className = buttons[prevIndex].className.replace(/[ ]*flash/,'');

			NTV.flashIndex++;
			if(NTV.flashIndex>=buttons.length)
				NTV.flashIndex = 0;
			if(buttons[NTV.flashIndex].className)
			{
				if(/active/.test(buttons[NTV.flashIndex].className))
					NTV.flashIndex++;
			}
			if(buttons[NTV.flashIndex].className)
				buttons[NTV.flashIndex].className+= ' flash';
		}
	},
	startLoop : function()
	{
		NTV.stopLoop();
		NTV.loopHandler = setInterval(NTV.loop,150);
	},
	stopLoop : function()
	{
		clearInterval(NTV.loopHandler);
		if(cat_buttons = document.getElementById('main_links'))
		{
			cat_buttons = cat_buttons.childNodes;
			for(var i=0; i<cat_buttons.length; i++)
			{
				if(cat_buttons[i].nodeType == 1)
				{
					if(/flash/.test(cat_buttons[i].className))
						cat_buttons[i].className = cat_buttons[i].className.replace(/[ ]*flash/,'');
				}
			}
		}
	},
	init:function()
	{
		setTimeout(NTV.startLoop,1000);
		// apply hover and out actions
		var buttons = document.getElementById('main_links').childNodes;
		for(var i=0; i<buttons.length; i++)
		{
			if(buttons[i].nodeType == 1)
			{
				buttons[i].onfocus = buttons[i].onmouseover = NTV.stopLoop;
				buttons[i].onblur = buttons[i].onmouseout = NTV.startLoop;
			}
		}
	},
	download:function(file){
		alert("Op al deze filmpjes zit copyright van CliniClowns Nederland (\u00A9 CliniClowns)\nDat betekent dat:\n - deze filmpjes uitsluitend en alleen in huiselijke kring mogen worden bekeken.\n - deze filmpjes mag je niet op internet zetten of anderszins openbaar maken of gebruiken");
		window.open(file);
		return false;
	}
};

