/*** STMcommon.js ***/
/*
 * Common functions used on Stellafane.org
 * Use: <head> <script src="../common/STMcommon.js"></script> </head>
 * Use: <body> <script>write_footer_here("../");</script>
  *     // The string parameter is used to adjust for relative poisition from page root
 * Use: <body> <script>email_webmaster( "Subject for email", "CSS class" )</script>text or img goes here</a> </body>
 * Created by Ken Slater on 2006-Feb-22
 */

/* --- Global Pavilion Fundraising Data --- */
function pav_fund_goal() { return( 80000) }
function pav_fund_current() {return( 68000) }

/* --- Image Functions --- */

var preloadFlag = false; // Set when preloading is complete

function newImage( arg ){ //Create a new image and load it
	if (document.images) { rslt = new Image(); rslt.src = arg; return rslt; } 
}

function preloader() { //Standard image preloader
    // Takes a variable length list of strings which are image paths
    // Returns the created array of images so it can kept (not garbage collected)
    var preloadArray = new Array();
    for( var i=0; i<preloader.arguments.length; i++ ) {
		preloadArray[i] = newImage( preloader.arguments[i] );
	}
    preloadFlag = true;
    return( preloadArray );
}

function changeImages( arg1, arg2 ) { // Swap an image (used by rollovers
	if ( document.getElementById( arg1 ) ) {
		document.getElementById( arg1 ).src = arg2;
	} else 	if( document.images && (preloadFlag == true) ) { 
		for( var i=0; i<changeImages.arguments.length; i+=2 ) {
			document[changeImages.arguments[i]].src = changeImages.arguments[i+1];
		}
	}
}

/* Use this to bypass innerHTML write problems inside a table */
//from http://jonefox.com/blog/2009/05/21/internet-explorer-and-the-innerhtml-property/
//el is the element object handle or element ID
//html is the new element content
//returns new element in case you need a handle to it for further operations.
function replace_el_html( el, html ) {
	if( el ) {
                var oldEl = (typeof el === "string" ? document.getElementById(el) : el);
                var newEl = document.createElement(oldEl.nodeName);

                // Copy the id and className properties
                newEl.id = oldEl.id;
                newEl.className = oldEl.className;

                //set the new HTML and insert back into the DOM
                newEl.innerHTML = html;
                if(oldEl.parentNode)
        	        oldEl.parentNode.replaceChild(newEl, oldEl);
                else
		        oldEl.innerHTML = html;

                //return a reference to the new element in case we need it
                return newEl;
	}
}

/* Used with the Highslide package to duplicate captions onto thumbnails at page load */
// should be called at startup on page load
// Expects caption to be in a <div class=highslide-caption>
// Expects next element to be <div class=thumbcap>, the thumbnail caption
function duplicateCaptions() {

	capsource = document.getElementsByTagName( "div" );
	for ( var a=0;  a<capsource.length; a++ ) {
		if ( capsource[a].className == 'highslide-caption' ) {
			var ns = capsource[a].nextSibling;
			while ( ns.nodeType!=1) { ns = ns.nextSibling }
			if ( ns.className == 'thumbcap' ) {
				replace_el_html( ns, (capsource[a].innerHTML) );
			}
		}
	}
}

/* --- Cookie Functions --- */
function writeCookie( name, value, minutes) { 
	if ( minutes ) { 
		var date = new Date(); 
		date.setTime( date.getTime() + (minutes*60*1000) ); 
		var expires = "; expires=" + date.toGMTString(); 
	} else var expires = ""; 
	document.cookie = name + "=" + value + expires +"; path=/"; 
} 

function readCookie( name ) { 
	var nameEQ = name + "="; 
	var ca = document.cookie.split(';'); 
	for( var i=0; i < ca.length; i++) { 
		var 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 eraseCookie( name ) { createCookie( name, "", -1 ); }

/* --- Random Thumbnail Functions --- */

function randmm( min, max ) { 
    // Random number between min and max, defaults to 1 thru 10
    min = min || 1; max = max || 10; // Argument Defaults
    return( Math.floor( Math.random() * (max - min + 1) + min ) );
}

function pickNofM( n, m ) {
    // Picks n unique random numbers from universe of 1 thru m
    // Returns array of 1 thru n random numbers
    if ( n > m ) { return( null ) } // Prevent infiinte loop
    var a = new Array( n + 1 );
    for ( var i=1; i<=n; i++ ) {
        do {
            a[i] = randmm( 1, m );
            var unique = true;
            for ( var j=1; j<i; j++ ) {
                if ( a[i]==a[j] ) {
                    unique = false;
                    break;
                }
            }
        } while ( !unique );
    }
    return( a );
}

// Pad integer with leading zeros and return as string
function padlz2( n ) { return( n<10 ?  '0'+n : n.toString() ) }
function padlz3( n ) { return( n<10 ? '00'+n : ( n<100 ? '0'+n : n.toString() ) ) }

// The random thumbnail object constructor
function RandomThumbnail( imgname, slots, photos, prefixS, postfixS, prefixL, postfixL ) {
    // Implements a random thubnaim function
    this.image_prefix  = imgname;	// imagename: image name prefeix
    this.image_count   = slots;		// slots: number of photos to display (01 thru NN)
    this.photo_count   = photos;	// photos: total number of photos available (001 thru MMM)
    this.photo_prefixS = prefixS;	// prefix & postfix: path and file name of photos to append to index.
    this.photo_postfixS= postfixS;	// S for thumbnails
    this.photo_prefixL = (prefixL=='*'?prefixS:prefixL);	// Use '*' to mean same as S prefix
    this.photo_postfixL= postfixL;	// L for link to full size
    this.doit = function( reload ){	// Generate & Populate random thumbnails
    	var c = readCookie( 'Stellafane_Random_Image_' + this.image_prefix + '_' + this.image_count );
    	if ( reload && c ) {
    		this.a =  c.split(','); // Reload old values from cookie
    	} else {
    		this.a = pickNofM( this.image_count, this.photo_count ); // Pick new images
    	}
    	for ( var i=1; i<=this.image_count; i++ ) { // Put photos into document
        	if( document.images ) { 
				document[ this.image_prefix + padlz2( i )].src = 
					this.photo_prefixS + padlz3( this.a[i] ) + this.photo_postfixS;
			}
		}
	}
	this.link = function( n ) {		// Follow hyperlink to large image
    	writeCookie( 'Stellafane_Random_Image_' + this.image_prefix + '_' + this.image_count, this.a.toString(), 1 );
		window.location.href = this.photo_prefixL + padlz3( this.a[n] ) + this.photo_postfixL;
		return( true );
	}
}

/* --- E-mail Functions --- */

function nhem( id, user, domain){
// No Harvest E-Mail - hides e-mail addresses by building them on the fly
// Normally, only an id is passed, and that causees a lookup for the user with a default domain
// If the id is '--' then and e-mail address is built from user and domain
// Function returns the complete e-mail address.

	var theusr, thedom, usrlst = new Array;
	usrlst['WM'] = 'WebMaster';
	usrlst['CV'] = 'Convention';
	usrlst['LK'] = 'Links';
	usrlst['MC'] = 'MirrorClass';
	usrlst['MU'] = 'Museum';
	usrlst['SM'] = 'SiteManage';
	
	if ( id=='--') {
		theusr = user;
		thedom = domain;
	} else {
		theusr = usrlst[id];
		thedom = 'Stellafane.org';
	}
	return( theusr + '@' + thedom );
}

function anhem( txt, subj, id, user, domain){
// Anchor No Harvet E-Mail - hides e-mail addresses by building them on the fly.
// txt is the user visible text
// subj is an optional subject for the e-mail
// id, user, domain as above in nhem documenation
// Writes a complete anchor statement directrly to the document
	document.write( '<a href="mailto:'+ nhem(id, user, domain) );
  	if ( subj && subj != "" ) { document.write( '?subject=' + subj ) }
	document.write( '">' + txt + '</a>');
}

// This is now depreicated - use anhem above
function email_webmaster( subj, cls ) {
  document.write( '<a href="mailto:Webmaster@Stellafane.org?subject=' );
  if ( subj && subj != "" ) {
        document.write( '[STMweb] ' + subj + ': "' );
  } else {
        document.write( '[STMweb] No Subject: "' );    
  }
  if ( cls ) { document.write( ' class="' + cls + '"' ) }
  document.write( '>');
}

/* --- Footer Functions --- */

function current_year() { // Returns current calendar year
	var year = new Date().getYear();
	if ( year<1900 ) { year += 1900 }
	return( year );
}

function write_footer_here( rps ) { // Writes the footer into the document
// rps is a string to prefix the URLs to adjust for relative page position in the heierarchy
	document.write( 
		'<hr>' +
		'<table border="0" cellspacing="0" cellpadding="3" style="margin:auto">' );
  	document.write(
		  '<tr><td align="center"><span class="footer">\n' +
	  		'<a class="footer" href="'+rps+'convention/index.html">Convention</a> | ' +
	  		'<a class="footer" href="'+rps+'observing/index.html">Observing</a> | ' +
	  		'<a class="footer" href="'+rps+'tm/index.html">Telescope Making</a> | ' +
	  		'<a class="footer" href="'+rps+'history/index.html">History</a> | ' +
	  		'<a class="footer" href="'+rps+'help/index.html">Help Stellafane</a> | ' +
	  		'<a class="footer" href="'+rps+'misc/index.html">Everything Else</a>' +
		  '</span></td></tr>' );
  	document.write(
		  '<tr><td align="center"><span class="footer">' +
	  		'<a class="footer" href="'+rps+'index.html">Stellafane Home Page</a> | ' +
	  		'<a class="footer" href="'+rps+'news/index.html">News &amp; Events</a> | ' +
	  		'<a class="footer" href="'+rps+'about/sitemap.html">Site Map</a> | ' +
       	  		'<a class="footer" href="'+rps+'search/index.html">Search</a> | ' +
	  		'<a class="footer" href="'+rps+'about/index.html#contact">Contact</a> | ' +
	  		'<a class="footer" href="'+rps+'about/index.html">About</a>' +
		  '</span></td></tr>' );
  	document.write( '<tr><td colspan="2" height="5"></td></tr>' );
  	document.write( 
		  '<tr><td align="center">' +
			'<span class="footer">Copyright &copy; ' + current_year() +
	  		' All Rights Reserved. The Springfield Telescope Makers, Inc.<BR>' +
      		'P.O. Box 601, Springfield, VT 05156&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' +
      		'<a href="mailto:' +  nhem('WM') + '?subject=[STM Footer]">e-mail Stellafane Webmaster</a>'  ); 
    document.write( '</span></td></tr>' );
	document.write( '</table>' );
}

function write_footer( rps ) { // Writes the footer into the document - newer version
// rps is a string to prefix the URLs to adjust for relative page position in the heierarchy
  	document.write( '<ul id="nav" class="nav1">' +
	  		'<li><a class="footer" href="'+rps+'convention/index.html">Convention</a></li>' +
	  		'<li><a class="footer" href="'+rps+'observing/index.html">Observing</a></li>' +
	  		'<li><a class="footer" href="'+rps+'tm/index.html">Telescope Making</a></li>' +
	  		'<li><a class="footer" href="'+rps+'history/index.html">History</a></li>' +
	  		'<li><a class="footer" href="'+rps+'help/index.html">Help Stellafane</a></li>' +
	  		'<li><a class="footer" href="'+rps+'misc/index.html">Everything Else</a></li>'+
		  '</ul>' );
  	document.write( '<ul id="nav" class="nav2">' +
	  		'<li><a class="footer" href="'+rps+'index.html">Stellafane Home Page</a></li>' +
	  		'<li><a class="footer" href="'+rps+'news/index.html">News &amp; Events</a></li>' +
	  		'<li><a class="footer" href="'+rps+'about/sitemap.html">Site Map</a></li>' +
       	  	'<li><a class="footer" href="'+rps+'search/index.html">Search</a></li>' +
	  		'<li><a class="footer" href="'+rps+'about/index.html#contact">Contact</a></li>' +
	  		'<li><a class="footer" href="'+rps+'about/index.html">About</a></li>' +
		  '</ul>' );
  	document.write( '<div class="copyright">Copyright &copy; ' + current_year() +
	  		' All Rights Reserved. The Springfield Telescope Makers, Inc.<br>' +
      		'P.O. Box 601, Springfield, VT 05156&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' +
      		'<a href="mailto:' +  nhem('WM') + '?subject=[STM Footer]">e-mail Stellafane Webmaster</a></div>'  ); 
}

function write_footer_here_members() { // Writes the Members footer into the document
	document.write( 
		'<hr><div align="center" id="STMfooter">' +
		'<table border="0" cellspacing="0" cellpadding="3" id="footer_tbl">' );
  	document.write(
		  '<tr><td align="center"><font class="footer">\n' +
	  		'<a class="footer" href="http://Stellafane.org/convention/index.html">Convention</a> | ' +
	  		'<a class="footer" href="http://Stellafane.org/observing/index.html">Observing</a> | ' +
	  		'<a class="footer" href="http://Stellafane.org/tm/index.html">Telescope Making</a> | ' +
	  		'<a class="footer" href="http://Stellafane.org/history/index.html">History</a> | ' +
	  		'<a class="footer" href="http://Stellafane.org/help/index.html">Help Stellafane</a> | ' +
	  		'<a class="footer" href="http://Stellafane.org/misc/index.html">Everything Else</a>' +
		  '</font></td></tr>' );
  	document.write(
		  '<tr><td align="center"><font class="footer">' +
	  		'<a class="footer" href="http://Members.Stellafane.org/">Stellafane Members Page</a> | ' +
	  		'<a class="footer" href="http://Stellafane.org/index.html">Stellafane Home Page</a> | ' +
	  		'<a class="footer" href="http://Stellafane.org/news/index.html">News &amp; Events</a> | ' +
	  		'<a class="footer" href="http://Stellafane.org/about/sitemap.html">Site Map</a> | ' +
       	  		'<a class="footer" href="http://Stellafane.org/search/index.html">Search</a> | ' +
	  		'<a class="footer" href="http://Stellafane.org/about/index.html#contact">Contact</a> | ' +
	  		'<a class="footer" href="http://Stellafane.org/about/index.html">About</a>' +
		  '</font></td></tr>' );
  	document.write( '<tr><td colspan="2" height="5"></td></tr>' );
  	document.write( 
		  '<tr><td align="center">' +
			'<font class="footer">Copyright &copy; ' + current_year() +
	  		' All Rights Reserved. The Springfield Telescope Makers, Inc.<BR>' +
      		'P.O. Box 601, Springfield, VT 05156&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' +
      		'<a href="mailto:' +  nhem('WM') + '?subject=[STM Footer]">e-mail Stellafane Webmaster</a>'  ); 
    document.write( '</font></td></tr>' );
	document.write( '</table></div>' );
}

/* End of STMcommon.js */
