// JavaScript Document

/////////////////////////////////////////////
/******* Show and hide the main menu *******/
/////////////////////////////////////////////

var timer = setTimeout("", 0);
var layers_menu = new Array();

// show the layer
function show_menu(layer_name, num)
{ 
 clearTimeout(timer);
 layers_menu[num] = layer_name;
 hide_menu();
 document.getElementById(layer_name).style.visibility = 'visible';
}

function delay()
{
 timer = setTimeout("hide_menu()", 500);
}

// hide the layers
function hide_menu()
{
 for(i in layers_menu)
 {
  document.getElementById(layers_menu[i]).style.visibility = 'hidden';
 }
 hide_select('visible');
}

// hide <select> when a layer is displayed on the <select>
function hide_select(v)
{
 ie = document.all ? 1 : 0;
 elmt = document.getElementsByTagName('select');
 if(ie) // hide <select> for only ie
 {
  for(i = 0; i < elmt.length; i++) elmt[i].style.visibility = v;
 }
}


/////////////////////////////////////////////////////////////////////////
/******* Show and hide layers in different parts of the web site *******/
/////////////////////////////////////////////////////////////////////////

var arr1 = new Array('news', 'domains', 'commissions', 'membership'); // array of all the layers
var arr2 = new Array('domain1', 'domain2', 'domain3', 'domain4', 'domain5', 'domain6', 'domain7', 'domain8', 'domain9', 'domain10'); // array of the domain layers
//arr1 = arr1.concat(arr2); // concat arr1 & arr2 to close the 10 domains layer when we click on one of the recs...
var arr3 = new Array('dc', 'xm', 'mhr', 'dd', 'vl', 'jld', 'rh', 'sp', 'tm', 'nk', 'sf', 'gv', 'pv'); // array of the staff layers

function show_layer(layer_name, cat)
{
 hide_layer(cat);
 document.getElementById(layer_name).style.display = '';
}

function hide_layer(cat)
{
 eval("for(i in arr"+cat+") { document.getElementById(arr"+cat+"[i]).style.display = 'none'; }");
}



//////////////////////////////////////////////
/*********** Open and/or close layers ************/
//////////////////////////////////////////////

function open_close(layer_name)
{
 layer = document.getElementById(layer_name);
 if (layer.style.display == 'none') layer.style.display = '';
 else layer.style.display = 'none';
}



///////////////////////////////////
/******* Add to bookmarks ********/
///////////////////////////////////

function bookmarks() 
{ 
 if (document.all) window.external.AddFavorite(location.href, document.title); 
 else alert('Your browser does not recognize this function, you can also use CTRL + D to add the website to your bookmarks') 
}



//////////////////////////////////////////////
/************ Open a popup window ***********/
//////////////////////////////////////////////

var op = 0;
function popup(page, s, h) // page url, scrollbar, height
{
 if (op == 1) mypop.close(); // close any popup that has been opened
 mypop = window.open(page,"pop", "left=300, top=270, width=442, height="+h+", scrollbars="+s+", resizable=0, status=0, toolbar=0, menubar=0");
 op = 1;
}



///////////////////////////////////////////////
/*********** Check the email format **********/
///////////////////////////////////////////////

function valid_email(mail)
{
 var format = /^[a-zA-Z0-9._-]{2,}@[a-zA-Z0-9._-]{2,}[.][a-zA-Z0-9]{2,4}$/
 return format.exec(mail);
}



//////////////////////////////////////////////////////////////////////////////
/*************** Check if the form has been correctly filled ****************/
/************ The compulsory fields are defined in the form page ************/
//////////////////////////////////////////////////////////////////////////////

function check_empty(form_name, theme)
{
 ok = true;
 email_format = true;
 img_tri = "/img/tri"+theme+"_anim.gif";
 img_pix = "/img/pixelt.gif";
 eval("d = document."+form_name);

 // Check if there is any compulsory fields and if they have been filled
 if(window.fields)
 {
  for(i in fields)	
  {  
   eval("if(!d."+fields[i]+".value) { d.pix_"+fields[i]+".src = img_tri; ok = false; } else d.pix_"+fields[i]+".src=img_pix;");
  }
 }
 
 // Check if there is any email fields and if they are in the right format
 if(window.emails)
 {
  for(j = 0; j < emails.length; j++)	
  {
   var exists = 0; // Variable to check if the email is a compulsory field 
   eval("if(d."+emails[j]+".value && !valid_email(d."+emails[j]+".value)) { d.pix_"+emails[j]+".src = img_tri; ok = false; email_format = false; } else { for(k in fields) { if(emails[j] == fields[k]) exists = 1; } if(exists == 0) d.pix_"+emails[j]+".src=img_pix; }");
  }
 }
 
 if(window.check_general) check_general(); // We call the function check_general if it exists, this function is used to make other tests...
 if(ok == false)
 {
  document.getElementById('layer_alert').style.display = "";
  if(window.emails) // if there is any email fields and email layers to show the error message
  {
   if(email_format == false) document.getElementById('layer_alert_email').style.display = "";
   else if(email_format == true) document.getElementById('layer_alert_email').style.display = "none";
  }
  window.location='#top';
 }
 return ok;
}



///////////////////////////////////////////////////////////////////////
/************************** Preload Images ***************************/
///////////////////////////////////////////////////////////////////////

function preload_img()
{ 
 var doc=document; 
 if(doc.images){ if(!doc.preload) doc.preload=new Array();
 var i,j=doc.preload.length,x=preload_img.arguments; for(i=0; i<x.length; i++)
 if (x[i].indexOf("#")!=0){ doc.preload[j]=new Image; doc.preload[j++].src=x[i];}}
}



///////////////////////////////////////////////////////////////////////
/************** Display a layer while loading the page ***************/
///////////////////////////////////////////////////////////////////////

function wait_load() 
{
 document.getElementById('layer_wait_load').style.display = "none";
}



///////////////////////////////////////////////////////////////////////
/************** Display a layer while downloading a file ***************/
///////////////////////////////////////////////////////////////////////

function wait_preload(val) 
{
 eval("document.getElementById('layer_wait_"+val+"').style.top = document.body.scrollTop + 300;");
 eval("document.getElementById('layer_wait_"+val+"').style.display = '';");
}



///////////////////////////////////////////////////////////////////////
/********** Check the upcoming tasks, concern the Admin Agenda**********/
///////////////////////////////////////////////////////////////////////

function check_task()
{
 var dt_now = new Date();
 dt_now = parseInt(dt_now.getTime() / 1000); // timestamp in sec
 document.cookie = "dt_last_check = " + dt_now + "; path = /"; // rewrite the cookie
 
 if(window.ActiveXObject) var xhr = new ActiveXObject("Microsoft.XMLHTTP"); // Internet Explorer
 else var xhr = new XMLHttpRequest(); // Firefox, Mozilla, ...
    
 xhr.onreadystatechange = function()
 {
  if(xhr.readyState == 4 && xhr.status == 200)
  {
   var res = xhr.responseText;
   if(res.length > 0) popup('/admin/directory/popup_alert.php?sound=1&ids=' + res, 1, 260);
  }
 };
 
 //Open the file, POST method
 xhr.open("POST", "/admin/directory/xhr_check_task.php", true);
 xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
 xhr.send();
 
 setTimeout("check_task()", 3600000);
}



////////////////////////////////////////////////////////////////////////////////////
/***** Display the proceedings of the selected year without reloading the page*****/
////////////////////////////////////////////////////////////////////////////////////

function xhr_proc(val1, val2)
{
 if(window.ActiveXObject) var xhr = new ActiveXObject("Microsoft.XMLHTTP"); // Internet Explorer
 else var xhr = new XMLHttpRequest(); // Firefox, Mozilla, ...
    
 xhr.onreadystatechange = function()
 {
  if(xhr.readyState == 4)
  {
   if(xhr.status == 200) document.getElementById('layer_content').innerHTML = xhr.responseText;
   else document.getElementById('layer_content').innerHTML = "Error code: " + xhr.status;
  }
 };
 
 //Open the file, POST method
 xhr.open("POST", "/admin/directory/xhr_display_proc.php?y=" + val1 + "&s_proc=" + val2, true);
 xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
 xhr.send();
}



////////////////////////////////////////////////////////////////////////////////////
/********************** Equivalent of some PHP functions **************************/
////////////////////////////////////////////////////////////////////////////////////

function addslashes(str)
{
	return str.replace(/([\\"'])/g, "\\$1").replace(/\0/g, "\\0");   
}


function stripslashes(str)
{
	return str.replace('/\0/g', '0').replace('/\(.)/g', '$1');
}


function is_array(mixed_var)
{
	return (mixed_var instanceof Array);
}


function str_replace(f, r, s)
{ 
	var ra = is_array(r), sa = is_array(s), f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;
	while(j = 0, i--)
	{
		while(s[i] = s[i].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f);
	}
	return sa ? s : s[0];
}


function nl2br(str)
{
	return (str + '').replace(/([^>])\n/g, '$1<br>\n');
}


function strip_tags(str, allowed_tags)
{
	var key = '', tag = '', allowed = false;
	var matches = allowed_array = [];
	var allowed_keys = {};
    
	var replacer = function(search, replace, str)
	{
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
	};
    
    // Build allowes tags associative array
    if (allowed_tags)
	{
        allowed_tags  = allowed_tags.replace(/[^a-zA-Z,]+/g, '');;
        allowed_array = allowed_tags.split(',');
	}
    
    // Match tags
    matches = str.match(/(<\/?[^>]+>)/gi);
    
    // Go through all HTML tags 
    for(key in matches)
	{
        if (isNaN(key)) continue; // IE7 Hack
    
        // Save HTML tag
        html = matches[key].toString();
		
		// Is tag not in allowed list? Remove from str!
        allowed = false;
        
        // Go through all allowed tags
        for (k in allowed_array)
		{
            // Init    
            allowed_tag = allowed_array[k];
            i = -1;
            
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
            if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag)   ;}
            
            // Determine
            if (i == 0)
			{
                allowed = true;
                break;
            }
        }
        
        if (!allowed) str = replacer(html, "", str); // Custom replace. No regexing
    }
    
    return str;
}


//////////////////////////////////////////////
/************* Persistent layer *************/
//////////////////////////////////////////////

window.onerror = null;
//var topMargin = 330;
var slideTime = 2200;
var ns = (!document.all && document.getElementById);
var ie = (document.all);

function layerObject(id,left)
{
 this.obj = document.getElementById(id).style;
 this.obj.left = left;
 return this.obj;
}

function layerSetup()
{
 //floatLyr = new layerObject('persistent', pageWidth * .15);
 window.setInterval("main()", 10)
}

function floatObject()
{
 if (ns) findHt = window.innerWidth;
 else if (ie) findHt = document.body.offsetWidth;
}

function main()
{
 if(ns)
 {
  this.currentY = parseInt(document.getElementById('persistent').style.top);
  this.scrollTop = scrollY;
  mainTrigger();
 }
 else if(ie)
 {
  this.currentY = persistent.style.pixelTop;
  this.scrollTop = document.body.scrollTop;
  mainTrigger();
 }
}

function mainTrigger()
{
 var newTargetY = this.scrollTop + this.topMargin;
 if (this.currentY != newTargetY)
 {
  if (newTargetY != this.targetY)
  {
   this.targetY = newTargetY;
   floatStart();
  }
  animator();
 }
}

function floatStart()
{
 var now = new Date();
 this.A = this.targetY - this.currentY;
 this.B = Math.PI / (2 * this.slideTime);
 this.C = now.getTime();
 if (Math.abs(this.A) > this.findHt)
 {
  this.D = this.A > 0 ? this.targetY - this.findHt : this.targetY + this.findHt;
  this.A = this.A > 0 ? this.findHt : -this.findHt;
 }
 else this.D = this.currentY;
}

function animator()
{
 var now = new Date();
 var newY = this.A * Math.sin(this.B * (now.getTime() - this.C)) + this.D;
 newY = Math.round(newY);
 if ((this.A > 0 && newY > this.currentY) || (this.A < 0 && newY < this.currentY))
 {
  if (ie) document.all.persistent.style.pixelTop = newY;
  if (ns) document.getElementById('persistent').style.top = newY + "px";
 }
}

function startscroll()
{
 if(ns)
 {
  pageWidth = innerWidth;
  pageHeight = innerHeight;
 }
 else if(ie)
 {
  pageWidth = document.body.clientWidth;
  pageHeight = document.body.clientHeight;
 }
 layerSetup();
 floatObject();
}