/*pirates and me page builder -- prototype based xml page renderer - js front end+
Copyright (C) 2006  Stephen S. Bussetti

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.*/

//init globals
document.xml_obj = '';
document.xml_loaded = false;

//max depth to render in xml hierarchy...
var MAXRECURSE = 32;
cbar_open = 0;

if (! document.nocomp )
{
	Event.observe(window, 'load', function(){
		getVars();	
		if ( ! document.page && document.page != 0 )
			document.page = 'index';
		
		xml_req('/cgi-bin/piratesandme.cgi', 'get', 'fn='+document.page);
		if ( $$('div#header_splash a').length )
			setTimeout('Nifty("div#header_splash a","bl fixed-height")', 1000);

		if ( $('curtain') )
			setTimeout("Element.hide('curtain')", 1500);
	});
}
/*ADDITIONAL STYLE FUNCS*/

/*from scriptaculous treasure chest for resize effects*/

Effect.ResizeTo = Class.create();
Object.extend(Object.extend(Effect.ResizeTo.prototype, Effect.Base.prototype), {
  initialize: function(element, toWidth, toHeight) {

    this.element      = $(element);
    this.toWidth      = toWidth;
    this.toHeight     = toHeight;

    this.originalWidth  = parseFloat(Element.getStyle(this.element,'width')  || 0);
    this.originalHeight = parseFloat(Element.getStyle(this.element,'height') || 0);

    this.effectiveWidth = this.toWidth 
                        - parseFloat(Element.getStyle(this.element,'margin-left') || 0) 
                        - parseFloat(Element.getStyle(this.element,'margin-right') || 0) 
                        - (document.compatMode == 'BackCompat' ? 0 : // height includes padding & border in IE BackCompat mode
                            parseFloat(Element.getStyle(this.element,'padding-left') || 0) 
                            + parseFloat(Element.getStyle(this.element,'padding-right') || 0) 
                            + parseFloat(Element.getStyle(this.element,'border-left-width') || 0)
                            + parseFloat(Element.getStyle(this.element,'border-right-width') || 0));

    this.effectiveHeight = this.toHeight
                        - parseFloat(Element.getStyle(this.element,'margin-top') || 0) 
                        - parseFloat(Element.getStyle(this.element,'margin-bottom') || 0) 
                        - (document.compatMode == 'BackCompat' ? 0 : // height includes padding & border in IE BackCompat mode
                            parseFloat(Element.getStyle(this.element,'padding-top') || 0) 
                            + parseFloat(Element.getStyle(this.element,'padding-bottom') || 0) 
                            + parseFloat(Element.getStyle(this.element,'border-top-width') || 0)
                            + parseFloat(Element.getStyle(this.element,'border-bottom-width') || 0));

    this.options = arguments[3] || {};

    if (this.effectiveWidth < 0) this.effectiveWidth = 0;
    if (this.effectiveHeight < 0) this.effectiveHeight = 0;

    if (this.originalWidth == this.effectiveWidth &&
        this.originalHeight == this.effectiveHeight) {
      return;
    }
	this.start(this.options);
},
update: function(position) {
  widthd  = this.effectiveWidth * (position) + this.originalWidth * (1 - position);
  heightd = this.effectiveHeight * (position) + this.originalHeight * (1 - position);
  this.setPosition(widthd, heightd);
},
setPosition: function(widthd, heightd) {
  this.element.style.width = widthd+'px';
  this.element.style.height = heightd+'px';
}
});

function getVars() {
	if (! document.location.href.split('?')[1])
		return;

	varArray = document.location.href.split('?')[1].split('&');

	for(var x=0; x<varArray.length; x++)
	{
		var tmp = varArray[x].split('=');
		document[unescape(tmp[0])] = unescape(tmp[1]);
	}
};

/* CORE PAGE BUILDING SUBS */

//build page-rep object
function xml_req (url, meth, pars) {
	document.xml_loaded = false;
	document.xml_obj = '';
	var myAjax = new Ajax.Request(
		url, 
		{
			method: meth, 
			parameters: pars, 
			onComplete: function (oReq, oJSON) {
				//import object 
				try { document.xml_obj = oReq.responseText.evalJSON(true); } catch(e) { };
							
				//pull callback out and store for execution at end of Complete phase..
				var callback = document.xml_obj[0].callback;
				delete document.xml_obj[0].callback;

				//make accessors
				document.xml_obj.findPath = function(pathList, Type) {
					var currArr = document.xml_obj;
					pathList.each( function(reqPathElem) {
						currArr.each( function (pathElem) {
							if(pathElem[reqPathElem])
								currArr = pathElem[reqPathElem];
						});
					});
					if (! Type)
						return ( currArr[0]['content'] ? currArr[0]['content'] : '' );
					else
						return currArr[0][Type];
				};
				
				document.xml_obj.setStyle = function(oObj, oStyle) {
					var newStyle = $A();
					oStyle.each( function(styEm) {
						newStyle.push(styEm);
					});
					
					for (var i = 0; i < newStyle.length; i++)
						for ( var key in newStyle[i])
							oObj.style[key.camelize()] = newStyle[i][key];
				};

				eval(callback);
			},
			onSuccess: function () { document.xml_loaded = true;  },
			onFailure: function(e) { alert(e); }
		});
	return true;
}

function renderObject (path) {
	var oTarget;
	if (path[(path.length - 1)].match(/^body$/i))
	{
		oTarget = document.body;
		document.xml_obj.setStyle(oTarget, document.xml_obj.findPath(path, 'style'));
	}
	else
	{

		oTarget = $(path[(path.length - 1)]);

		oTarget.innerHTML =  document.xml_obj.findPath(path) + oTarget.innerHTML;
		if(document.xml_obj.findPath(path, 'style'))
			document.xml_obj.setStyle(oTarget, document.xml_obj.findPath(path, 'style'));
	
		if(typeof(oTarget.style) != 'undefined')
			oTarget.className = oTarget.style.className;

		if(oTarget.style.nifty)
			setTimeout("Nifty('"+oTarget.nodeName+'#'+oTarget.id+"', '"+oTarget.style.nifty+"')", 1000);
		else if(oTarget.style.ruzee)
			setTimeout("RUZEE.ShadedBorder.create(\""+oTarget.style.ruzee+"\").render('"+oTarget.id+"')", 5000);

		if(oTarget.style.aculous)
		{			
			Element.hide(oTarget.id);
			if( ! oTarget.style.aculous.match(/^hide$/i))
			{
				var effects = oTarget.style.aculous.split('|');				
				setTimeout( function() { new Effect[effects[0]]($(oTarget.id)); }, ( oTarget.style.ac_timeout ? oTarget.style.ac_timeout : 1000 ));
			}	
		}

	}

	return true;
}

function rec_all (currArr, memory, depth) {
    	
	if ( ! memory )
		memory = $A([]);
	
    	if ( ! depth )
		depth = 0;
    	else if (depth > MAXRECURSE)
		return memory;

	$A(currArr).each( function (oKeyList) {
		var keyList = $H(oKeyList).keys();
		$A(keyList).each( function(key) {
			if( ! key.match(/^style$/i) && ! key.match(/^content$/i) )
			{
				memory.push(key);
				depth++;

				var rav = rec_all(currArr[0][key], memory, depth);
				if (rav)
					memory = $A(rav);
			}
			else if ( key.match(/^style$/) )
			{
				renderObject(memory);
				depth--;
			}
		});
	});

	memory.pop();
	return memory;
}

function buildpage_action() {
	if (document.xml_loaded)
		rec_all(document.xml_obj);
};
