// OFTP page style script.
var cookie, title;

function setActiveStyleSheet( title ) {
	var i, a, main, has_enabled_one = false;
	
	// alert( "changing style to " + title );
	
	for( i=0; ( a = document.getElementsByTagName( "link" )[i] ); i++ ) {
		// alert( "rel=" + a.getAttribute( "rel" ) + "\r\ntitle=" + a.getAttribute( "title" ) );
		if( a.getAttribute( "rel" ).indexOf( "style" ) != -1 && a.getAttribute( "title" ) )
		{
			a.disabled = true;
			if( a.getAttribute( "title" ) == title )
			{
				has_enabled_one = true;
				a.disabled = false;
			}
		}
	}
	
	if( !has_enabled_one && title != getPreferredStyleSheet() )
	{
		setActiveStyleSheet( getPreferredStyleSheet() );
	}
}

function getActiveStyleSheet() {
	var i, a;
	
	for( i=0; ( a = document.getElementsByTagName( "link" )[i] ); i++ ) {
		if( a.getAttribute( "rel" ).indexOf( "style" ) != -1 && a.getAttribute( "title" ) && !a.disabled )
			return a.getAttribute( "title" );
	}
	return null;
}

function getPreferredStyleSheet() {
	var i, a;
	
	for( i=0; ( a = document.getElementsByTagName("link")[i] ); i++ ) {
		if( a.getAttribute( "rel" ).indexOf( "style" ) != -1 && a.getAttribute( "rel" ).indexOf( "alt" ) == -1 && a.getAttribute( "title" ) )	
			return a.getAttribute( "title" );
	}
	return null;
}

function createCookie( name, value, days ) {
	var date, expires;
	
	if( days )
	{
    	date = new Date();
    	date.setTime( date.getTime() + ( days * 24 * 60 * 60 * 1000 ) );
    	expires = ";expires=" + date.toGMTString();
	}
  	else
	{
		expires = "";
	}
	document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie( name ) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	var c, i;
	
	for( i=0;i<ca.length;i++ ) {
    	c = ca[i];
    	while( c.charAt(0) == ' ' )
			c = c.substring(1, c.length);
    	if( c.indexOf( nameEQ ) == 0 )
			return c.substring( nameEQ.length, c.length );
  	}
  	return null;
}

function doOnLoad( e ) {
	var title, cookie;
	
	cookie = readCookie( "style" );
	title = cookie ? cookie : getPreferredStyleSheet();
	setActiveStyleSheet( title );
}

function doOnUnLoad( e ) {
	var title;
	
	title = getActiveStyleSheet();
  	createCookie( "style", title, 365 );
}

function changePageStyle() {
	var style;
	
	if( document.page_style_form && document.page_style_form.style_select )
	{
		style = document.page_style_form.style_select.selectedIndex;
		if( style > -1 )
		{
			style = document.page_style_form.style_select.options[style].text.toLowerCase();
			// alert( "calling set with " + style );
			setActiveStyleSheet( style );
		}
	}
}

window.onload = doOnLoad;
window.onunload = doOnUnLoad;

cookie = readCookie( "style" );
title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet( title );
