/************************
*	** Métodos disponiveis:
*
*	* Auxiliares **
*	@name: externalLinks()
*	@name: getDomStyle(str)
*	@name: getText(obj)
*	@name: getHtml(obj)
*	@name: clearInnerHTML(obj)
*	@name: clearWhiteSpace(obj)
*
*
*	* Manipulação DOM *
*	@name: getTags(strTagName,objParentNode) 
*	@name: insertBefore(objNew,objRefer)
*	@name: insertAfter(objNew,objRefer)
*	@name: replaceChild(objNew,objOld)
*	@name: createTextNote(strConteudo) 
*	@name: createElement(strTagName, arrParams, strConteudo)
*	@name: appendChild(objNode, objParentNode)
*	@name: removeChild(objNode)
*	@name: addClass(objTarget, strClass)
*	@name: removeClass(objTarget, strClass)
*	@name: hasClass(objTarget, strClass)
*/

ccDOM = {

	init:function(){
		if(!document.getElementById || !document.createTextNode){return;}
	},	
	
	/*
	*	@description: Retorna um array com atributo e valor para o style
	*/
	getDomStyle: function(str){

		 var parte_string = str.split(":");

		 //String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };

		 style_attrib = parte_string[0].trim();
		 style_values = parte_string[1].trim();

		 style_attrib.camelize();
		 /*
		 if(style_attrib.indexOf("-") > -1){
			 // nameCamelize
			 arr_att = style_attrib.split("-");
			 style_attrib = arr_att[0];
			 style_attrib += arr_att[1][0].toUpperCase();
			 style_attrib += arr_att[1].substring(1, (arr_att[1].length));
		 }
		 */
		 dom_style = new Array(style_attrib, style_values);
		 return dom_style;
	},
	
	/*
	*	@name: getText(obj)
	*	@version: ---
	*	@author: www.slayeroffice.com
	*	@param: obj => Node Object
	*	@return: String
	*	@description: Retorna somente o texto contido no objeto
	*/
	getText: function(obj) {
		// Se for já for o texto retorna o mesmo
		if (obj.nodeType == 3){
			return obj.nodeValue;
		}
		var txt = new Array(),i=0;
		// loop over the children of obj and recursively pass them back to this function
		while(obj.childNodes[i]) {
			txt[txt.length] = so_getText(obj.childNodes[i]);
			i++;
		}
		// return the array as a string
		return txt.join("");
	},
	
	/*
	*	@description: Retorna somente o texto e o html contido no objeto
	*/
	getHtml: function(obj) {
		// Obs.:innerHTML NÃO faz parte do DOM
		// Só está aqui implementado por uma questão de debug
		return obj.innerHTML;
	},

	/*
	*	@name: clearInnerHTML(obj)
	*	@version: ---
	*	@author: Steve - www.slayeroffice.com
	*	@param: obj => Node Object
	*	@return: String
	*	@description: Limpa o conteúdo do objeto
	*/
	clearInnerHTML: function(obj) {
		// so long as obj has children, remove them
		while(obj.firstChild){
			obj.removeChild(obj.firstChild);
		}
		//ou pode ser feito assim - clonando
		/*
		nObj = obj.cloneNode(false); // perform a shallow clone on obj
		obj.parentNode.insertBefore(nObj,obj); // insert the cloned object into the DOM before the original one
		obj.parentNode.removeChild(obj); // remove the original object
		*/
	},

	/*
	*	@name: cleanWhiteSpace(obj)
	*	@version: ---
	*	@author: Cristiano Carlos da Silva
	*	@param: obj => Node Object
	*	@return: String
	*	@description: Limpa espaços em branco, tabulações e quebras de linha
	*/
	clearWhiteSpace: function(obj){
		for (var i=0; i<obj.childNodes.length; i++) {
			var currentNode = obj.childNodes[i];
			if (currentNode.nodeType == 1) {
				ccDOM.clearWhiteSpace(currentNode);
			}
			// Se for do tipo textNode e não tiver texto algum
			if ((currentNode.nodeType == 3) && ((/^\s+$/.test(currentNode.nodeValue)))) {
				obj.removeChild(obj.childNodes[i]);
				i--;
			}
		}
	},
	
	/*
	*	@name: getTags(strTagName,objParentNode) 
	*	@version: 1.0
	*	@author: Andre Metzen
	*	@param: strTagName => String
	*	@param: objParentNode => Node Object(optional)
	*	@return: Array of Node Objects
	*	@description: Retorna todas as tags que possuam nodeName igual a "strTagName" dentro do objeto "objParentNode". 
	*				  Caso "objParentNode" nao seja definido, e usado como padrao "document"
	*/
	getTags: function(strTagName, objParentNode){
		if(typeof objParentNode == "undefined"){
			objParentNode = document;
		}	
		return objParentNode.getElementsByTagName(strTagName);
	},

	/*
	*	@name: insertBefore(objNew,objRefer)
	*	@version: 1.0
	*	@author: Andre Metzen
	*	@param: objNew => Node Object
	*	@param: objRefer => Node Object
	*	@return: Node Object
	*	@description: Insere o objeto "objNew" logo acima na arvore de n� do objeto "objRefer"
	*/
	insertBefore: function(objNew,objRefer){ 
		return objRefer.parentNode.insertBefore(objNew,objRefer);
	},

	/*
	*	@name: insertAfter(objNew,objRefer)
	*	@version: 1.0
	*	@author: Leandro Vieira
	*	@param: objNew => Node Object
	*	@param: objRefer => Node Object
	*	@return: Node Object
	*	@description: Insere o objeto "objNew" logo abaixo na arvore de n� do objeto "objRefer"
	*/
	insertAfter: function(objNew,objRefer){ 
		return objRefer.parentNode.insertBefore(objNew,objRefer.nextSibling);
	},

	/*
	*	@name: replaceChild(objNew,objOld)
	*	@version: 1.0
	*	@author: Andre Metzen
	*	@param: objNew => Node Object
	*	@param: objOld => Node Object
	*	@return: Node Object, false
	*	@description: Substitue o objeto "objOld" pelo objeto "objNew"
	*/
	replaceChild: function(objNew,objOld){
		if(objOld.parentNode){
			return objOld.parentNode.replaceChild(objNew,objOld);
		}
		else{
			return false;
		}
	},

	/*
	*	@name: createTextNote(strConteudo) 
	*	@version: 1.0
	*	@author: Andre Metzen
	*	@param: strConteudo => String
	*	@return: Text Node Object, false
	*	@description: Cria e retorna um text node com o conteudo passado em "strConteudo"
	*/
	createTextNote: function(strConteudo){
		if(typeof strConteudo == "string"){
			return document.createTextNode(strConteudo);
		}
		else{
			return false;
		}
	},

	/*
	*	@name: createElement(strTagName, arrParams, strConteudo)
	*	@version: 1.0
	*	@author: Diego Nunes, adaptado por Cristiano Carlos da Silva
	*	@param: strTagName => String
	*	@param: arrParams =>Array of strings; ex: ["href=#","target=_blank"]
	*	@param: strConteudo => String
	*	@return: Node Object
	*	@description: Cria um novo elemento do tipo "strTagName". O parametro "arrParams" sao os atributos que serao aplicadas ao objeto.
	*/
	createElement: function(strTagName, arrParams, strContent){
		var i, j, newElement, arrParameters;

		if(document.all){
			// Isso é algum tratamento específico para o IE
			// acho que cria no padrão innerHTML ou não
			var fixIEParams = ["name","enctype"];
			//alert('que diabos é document.all');
			strTagName = '<'+strTagName+' ';		
			if(arrParams instanceof Array){
				for(i=0; i<arrParams.length && (arrParameters = arrParams[i].split("=")); i++)
					for(j=0; j<fixIEParams.length; j++){
						if(arrParameters[0] == fixIEParams[j]){
							strTagName += arrParameters[0]+'="'+arrParameters[1]+'" ';
						}
					}
			}
			strTagName += '>';
		}

		newElement = document.createElement(strTagName);
		
		if(arrParams instanceof Array){
			for(i=0; i<arrParams.length && (arrParameters = arrParams[i].split("=")); i++){	
				if(arrParameters[0] == "style"){
					dom_style = ccDOM.getDomStyle(arrParameters[1]);
					newElement.style[dom_style[0]] = dom_style[1];
				}
				else{
					newElement[arrParameters[0]] = arrParameters[1];
				}
			}
		}

		if(typeof(strContent) == "string"){
			ccDOM.appendChild(strContent, newElement);
		}
		
		return newElement;
	},

	/*
	*	@name: appendChild(objNode, objParentNode)
	*	@version: 1.0
	*	@author: Andre Metzen
	*	@param: objNode => Node Object, String, Array of Node Objects or Strings
	*	@param: objParentNode => Node Object
	*	@return: Integer
	*	@description: Adiciona o "objNode" como ultimo no filho de "objParentNode". Se "objNode" for uma string
	*				  e criada um Text Node e adicionado como ultimo no. Caso "objParentNode" nao seja definido e tomado
	*				  como padrao "document.body"
	*/
	appendChild: function(objNode, objParentNode){
		var i;
		if(typeof(objParentNode) == "undefined"){
			objParentNode = document.body;
		}
		
		if(objNode=="" || objNode == null){
			return true;
		}
		if(objNode instanceof Array){
			for(i=0; i<objNode.length; i++)	{
				ccDOM.appendChild(objNode[i], objParentNode);
			}
		}
		else{
			if(typeof(objNode) == "string")	{
				objParentNode.appendChild(ccDOM.createTextNote(objNode))
			}
			else{
				objParentNode.appendChild(objNode);
			}
		}	
		return objParentNode.childNodes.length;
	},

	/*
	*	@name: removeChild(objNode)
	*	@version: 1.0
	*	@author: Andre Metzen
	*	@param: objNode => Node Object
	*	@return: void
	*	@description: Remove o elemento "objNode"
	*/
	removeChild: function(objNode){
		if(objNode && objNode.parentNode){
			objNode.parentNode.removeChild(objNode);
		}
	},

	/*
	*	@name: addClass(objTarget, strClass)
	*	@version: 1.0
	*	@author: Diego Nunes
	*	@param: objTarget => Node Object
	*	@param: strClass => String
	*	@return: String
	*	@description: Adiciona a class strClass ao objeto objTarget caso ele não possua essa classe
	*/
	addClass: function(objTarget, strClass){
		if(ccDOM.hasClass(objTarget, strClass)){
			return false;
		}  	
		return objTarget.className = ((objTarget.className) ? objTarget.className : '') +' '+ strClass;
	},

	/*
	*	@name: hasClass(objTarget, strClass)
	*	@version: 1.0
	*	@author: Diego Nunes
	*	@param: objTarget => Node Object
	*	@param: strClass => String
	*	@return: Boolean
	*	@description: Verifica se o objTarget já possui a classe strClass
	*/
	hasClass: function(objTarget, strClass){
		var n, i, tToks=objTarget.className.split(' ');
		for (n=tToks.length; n--; ){
			if(tToks[n]==strClass){
				return true;
			}
		}
		return false;
	},

	/*
	*	@name: removeClass(objTarget, strClass)
	*	@version: 1.0
	*	@author: Diego Nunes
	*	@param: objTarget => Node Object
	*	@param: strClass => String
	*	@return: String
	*	@description: Remove a classe strClass de objTarget, se ele possuir
	*/
	removeClass: function(objTarget, strClass){
		if(!objTarget.className){
			return '';
		}		
		var n, i, tRs=[], tToks=objTarget.className.split(' ');
		for(n=tToks.length, i=0; i<n; i++){
			if(tToks[i]!=strClass){
				tRs[tRs.length]=tToks[i];
			}
		}	
		return objTarget.className = (tRs.length ? tRs.join(' ') : '');
	}
}

/*
hasClass2(strClass, objTarget){

	//if you want to find all elements that have a class of test
	//hasClass("test"")
	//If you want to find only the <li> elements that have a class of test
	//hasClass("test","li")
	//if you want to find the first <li> with a class of test
	//hasClass("test","li")[0]
	
	var r = [];
	// Locate the class name (allows for multiple class names)
	var re = new RegExp("(^|\\s)" + strClass + "(\\s|$)");
	// Limit search by type, or look through all elements
	var e = document.getElementsByTagName(objTarget || "*");
	for(var j=0; j<e.length; j++){
		// If the element has the class, add it for return
		if (re.test(e[j])){
				r.push( e[j] );
		}		
	}
	// Return the list of matched elements
	return r;
}
*/

/*
Exemplos de utilização:
appendChild(createElement('hr'), getTags('div')[2]); // Inserir hr dentro da 3ª div do documento ao final do conteúdo
insertBefore(createElement('hr'), getTags('div')[2].firstChild); // Inserir hr dentro da 3ª div do documento antes de qualquer conteúdo
insertBefore(createElement('hr'), getTags('div')[2]); // Inserir hr antes da 3ª div do documento
// Podem tbm ser utilizados com id (mais comum)
appendChild(createElement('hr'), $('container3'));
appendChild(createElement('hr'), $('container3').firstChild);
...
*/