﻿
/*
Engine parsera DOM

*/

/*
 * Funkcja tworząca dokument XML
 * (Rozszerzenie JQuery)
 */

jQuery.createXMLDocument = function( xmlText ) 
{
	
	try //Internet Explorer
	{

	  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
	  xmlDoc.async="false";
	  xmlDoc.loadXML(xmlText);
	  return xmlDoc;
	  
	}
	catch(e) // przeglądarki internetowe
	  {
			
		  	//parser=new DOMParser();
		  	//xmlDoc=parser.parseFromString(xmlText, "text/xml");
		  	//return xmlDoc;
		  	return xmlText;					
	  }
	
	
	return xmlText;
}



//----------------------------------------

/*
 * Klasa elementu DOM
 * level - posiom zagnieżdzenia
 * tag - nazwa elementu
 * xpath - ścieżka do elementu
 * attributes - atrybuty elementu
 */
function DomElement(level, tag, xpath, attributes) 
{
	this.level = level;
	this.tag = tag;
	this.xpath = xpath;
	this.attributes = jQuery.makeArray(attributes);
}

/*
 * Funkcja zamienia XML na tablicę elementów DomElement 
 * 
 */
function CreateDOMLinksTree(xmlDoc)
{
	// tablica wynikowa
	var result = '';
	
	// trzeba dodać swojego roota
	xmlDoc = jQuery.createXMLDocument('<parseroot><searchroot>'+xmlDoc+'</searchroot></parseroot>');
	
		
	$(xmlDoc).find("searchroot").each(function()
	{
		// łączenie tablicy z rekurencyjnymi wynikami
		result += GetChildsLinkList($(this), '', 1);	
		
	});
	
	return result;
}


 

/*
 * Funkcja parsujaca rekurencyjnie DOM do postaci linków
 */
function GetChildsLinkList(node, path, level)
{
	
	var curPath = path;	
	var result = '';
	
	if(level>1)
	{
		curPath += '/' + node.tagName;
		result += '<li>'+CreateDomLink(new DomElement(level, node.tagName, curPath, node.attributes))+'</li>';
	}
	
	
    var children = $(node).children();
    
    //alert(children.length);
    
	if(children != null && children.length >0)
	{
		result += '<ul class="domList" style="margin-left: '+(level*10)+'px;">';
			
		for(var i=0; i< children.length; i++)
		{	
			// pobiera resztę rekurencyjnie
			result += GetChildsLinkList(children[i], curPath, level+1);			
		};
		
		result += '</ul>';
	}

	
	return result;
}


/*
 * Funkcja tworzaca linki
 * 
 */
function CreateDomLink(el)
{
	var html = '<a href="#" onclick="InsertXPath(\''+el.xpath.toLowerCase()+'\'); return false;"> ' + el.tag + '</a>';
	
	if( el.attributes != null && el.attributes.length>0)
	{
		for(var i=0; i<el.attributes.length; i++)
		{	
			// dodatkowe linki do atrybutów
			html += ' [<a href="#" onclick="InsertXPath(\''+el.xpath.toLowerCase()+'@'+el.attributes[i].name+'\'); return false;"> ' + el.attributes[i].name + '</a>]';		
		};	
	}
	
	
	return html;
}

 
 /*
  * Tworzenie edytora HTML
  * 
  */
 
 function initEditor()
 {
	 tinyMCE.init({
		 	mode : "exact",
		    elements : "xslEditor",
			language : "pl",    
			//convert_fonts_to_spans : true,
			theme: "advanced",
			
			// przyciski
			theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
			theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
			theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen, btXSLElement, btXSLPath, btXSLLoop",
			//theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak, btXSLElement, btXSLPath, btXSLLoop",
		    //theme_advanced_buttons3 : "btXSLElement, btXSLLoop",
		    // toolbary
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location : "bottom",
			theme_advanced_resizing : true,


			setup : function(ed) 
			{
			
				// przycisk XSL Elementu
				ed.addButton('btXSLElement', 
						{
							title : 'Wartość XSL',
							image : 'mce_imgs/btn_xsl_element.gif',
							onclick : function() 
								{
									ed.focus();
									ed.selection.setContent(GetElementName($('#xslElPath').val()));
								}
							}
				);
				
				// przycisk XSL relatywnej warości Elementu
				ed.addButton('btXSLPath', 
						{
							title : 'Ścieżka XSL',
							image : 'mce_imgs/btn_xsl_path.gif',
							onclick : function() 
								{
									ed.focus();
									ed.selection.setContent(GetElementPath($('#xslElPath').val()));
								}
							}
				);

				// przycsik XSL Petli
				ed.addButton('btXSLLoop', 
						{
							title : 'Pętla XSL',
							image : 'mce_imgs/btn_xsl_loop.gif',
							onclick : function() 
								{
									ed.focus();
									ed.selection.setContent(GetElementLoop($('#xslElPath').val()));
								}
							}
				);
			}

		});
	 
 }
 

/*
* Funkcja obsługująca klik w drzewie
*/ 
 function InsertXPath(path)
 {
	 //alert(path);
	 $('#xslElPath').val(path);
	 
 }

 
/*
 * Funkcja tworząca wyjściowy XSLT
 * 
 */
 function BuildXSLT(htmlSRC)
 {
   
	var outXSL = '<?xml version="1.0" encoding="utf-8"?>\n';
	outXSL += '<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">\n';
	outXSL += '<xsl:output method="html" encoding="UTF-8" doctype-public="-//W3C//DTD HTML 4.01//EN"/>\n';
	outXSL += '<xsl:template match="/">\n';
	
	outXSL += '<html><head>';
	outXSL += '<meta name="language" content="pl" />';
	outXSL += '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';
	outXSL += '</head><body>';
	
	outXSL += '<!-- *************************   <TRESC> ******************** -->\n';
	outXSL += ReplaceXSLCode(htmlSRC) + '\n';
	outXSL += '<!-- *************************   </TRESC> ******************** -->\n';
	
	outXSL += '</body></html>';
	
	outXSL += '</xsl:template>\n';  
	outXSL += '</xsl:stylesheet>\n';
 
	return outXSL;
 }
 
 
 
 /*
  * Funkcja podmienia nasze znaczniki XSLT na prawdziwy kod
  *  np. [VAL=nazwisko] -> <xsl:value-of select="nazwisko" />
  */ 
 function ReplaceXSLCode(htmlSRC)
 {
	 
	//str = str.replace(/\[b\](.*?)\[\/b\]/ig, "<b>$1</b>");
	 
	// htmlSRC
	 
	// wyrażenie regularne do zamiany VAL
	var valRegex =  /\[VAL=([^\[]*)\]/g;
	var loopRegex = /\[FOR=([^\[]*)\]/g;
	var loopEndRegex = /\[\/FOR\]/g;
	
	// podmiana twardych spacji
	htmlSRC  = htmlSRC.replace(/&nbsp;/g, ' ');
	
	// usuniecie P
	htmlSRC  = htmlSRC.replace(/<p>/g, '');
	htmlSRC  = htmlSRC.replace(/<\/p>/g, '');
	
	// podmiana początku pętli
	htmlSRC  = htmlSRC.replace(loopRegex, '<xsl:for-each select=\"$1\" >');

	// podmiana końca pętli
	htmlSRC  = htmlSRC.replace(loopEndRegex, '</xsl:for-each>');
	
	
	// podmiana wartości
	htmlSRC  = htmlSRC.replace(valRegex, '<xsl:value-of select=\"$1\" />');
	
	
	 
	return htmlSRC; 
 }
 
 
 /* 
  * Funkcje dodatkowych przycisków edytora
  */
 
 
  /// wycina tylko koniec ścieżki (nazwę)
  function GetElementName(xpath)
  {
	  var ret = '[VAL='+ xpath.substring(xpath.lastIndexOf('/')+1, xpath.length) +']';
	  
	  // i jeszcze wyciagniecie atrybutu
	  
	  if(ret.indexOf('@') >=0)
		ret = '[VAL='+ret.substring(ret.indexOf('@'), ret.length);  
		  
	  return ret;
	  
  }
  
  
  // podaje całą ściezkę
  function GetElementPath(xpath)
  {
	 return '[VAL='+ xpath +']'; 
  }
  
  
  // tworzy petlę
  function GetElementLoop(xpath)
  {
	  return '[FOR='+$('#xslElPath').val()+']<br />...<br />[/FOR]';
  }
  
  
 
