var panelLinks = new Array(3);
var newWindow = null;


function showCalendar(dateField)
{
    newWindow = window.open('/calendar.php?field=' + dateField, 'calendarWindow','toolbar=no,width=260,height=220,directories=no,status=no,scrollbars=auto,resize=no,menubar=no');
    if(newWindow != null && newWindow.opener == null)
    {
        newWindow.opener = window;
    }
}

function selectJump(selectorObj, url)
{
    value = selectorObj.options[selectorObj.selectedIndex].value;
    if (value == 'REST_SUBS')
    {
        document.location.href = "/subject_type_groups/subject_type_group_detail.php?id=6";
    }
    else if (value)
    {
        document.location.href = url + value;
    }
}


var genericWindow;
// opens a generic window
function openGenericWindow(url, width, height)
{
    var leftPos = (screen.availWidth-width) / 2;
    var topPos = (screen.availHeight-height) / 2;

    genericWindow = window.open(url,'genericWindow','toolbar=0,location=no,directories=0,status=1,menubar=0,scrollbars=0,resizable=0,width=' + width + ',height=' + height + ',titlebar=0,top=' + topPos + ',left=' + leftPos);
}

// displays the client contact screen
function emailClientContact(restSubstanceID, subjectID, jurisdictionID, contactListID)
{
    url = "/email_client_contact.php?rid=" + restSubstanceID + "&sid=" + subjectID + "&jid=" + jurisdictionID + "&cid=" + contactListID + "&pageTitle=<? echo($pageTitle); ?>";

    openGenericWindow(url, 500, 550);
}

// used to flick the panel links on the homepage
function setPanel(baseDir, n, cache)
{
	document.getElementById('panelHolder').style.backgroundImage = 'url('+baseDir+'/panel_'+n+'.jpg?cache='+cache+')';
	document.getElementById('panelMain').href = panelLinks[n];
}


//slideshow functions

function inArray(arr, txt)
{
    for (i=0; i<arr.length; i++){
        if (arr[i] == txt){
            return true;
        }
    }
    return false;
}


function loadSlide(i)
{
    document.getElementById('slidePlayer').innerHTML = '';
    if (i >= 0)
    {
        document.getElementById('slideImage').src = slide_dir + '/Slide' + i + '.gif';
        if (inArray(audioSlides, i))
        {
            if (document.getElementById('slideAudio').checked)
            {
                var soundPath = slide_dir +'/'+i+'.mp3';                
                document.getElementById('slidePlayer').innerHTML = '<object data="'+player+'" width="1" height="1" style="vertical-align: bottom;" type="application/x-shockwave-flash"> <param name="type" value="application/x-shockwave-flash" /> <param name="src" value="'+player+'" /> <param name="data" value="'+player+'" /> <param name="codebase" value="'+player+'" /> <param name="FlashVars" value="SoundFileName='+soundPath+'" /> <param name="allowScriptAccess" value="sameDomain" /> <param name="movie" value="'+player+'" /> <param name="loop" value="false" /> <param name="quality" value="high" /> <param name="wmode" value="transparent" /> <param name="PLAY" value="true" /></object>';
            }
        }
        else
        {
            if (document.getElementById('slideAudio').checked)
            {
                setTimeout("slideNext()", 4000);
            }
            
        }
        
    }
    else
    {
        document.getElementById('slideImage').src = "/images/slideshow-login.gif";
    }
    
    var selector = document.getElementById('selectorSlideShow');
    
    // image defaults
    document.getElementById('slidePlay').src = '/images/icons'+slide_skin+'/slide_pause.gif?1'
    document.getElementById('slideNext').src = '/images/icons'+slide_skin+'/slide_next_disabled.gif?1'
    document.getElementById('slidePrev').src = '/images/icons'+slide_skin+'/slide_back_disabled.gif?1'
    
    // images set to status
    if (selector.selectedIndex > 0)
        document.getElementById('slidePrev').src = '/images/icons'+slide_skin+'/slide_back.gif?1'
    if (selector.selectedIndex + 1 < selector.options.length) 
        document.getElementById('slideNext').src = '/images/icons'+slide_skin+'/slide_next.gif?1'
    if (!document.getElementById('slideAudio').checked) 
        document.getElementById('slidePlay').src = '/images/icons'+slide_skin+'/slide_play.gif?1'
}

function slideNext()
{
    slideGo(1);
}
function slideGo(i)
{
    var selector = document.getElementById('selectorSlideShow');
    if (selector.selectedIndex + i < selector.options.length && selector.selectedIndex + i >= 0)
    {
         selector.selectedIndex += i;
         loadSlide(selector.value);
    }
}

function toggleAudio()
{
    document.getElementById('slideAudio').checked = !document.getElementById('slideAudio').checked;
    var selector = document.getElementById('selectorSlideShow');
    loadSlide(selector.options[selector.selectedIndex].value);
    
}

function findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=findObj(args[i]);
    if (val) { nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
  } if (errors) alert('Please correct the following to submit this form:\n'+errors);
  document.returnValue = (errors == '');
}

function tickChildCheckboxes(objName, ticked)
{
            var holderObj = document.getElementById(objName);
            
            for(i=0; i<holderObj.childNodes.length; i++){
                var obj = holderObj.childNodes[i];
                if (obj.tagName == 'INPUT' && obj.type == 'checkbox')
                {
                    obj.checked = ticked;
                }
                
            }
            
}

function webinarButton(dir, title, is_public, domain){
    var preDir = "private/";
    if (is_public){ preDir = "public/"; }
    else {is_public = 0}
    
    if (!domain){domain = ""};
    
    var command = "showWebinar(\""+preDir+dir+"\","+is_public+",\""+domain+"\");";
    
    document.write("<table width='100%' border=0 cellpadding=0 cellspacing=0><tr>");
    document.write("<td width=1%><a href='javascript:"+command+"'><img src=/images/icons/webinar_brown/launcher_l.gif border=0 align=lef/></a></td>");
    document.write("<td width=100% valign=middle onclick='"+command+"' style='cursor: pointer; font-family: Trebuchet MS, Frutiger, Arial, Helvetica; font-weight: normal; font-size: 16px; color: white; background-image: url(/images/icons/webinar_brown/launcher_bkg.gif)'>"+title+"</td>");
    document.write("<td width=1%><a href='javascript:"+command+"'><img src=/images/icons/webinar_brown/launcher_r.gif border=0 /></a></td>");
    document.write("</tr></table>");
}

function showWebinar(dir, is_public, domain){
    if (is_public) {is_public =1;} else {is_public=0;}
    var w = window.open(domain+"/webinar_viewer.php?Dir="+dir+"&__print=1&demo="+is_public+"&msecs="+Math.random(), "webinar", "width=1000, height=700, resizable=yes, scrollbars=yes");
    w.focus();
}

function showAudioPlayer(filePath)
{
	/*
	# <p id="audioplayer_1">Alternative content</p>  
	#         <script type="text/javascript">  
	#         AudioPlayer.embed("audioplayer_1", {soundFile: "http://yoursite.com/path/to/mp3_file.mp3"});  
	#         </script>
	*/
	var flashLink = "http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash&amp;promoid=BIOW";
	var noFlash = "Audio clip: Adobe Flash Player (version 9 or above) is required to play this audio clip. Download the latest version<a href=\""+flashLink+"\" title=\"Download Adobe Flash Player\">here</a>";
	document.write("<p id=\"audioplayer_1\"><span style=\"display:block;padding:5px;border:1px solid #dddddd;background:#f8f8f8\">"+noFlash+"</p>");
	document.write("<script type=\"text/javascript\">AudioPlayer.embed(\"audioplayer_1\", {soundFile: \"http://"+window.location.host+"/"+filePath+"\"});</script>");
}



    /* ====== tool for easilly making a button that toggles a div. (c) 2006 John Cameron ==========
        Usage: <script>showHideButton('myDiv', false);</script>
        
        where there is a div in the page called MyDiv that you want to toggle, change false to true
        to display the div by default.
    */
    
    var FLICKER_ON_TEXT = "More info [+]";
	var FLICKER_OFF_TEXT = "Less info [-]";
	
	function showHideButton(objName, on){
		var text = FLICKER_OFF_TEXT;
		var html = "<div style='float:right'><a class=dateText id=Aflicker_"+objName+" href='javascript:showHideToggle(\""+objName+"\")'>"+text+"</a></div>";
		document.write(html);
		
		if (!on){
			setTimeout("showHideToggle('"+objName+"')", 50);
		}
	}
	function showHideToggle(objName){
		if(obj = document.getElementById(objName)){
			if (obj.style.display != 'none')
			{
				obj.style.display = "none";
				btn = document.getElementById("Aflicker_"+objName);
				btn.innerHTML = FLICKER_ON_TEXT;
			}
			else
			{
				obj.style.display = "block";
				btn = document.getElementById("Aflicker_"+objName);
				btn.innerHTML = FLICKER_OFF_TEXT;
			}
		}else{
			// else obj is not ready, so set timeout to try again after page ahs finished loading
			setTimeout("showHideToggle('"+objName+"')", 400);
		}
		
	}
	
	/* ====== ========================================================================== ==========*/
	


	/* CHECKBOARD PANEL BY JOHN CAMERON */
	
	var cbNumRows = 4;
	var cbNumCols = 4;

	function cbChange(){

		$('cbChanger').hide();

		// turn off all cells so scriptaculous effects work
		for (var row=1; row <= cbNumRows; row++){
			for (var col=1; col <= cbNumCols; col++){
				var id = "cbRow"+row+"Col"+col;
				$(id).hide()
			}
		}

		$('cbPanel2').show();

		// turn on cells with random duration
		for (var row=1; row <= cbNumRows; row++){
			for (var col=1; col <= cbNumCols; col++){
				var myDuration = (Math.random() * 1) + 1;
				var id = "cbRow"+row+"Col"+col;
				Effect.Appear(id, { duration: myDuration });
			}
		}



	}

	function cbBack(){
		$('cbChanger').show();
		Effect.Fade('cbPanel2');
	}


	function initCheckboard(){
		
		if ($('cbPopup_login_link')) {Effect.Appear('cbPopup_login_link');}
		new FancyZoom('cbPopup_login_link');
		
		
		if (document.getElementById('advert')){
			var tags = "<tags>";
			tags += "<a href='search/summary.php?SUBJECT_TYPE_ID=5&Insert=RoHS' style='40'>RoHS</a>";
			tags += "<a href='search/summary.php?SUBJECT_TYPE_ID=5&Insert=RoHS' style='40'>REACH</a>";
			tags += "<a href='search/summary.php?SUBJECT_TYPE_ID=8&Insert=WEEE' style='60'>WEEE</a>";
			tags += "<a href='search/summary.php?SUBJECT_TYPE_ID=7&Insert=DfE' style='20'>EuP</a>";
			tags += "<a href='search/summary.php?SUBJECT_TYPE_ID=7&Insert=DfE' style='7'>Design for Environment</a>";
			tags += "<a href='search/summary.php?SUBJECT_TYPE_ID=10&Insert=EE' style='12'>Energy Efficiency</a>";
			tags += "<a href='search/summary.php?SUBJECT_TYPE_ID=3&Insert=Batteries' style='12'>Batteries</a>";
			tags += "<a href='search/summary.php?SUBJECT_TYPE_ID=4&Insert=Packaging' style='12'>Packaging</a>";
			// tags += "<a href='search/summary.php?JURISDICTION_ID=185' style='12'>India</a>";
			tags += "<a href='regions/region_detail.php?id=2' style='12'>Europe</a>";
			tags += "<a href='regions/region_detail.php?id=1' style='12'>Asia/Pacific</a>";
			tags += "<a href='regions/region_detail.php?id=4' style='12'>USA</a>";
			tags += "<a href='search/summary.php?SUBJECT_TYPE_ID=69' style='17'>Cadmium</a>";

			tags += "</tags>";
			tags = tags.replace(/&/g,"%26");

			var so = new SWFObject("ssi/js/tagcloud.swf", "tagcloud", "260", "230", "7", "#fafafa");
			// uncomment next line to enable transparency
			so.addParam("wmode", "transparent");
			so.addVariable("tcolor", "0x3356ba");
			so.addVariable("mode", "tags");
			so.addVariable("distr", "true");
			so.addVariable("tspeed", "100");
			so.addVariable("tagcloud", tags);
			so.write("flashcontent");
            
			new FancyZoom('cbPopup_subscribe_link');
			new FancyZoom('cbPopup_video_link');
			new FancyZoom('cbPopup_video_link2');
			new FancyZoom('cbPopup_industry_link');
			new FancyZoom('cbPopup_news_link');
			new FancyZoom('cbPopup_quotes_link');
			new FancyZoom('cbPopup_experts_link');
			new FancyZoom('cbPopup_experts_link');
			new FancyZoom('cbPopup_brochures_link');
			new FancyZoom('cbPopup_coverage_link');
			new FancyZoom('cbPopup_lifecycle_link');

            if (document.getElementById('cbPopup_REMOVEME_link'))
{
                   new FancyZoom('cbPopup_REMOVEME_link');
            }
			
			//* --- ANDREW FRONTPAGE HACK --- *
			new FancyZoom('cbPopup_REMOVEME_link');
		}
	}
	
	function focusLogin()
	{
		var objs = $$('#zoom_content #Login_Username');
		if(objs.length > 0 )
			objs[0].focus();
	}
	
	function preLoadImage(url){
		var pic1 = new Image(1,1); 
		pic1.src=url;
	}


	function getPositionCenter() 
	{
		var self = this;
		// First, determine how much the visitor has scrolled
		var scrolledX, scrolledY;
		if( self.pageYOffset )
		{
			scrolledX = self.pageXOffset;
			scrolledY = self.pageYOffset;
		}
		else if( document.documentElement && document.documentElement.scrollTop )
		{
			scrolledX = document.documentElement.scrollLeft;
			scrolledY = document.documentElement.scrollTop;
		}
		else if(document.body)
		{
			scrolledX = document.body.scrollLeft;
			scrolledY = document.body.scrollTop;
		}

		// Next, determine the coordinates of the center of browser's window
		var centerX, centerY;
		if( self.innerHeight )
		{
			centerX = self.innerWidth;
			centerY = self.innerHeight;
		}
		else if( document.documentElement && document.documentElement.clientHeight )
		{
			centerX = document.documentElement.clientWidth;
			centerY = document.documentElement.clientHeight;
		}
		else if( document.body )
		{
			centerX = document.body.clientWidth;
			centerY = document.body.clientHeight;
		}

		var leftOffset = scrolledX + (centerX) / 2;
		var topOffset = scrolledY + (centerY) / 2;
		return {'left':leftOffset, 'top':topOffset};
	}
