/*
* Copyright 2008 Municipality of Ancona
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*   http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

var onPageLoaded = new FnArray();

/*************************************
 * run external initialize functions *
 *************************************/
function initAll () {
    onPageLoaded.execute();
}

/******************************************************************************
 * This function adds events to handle multiple funcitions                    *
 * It attachs to the given object (obj) at the event (type) the function (fn) *
 * For example It is useful to attach fuctions to the onload event of the     *
 * window like this: addEvent(window, 'load', foo);                           *
 ******************************************************************************/
function addEvent(obj, evType, fn) { 
  if (obj.addEventListener) { 
    obj.addEventListener(evType, fn, false); 
    return true; 
  } else if (obj.attachEvent) { 
    var r = obj.attachEvent("on"+evType, fn); 
    return r; 
  } else { 
    return false; 
  } 
}


/***********************************************
 * Ajax Includes contents into a specified div *
 ***********************************************/

//To include a page, invoke ajaxinclude("afile.htm", "divId")
//Included file MUST be from the same domain as the page displaying it.

var rootdomain="http://"+window.location.hostname;

//Includes the content of the url into the given div and apply the specified CSS to the document
function ajaxIncludeGetWithCSS(elementId, url, cssRef) {
	writeCssElement(cssRef);
	ajaxIncludeGet(elementId, url);
}

//Post the form data to the given URL loading the given css
function ajaxIncludePostWithCSS(elementId, formId, url, cssRef) {
	writeCssElement(cssRef);
	ajaxIncludePost(elementId, formId, url);
}

//Includes the content of the url into the given div
function ajaxIncludeGet(elementId, url) {
	var page_request = false;
	if (window.XMLHttpRequest) // if Mozilla, Safari etc
		page_request = new XMLHttpRequest();
		else if (window.ActiveXObject){ // if IE
			try {
				page_request = new ActiveXObject("Msxml2.XMLHTTP");
			} 
			catch (e){
				try{
					page_request = new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch (e){}
			}
		} else {
			return false;
		}
	page_request.open("GET", url, false); //get page synchronously 
	page_request.setRequestHeader("X-View-Mode", "html/fragment");
	page_request.setRequestHeader("Connection", "close");
	page_request.send(null);
	writeContent(page_request, elementId);
}

//Includes the content of the url into the given div
function ajaxIncludePost(elementId, formName, url) {
	var page_request = false;
	var postData = preparePostData(formName);
	
	if (window.XMLHttpRequest) // if Mozilla, Safari etc
		page_request = new XMLHttpRequest();
	else if (window.ActiveXObject){ // if IE
		try {
			page_request = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e){
			try{
				page_request = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e){}
		}
	} else {
		return false;
	}
	page_request.open("POST", url, false); //get page synchronously 
	page_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	page_request.setRequestHeader("X-View-Mode", "html/fragment");
	page_request.setRequestHeader("Content-length", postData.length);
	page_request.setRequestHeader("Connection", "close");
	page_request.send(postData);
	writeContent(page_request, elementId);
}


//Prepare the Post request based upon form data
function preparePostData(formName) {
	var theForm = document.forms[formName]
	var numElements = theForm.elements.length;
	var postString = "";
	
	for(var i = 0; i < numElements; i++) {
		if ((theForm.elements[i].type == "radio") || (theForm.elements[i].type == "checkbox")) {
			if (theForm.elements[i].checked) {
				if(postString.length > 1)
					postString += "&";
				postString += theForm.elements[i].name+"="+encodeURIComponent(theForm.elements[i].value);
			}
		} else if (theForm.elements[i].type == "select") {
			if(postString.length > 1)
				postString += "&";
			postString += theForm.elements[i].name+"="+encodeURIComponent(theForm.elements[i].selectedIndex);		
		} else if (theForm.elements[i].type == "submit") {
			//Do nothing
			;
		} else {
			if(postString.length > 1)
				postString += "&";
			postString += theForm.elements[i].name+"="+encodeURIComponent(theForm.elements[i].value);
		}
	}
	
	return postString;
}


//writes the content into the div.
function writeContent(page_request, elementId){
	var theDiv = document.getElementById(elementId);
	if (window.location.href.indexOf("http")==-1 || page_request.status==200) {
		if (theDiv) {
			theDiv.innerHTML=page_request.responseText;
		} else {
			theDiv.innerHTML="Content NOT Available.";
		}
	} else {
		theDiv.innerHTML="Content NOT Available.";
	}
}

//Writes the given CSS link into the head section of the page
function writeCssElement(cssRef) {
	var headElement = document.getElementsByTagName("head").item(0);
	if (headElement) {
		var fileRef=document.createElement("link");
		fileRef.setAttribute("rel", "stylesheet");
		fileRef.setAttribute("type", "text/css");
		fileRef.setAttribute("href", cssRef);
		headElement.appendChild(fileRef);
	}
}

/*******************************
 * Handles a functions handler *
 *******************************/

// EXAMPLE:
// function hello(){ alert("hello"); }
// function goodbye( name ){ alert( "Goodbye " + name ); }
// var foo = new FnArray();
// foo.add(hello);
// foo.add("alert('function from string')");
// foo.execute();
 
function FnArray() { 
    this.funcs = new Array; 
} 

FnArray.prototype.add = function(f) {
    if( typeof f!= "function" ) {
        f = new Function(f);
    }

    this.funcs[this.funcs.length] = f;
}

FnArray.prototype.execute = function() {
    for( var i=0; i<this.funcs.length; i++ ) {
        this.funcs[i]();
    }
}

