/*
	name			: ClassBehaviours, the javascript framework based on class-name parsing
	update			: 9.3.17
	author			: Maurice van Creij
	dependencies	: jquery.classbehaviours.js
	info			: http://www.classbehaviours.com/

    This file is part of jQuery.classBehaviours.

    ClassBehaviours is a javascript framework based on class-name parsing.
    Copyright (C) 2008  Maurice van Creij

    ClassBehaviours 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 3 of the License, or
    (at your option) any later version.

    ClassBehaviours 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 ClassBehaviours. If not, see http://www.gnu.org/licenses/gpl.html.
*/

	// create the jQuery object if it doesn't already exist
	if(typeof(jQuery)=='undefined') jQuery = function(){};

	// create the root classbehaviours object if it doesn't already exist
	if(typeof(jQuery.classBehaviours)=='undefined') jQuery.classBehaviours = function(){};

	// create the handlers child object if it doesn't already exist
	if(typeof(jQuery.classBehaviours.handlers)=='undefined') jQuery.classBehaviours.handlers = function(){}

	// Replace a link to external content with the actual content
	jQuery.classBehaviours.handlers.insertFromFile = {
		// properties
		name: 'insertFromFile',
		index: 0,
		// methods
		start: function(node){
			// if the node is marked to load automatically start loading else set an onclick event
			automatic = jQuery.classBehaviours.utilities.getClassParameter(node, 'auto', 'no');
			if(node.nodeName=='IFRAME' || automatic=='yes') this.clicked(node)
			else if(node.nodeName == 'FORM') node.onsubmit = this.clicked
			else node.onclick = this.clicked;
		},
		wait: function(importProgress, referedNode, importError){
			// get the target for the indicator
			targetId = jQuery.classBehaviours.utilities.getClassParameter(referedNode[0], 'target', null);
			if(targetId!=null) targetNode = document.getElementById(targetId)
			else targetNode = referedNode[0];
			// display the progress indicator
			jQuery.classBehaviours.utilities.setClassParameter(referedNode[0], 'step', importProgress);
			if(targetNode.innerHTML) targetNode.innerHTML = (importProgress>=0) ? '<h3>loading:</h3><meter><span>' + Math.round(importProgress*100) + '%</span></meter>' : '<h3>error: </h3><meter><span>' + importError + '</span></meter>';
		},
		insert: function(importedObj, referedNode, importedText){
			var iff = jQuery.classBehaviours.handlers.insertFromFile;
			// clean the imported text and replace optional strings
			importedText = iff.clean(importedObj, referedNode[0], importedText);
			// if an ID was given
			targetId = jQuery.classBehaviours.utilities.getClassParameter(referedNode[0], 'target', null);
			if(targetId!=null){
				// use that as target
				targetNode = document.getElementById(targetId);
			}else{
				// or replace the current node
				newDiv = document.createElement('div');
				newDiv.id = (newDiv.id) ? newDiv.id : iff.name + iff.index++ ;
				referedNode[0].parentNode.replaceChild(newDiv, referedNode[0]);
				targetNode = document.getElementById(newDiv.id);
			}
			// insert the content in the given container
			targetNode.innerHTML = importedText;
			// restore any relevant form values
			iff.restore(targetNode, referedNode[1]);
			// activate any classbehaviours in there
			jQuery.classBehaviours.parser.parseNode(targetNode);
			// OPTIONAL: replace the title
			replaceTitleId = jQuery.classBehaviours.utilities.getClassParameter(referedNode[0], 'title', null);
			if(replaceTitleId!=null) document.getElementById(replaceTitleId).innerHTML = referedNode[0].title;
		},
		restore: function(formNode, postValues){
			// for all the post name value pairs
			postValuePairs = postValues.split('&');
			for(var a=0; a<postValuePairs.length; a++){
				postName = postValuePairs[a].split('=')[0];
				postValue = unescape(postValuePairs[a].split('=')[1]);
				// get the target node(s)
				postNodes = document.getElementsByName(postName);
				if(postNodes.length>0){
					// if this is a radio button or a checkbox
					if(postNodes[0].type=='radio' || postNodes[0].type=='checkbox'){
						for(var b=0; b<postNodes.length; b++){
							if(postNodes[b].value == postValue) postNodes[b].checked = true;
						}
					}
					// if this is a select
					if(postNodes[0].nodeName=='SELECT'){
						for(var c=0; c<postNodes[0].length; c++){
							if(postNodes[0][c].value == postValue || postNodes[0][c].firstChild.nodeValue == postValue){
								postNodes[0].selectedIndex = c;
							}
						}
					}
					// if this is a text input
					if(postNodes[0].nodeName=='INPUT' && (postNodes[0].type=='text' || postNodes[0].type=='file' || postNodes[0].type=='password')){
						postNodes[0].value = postValue;
					}
					// if this is a textarea
					if(postNodes[0].nodeName=='TEXTAREA'){
						postNodes[0].value = postValue;
					}
				}
			}
		},
		clean: function(importedObj, referedNode, importedText){
			// strip the content from the body
			if(importedText.indexOf('<body')>-1){
				importedText = importedText.split('<body')[1].split('</body>')[0];
				importedText = importedText.substr(importedText.indexOf('>') + 1, importedText.length);
			}
			// cut the content from a specific ID
			targetId = jQuery.classBehaviours.utilities.getClassParameter(referedNode, 'target', null);
			sourceId = jQuery.classBehaviours.utilities.getClassParameter(referedNode, 'source', targetId);
			if(sourceId!=null){
				// if we have an XML DOM to work with
				if(importedObj!=null){
					// look through all nodes until you find one with the right ID
					allNodes = importedObj.getElementsByTagName('*');
					for(var a=0; a<allNodes.length; a++){
						if(allNodes[a].getAttribute('id')==sourceId){
							importedText = (allNodes[a].xml!=null) ? allNodes[a].xml : (new XMLSerializer()).serializeToString(allNodes[a]) ;
						}
					}
				// otherwise try to get it from the text
				}else{
					// if the iframe wasn't there before
					if(window.frames['insertFromFile0'] == null){
						// let's make a new iframe, because we're really fond of those
						newIframe = document.createElement('IFRAME');
						newIframe.setAttribute('name', 'insertFromFile0');
						newIframe.setAttribute('id', 'insertFromFile0');
						newIframe.setAttribute('class', 'popUpLayer');
						newIframe.setAttribute('style', 'visibility:hidden; position:absolute; left:-2000px; top:-2000px;');
						// add it to the page
						document.body.appendChild(newIframe);
					}
					// stuff the imported text into iframe
					window.frames['insertFromFile0'].document.body.innerHTML = importedText;
					// get the contents of the source id from the iframed document
					if(window.frames['insertFromFile0'].document.getElementById(sourceId) != null)
						importedText = window.frames['insertFromFile0'].document.getElementById(sourceId).innerHTML;
				}
			}
			// process optional replaces
			replaceId = jQuery.classBehaviours.utilities.getClassParameter(referedNode, 'replace', null);
			if(replaceId!=null){
				replaceInputs = document.getElementById(replaceId).getElementsByTagName('INPUT');
				for(var a=0; a<replaceInputs.length; a++){
					importedText = importedText.replace(replaceInputs[a].name, replaceInputs[a].value);
				}
			}
			// return the cleaned content
			return importedText;
		},
		// events
		clicked: function(that){
			var objNode = (typeof(this.nodeName)=='undefined') ? that : this ;
			var iff = jQuery.classBehaviours.handlers.insertFromFile;
			// try to get an URL from somewhere
			targetHref = objNode.getAttribute('href');
			targetSrc = objNode.getAttribute('src');
			targetAction = objNode.getAttribute('action');
			targetLongdesc = objNode.getAttribute('longdesc');
			targetUrl = (targetHref!=null) ? targetHref :
				(targetSrc!=null) ? targetSrc :
				(targetAction!=null) ? targetAction :
				(targetLongdesc!=null) ? targetLongdesc :
				document.location.href ;
			// get the post values
			postValues = jQuery.classBehaviours.ajax.getPostValues(objNode);
			// place the AJAX request and cancel the click
			return (objNode.nodeName=='BUTTON' || objNode.nodeName=='INPUT' || objNode.nodeName=='FORM') ?
				jQuery.classBehaviours.ajax.addSubmit(objNode, iff.insert, iff.wait, null, new Array(objNode, postValues, targetUrl)) :
				jQuery.classBehaviours.ajax.addRequest(targetUrl, iff.insert, iff.wait, postValues,  new Array(objNode, postValues, targetUrl)) ;
		}
	}

	// add this addon to the jQuery object
	if(typeof(jQuery.fn)!='undefined'){
		// extend jQuery with this method
		jQuery.fn.insertFromFile = function(){
			return this.each(
				function(){
					jQuery.classBehaviours.handlers.insertFromFile.start(this);
				}
			);
		};
		// set the event handler for this jQuery method
		$(document).ready(
			function(){
				$(".insertFromFile").insertFromFile();
			}
		);
	}

