// namespaces used in this header
YAHOO.namespace("gaia.util.Dom");
YAHOO.namespace("gaia.app");


/**
* Launch flash games from the header
* provides a means for launching the flash games with parameterized n/v pairs
*/
function header_launcher(obj, srv, sid, params) {
	trim_obj = obj.split("&")[0];
  var gaia_game;


  /**
   *  if you edit here, you also have to edit in /src/js/core.js
   */
  var game_dims_ads = {
      'towns': new Array (740, 580),
      'rally': new Array (740, 580),
      'wordbump': new Array (640, 573),
      'slots': new Array (640, 673),
      'blackjack': new Array (640, 673),
      'arranger': new Array (760, 360),
      'jigsaw': new Array (770, 673),
      'cinema': new Array (740, 670),
      'vj': new Array (740, 675),
      'gameshell': new Array (770, 585),
      'battle': new Array (1068,905),
	  'zomg': new Array (1000,555),
      'prom': new Array (740, 580),
      'olympics2008': new Array (764, 652),
      'olympics2008stadium': new Array (740, 580),
      'default': new Array ( 640, 580 )
   };

  var game_dims = {
      'towns': new Array (740, 580),
      'rally': new Array (740, 580),
      'wordbump': new Array (640, 480),
      'slots': new Array (640, 580),
      'blackjack': new Array (640, 580),
      'arranger': new Array (760, 360),
      'jigsaw': new Array (770, 580),
      'cinema': new Array (740, 670),
      'vj': new Array (740, 675),
      'gameshell': new Array (770, 585),
	  'zomg': new Array (1000,555),
      'battle': new Array (1068,905),
      'prom': new Array (740, 580),
      'olympics2008': new Array (764, 652),
      'olympics2008stadium': new Array (740, 580),
      'default': new Array ( 640, 580 )
   };

	var dims = Array();
  if (game_dims[obj] != null) {
    dims = game_dims[obj];
  } else {
    dims = game_dims['default'];
  }

	// add an & to sid if there is one
	if (sid.length > 0) sid = "&"+sid;
	else sid='';
	
	if (params != null) {
		param_list = "&" + params.replace(/,/g, "&").replace(/:/g, "=");
	} else {
		param_list = "";
	}
  
    var resizable = 'no';
    if ( obj == 'zomg' || obj == 'gameshell' ) resizable='yes';

    gaia_game = window.open( "http://"+srv+"/launch/"+obj+"?"+param_list+sid , trim_obj, "alwaysRaised=yes,toolbar=no,status=no,scrollbars=no,menubar=no,locationbar=no,width="+dims[0]+",height="+dims[1]+",resizable=" + resizable);
    
    if ((!gaia_game) || (gaia_game.closed)) {
        // stopped. do we have flash to notify?
        // send fail to browser
        var message = "";
        message += "We detected that you have a popup blocker"+"\n"+"that is stopping the game from loading."+"\n";
        message += "Please check your browser's settings and try again.";
        alert(message);
    } else {
        gaia_game.focus();
    }

	return false;
};

var sfHover = function() {
	var navIcons = $("navicons");
	if (navIcons) {
		var sfEls = navIcons.getElementsByTagName("LI");
		for (var i=0; i<sfEls.length; i++) {
			sfEls[i].onmouseover=function() {
				this.className+=" sfhover";
			}
			sfEls[i].onmouseout=function() {
				this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
			}
		}
	}
}

function $(strId) {
    if (typeof strId == "string") {
	    return YAHOO.util.Dom.get(strId);
    }
    return strId;
}

if(typeof Array.prototype.push != "function"){
	Array.prototype.push = function (){
		for(var i=0; i<arguments.length; i++){
        	this[this.length] = arguments[i];
        }
		return this.length;
	}
}

function getElementsByClassName(oElm, strTagName, strClassName){
    var tag_scope = (strTagName == "*") ? null : strTagName;
    return YAHOO.util.Dom.getElementsByClassName(strClassName, tag_scope, oElm);
}


function addClassName(oElm, strClassName){
    return YAHOO.util.Dom.addClass(oElm, strClassName);
}

function removeClassName(oElm, strClassName){
    return YAHOO.util.Dom.removeClass(oElm, strClassName);
}

function getElementsByAttribute(oElm, strTagName, strAttributeName, strAttributeValue){
    return YAHOO.gaia.util.Dom.getElementsByAttribute(strAttributeName, strAttributeValue, strTagName, oElm);
}

function getStyle(oElm, strCssRule){
	return YAHOO.util.Dom.getStyle(oElm.id.toString(), strCssRule);
}

ELO = {
    functionsToCallOnload: {
        push: function(execute_call) {
            YAHOO.util.Event.onContentReady("wrap", function() { eval(execute_call); });
        }
    }
}

/**
* Migration of Robert Nyman's getElementsByAttribute
* coded for integration with the yahoo UI library
*/
YAHOO.gaia.util.getElementsByAttribute = function(strAttributeName, strAttributeValue, strTagName, oRootElement) {
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	var oAttributeValue = (typeof strAttributeValue != "undefined")? new RegExp("(^|\\s)" + strAttributeValue + "(\\s|$)") : null;
	var oCurrent;
	var oAttribute;
	for(var i=0; i<arrElements.length; i++){
		oCurrent = arrElements[i];
		oAttribute = oCurrent.getAttribute && oCurrent.getAttribute(strAttributeName);
		if(typeof oAttribute == "string" && oAttribute.length > 0){
			if(typeof strAttributeValue == "undefined" || (oAttributeValue && oAttributeValue.test(oAttribute))){
				arrReturnElements.push(oCurrent);
			}
		}
	}
	return arrReturnElements;
}


/**
* Gaia Online Form Submit Button Replacement
* Used to replace submit buttons with button tags in order
* to support proper stylization in all browsers, including
* Camino and Safari.
*/
YAHOO.gaia.util.Dom.swapSubmit = function() {
    this.replacedEles = new Object();
    
    if (YAHOO.widget.LogWriter) {
        this.logger = new YAHOO.widget.LogWriter("swapSubmit");
    }
    
    this.log("Instance of swapSubmit creaited", "info");
}
YAHOO.gaia.util.Dom.swapSubmit.prototype.log = function(message, level) {
    if (YAHOO.widget.LogWriter) {
        this.logger.log(message, level);
    }
}
YAHOO.gaia.util.Dom.swapSubmit.prototype.replace = function(formid, eleid) {
    var ele = $(eleid);
    
    if (ele == null) {
        this.log("Could not find occurance of "+eleid.toString()+" in DOM", "error");
        return;
    }

	// build thew new element.
	var o = this.build(ele);
		
	// get the parent node.
	var pn = ele.parentNode;
	
	// use a blank span temporarily to save IE from itself.
	// re-added to live code 05.24.07 [kaia] (orig:05.03.07)
	var blank = document.createElement('span');
	pn.appendChild(blank);
	pn.removeChild(ele);
	pn.appendChild(o);
	pn.removeChild(blank);

	/** 
	* old style of replacing the node.
	* replaced with blank span on 05.24.07 [kaia]
	* * * * * * * * * * * * * * * * * * * * * * * *
	* pn.removeChild(ele);
	* pn.appendChild(document.createTextNode(''));
	* pn.appendChild(o);
	*/
	
	// define the values of the replaced element.
	this.replacedEles[eleid]            = new Object();
	this.replacedEles[eleid]['name']    = ele.getAttribute('name');;
	this.replacedEles[eleid]['value']   = ele.getAttribute('value');
	this.replacedEles[eleid]['click']   = ele.getAttribute('onclick');
	this.replacedEles[eleid]['form']    = formid;
	
	this.log("Replaced "+eleid.toString()+" for form "+formid.toString(), "info");
	//window.location = location.href;
}
YAHOO.gaia.util.Dom.swapSubmit.prototype.build = function(ele) {
    
	// create the new element
	var o = document.createElement("button");
    
	// make sure it has the old id and classname.
    o.id = ele.id;
    o.className = ele.className;
	
	// moved the onclick execution to the submitForm function. 05.24.07 [kaia]
    //o.setAttribute("onclick", ele.getAttribute("onclick"));
    
	// add a listener to make it submit the form like a submit button would.
	YAHOO.util.Event.addListener(o, "click", this.submitForm, this);
	
    this.log("Added onclick handler for "+o.id.toString(), "info");
    
    return o;
}
YAHOO.gaia.util.Dom.swapSubmit.prototype.buildInputField = function(name, value) {
    var o = document.createElement("input");

    o.setAttribute("type", "hidden");
    o.id = name;
    o.setAttribute("name", name);
    o.setAttribute("value", value);

    return o;
}
YAHOO.gaia.util.Dom.swapSubmit.prototype.submitForm = function(e, obj) {
    
    if (obj._disabled) {
        return false;
    }
    
    // load the click id and get all the names
    // name = the original form control element's name
    // value = the original value of the original form control
    // form = the form this element belongs to
    var clickId         = this.id;
    var name            = obj.replacedEles[clickId]["name"];
    var value           = obj.replacedEles[clickId]["value"];
    var formid          = obj.replacedEles[clickId]["form"];
    var submit_form     = $(formid);
    obj.log("Submit on form "+formid+" called", "info");
    // add an input field with the proper name and value
    // if there is no form, just bail
    if (!$(formid)) {
        obj.log("There is no form to submit for this button", "info");
    }
    else {
        var o = obj.buildInputField(name, value);
        submit_form.appendChild(o);
        submit_form.submit();
    }
}

YAHOO.gaia.util.Dom.swapSubmit.prototype.disable = function() {
    this._disabled = true;
}
YAHOO.gaia.util.Dom.swapSubmit.prototype.enable = function() {
    this._disabled = false;
}

var GAIA_SwapSubmit = {
	replace: function(formid, eleid) {
        var ss = new YAHOO.gaia.util.Dom.swapSubmit();
        ss.replace(formid, eleid);
	}
};


/**
* Utility for checking / unchecking all items in a form
*/
YAHOO.gaia.util.Dom.checkAll = function(formid, mark) {
    
}

/**
 * Mimics the PHP version of addSlashes. Escapes several potentially dangerous characters
 * single quote '
 * double quote "
 * slash \
 * @author tlynn
 * @param {String} str The unescaped string
 * @return {String} Escaped string
 */
YAHOO.gaia.util.Dom.addSlashes = function(str) {
	var tmp = str.split('');
	var cleanStr = new Array();
	for (var x = 0; x < tmp.length; x++) {
		switch (tmp[x]) {
			/*case String.fromCharCode(0):
				cleanStr.push('\\');
				cleanStr.push(String.fromCharCode(0));
				break;*/
			case "'":
			case '"':
			case '\\':
				cleanStr.push('\\');
				/* break is missing *intentionally* */
			default:
				cleanStr.push(tmp[x]);
				break;
		}
	}
	return cleanStr.join('');
};

var GAIA_FormHandler = {
	checkall: function( formid, mark ) {
		var form = $(formid);
		var nodes = document.getElementsByTagName('input');
		if ( mark=='open' && typeof openrec=='undefined' ) return;
		for ( var i=0; i< nodes.length; i++) {
			if ( nodes[i].getAttribute( 'type' )!='checkbox') continue;
			var value = nodes[i].getAttribute('value');
			if ( mark==true ) nodes[i].setAttribute( 'checked', true );
			else if ( mark=='some' && Math.random() > .5 ) nodes[i].setAttribute( 'checked', true );
			else if ( mark=='open' && openrec[value]==1 ) nodes[i].setAttribute( 'checked', true );
			else {
				nodes[i].setAttribute( 'checked', 0);
				nodes[i].removeAttribute( 'checked' );
			}
		}	
	}
};

var GAIA_Element = {
	show: function( divname ) {
		var _div = $(divname);
		if (_div) {
			_div.style.visibility="visible";
			_div.style.display="block";
		}
	},
	hide: function( divname ) {
		var _div = $(divname);
		if (_div) {
			_div.style.visibility="hidden";
			_div.style.display="none";
		}
	},
	setVisibilities: function( props ) {
		for (elename in props) {
			if (props[elename] == true) {
				this.show(elename);
			}
			else {
				this.hide(elename);
			}
		}
	},
	stopform: function() {
		return false;
	}
};



ELO.functionsToCallOnload.push("if(window.attachEvent) sfHover();");


// this will run a swapsubmit on all input.swapSubmitButton that exist on the page
// both when #content loads, and when the dom has completed (in case of something in the
// footer).  Orig code from Kaia's Moddog.  Does not conflict.
// open scope
(function(){

// creates a function that will swap all input.swapSubmitButton with the gaia util class
var swapSubmitLoader = function(){
    // if there's nothing to swap, return false. prevents conflicts with onDomReady and moddog
    if( !YAHOO.util.Dom.getElementsByClassName('swapSubmitButton', 'input') ) return false;
    
    // create an instance of swap submit
    var SwapSubmit = new YAHOO.gaia.util.Dom.swapSubmit();
    
    // capture the inputs of .swapSubmitButton
    var allbuttons = YAHOO.util.Dom.getElementsByClassName('swapSubmitButton', 'input');
    
    // loop and assign an anon function to each button
    // this is where the replace is
    // this makes one swap submit instance hold onto all swaps for the page
	for( var i=0; i< allbuttons.length; i++) {
        YAHOO.util.Event.onAvailable(allbuttons[i].id, function() {
            var element = document.getElementById( this.id );
            SwapSubmit.replace(element.form.id, this.id);
		}); 
	}
	
	// done
	return true;
}

// add listeners
YAHOO.util.Event.onContentReady('content', swapSubmitLoader);
//YAHOO.util.Event.onContentReady('footer', swapSubmitLoader);
})(); // end scope

