var oLayoutTemplates = null;
var oTextAreaHtml = null;
var oTextAreaInput = null;
var oDivResult = null;
var oMainForm = null;
var oDivHtmlSource = null;
var oDivInputCode = null;
var oDivResultOutput = null;
var oBtnResult = null;
var oBtnHtmlSource = null;
var oBtnInputCode = null;
var oActiveTabWindow = null;
var oQuotedIdentifierOn = null;

var urlHandler = "_handler.php";
var msgErrorProcessingRequest = "Error during the request processing .";
var msgScriptTooLarge = "Script larger than 10K cannot be processed.";
var msgNoScriptToReformat = "No script to process.";
var msgNoErrorsFoound = "No errors found.";
	
	
function initialize()
{
	var r = {"suceeded":true,"templates":["Default Layout Template","Mastering Oracle SQL","SQL Server Books Online Style (small caps)","SQL Server Books Online Style","The Guru's Guide to Transact-SQL","Ubitsoft Favorite 1 (small caps)","Ubitsoft Favorite 1","Ubitsoft Favorite 2 (small caps)","Ubitsoft Favorite 2"]};;
	var templates = null;
	if (r && r.suceeded){
		templates = r.templates;
	}
	var layoutTemplatesList = $('LayoutTemplates');
	for(var i=0;i<templates.length;i++)
	{
		
		layoutTemplatesList[i] = new Option(templates[i],templates[i]);
	}
	if (templates.length>0) layoutTemplatesList[0].selected="selected";
	
	 oLayoutTemplates = $('LayoutTemplates');
	 oTextAreaHtml = $('taHtml');
	 oMainForm = $('mainForm');
	 oTextAreaInput = $('taInput');
	 oDivResult = $('divResult');
	 oDivHtmlSource = $('divHtmlSource');
	 oDivInputCode = $('divInputCode');
	 oDivResultOutput = $('divResultOutput');
	 oBtnResult = $('btnResult');
	 oBtnHtmlSource = $('btnHtmlSource');
	 oBtnInputCode = $('btnInputCode');
	 oActiveTabWindow = oTextAreaInput;
	 oQuotedIdentifierOn= $('QuotedIdentifierOn');
	 
	 oDivResultOutput.select = function() { 
	 SelectText(oDivResultOutput);
	 };
	 
	 
	 // Register global responders that will occur on all AJAX requests 
Ajax.Responders.register
    ({   
        onCreate: function(){ $('loadingMessage').show(); oMainForm.disable();  },   
        onComplete: function(){ $('loadingMessage').hide();  oMainForm.enable(); } 
    });
};


function btnReformat_onclick() {
    CommonAsyncRequestCall('reformat',OnSuccess,OnFailure);
}
function btnValidate_onclick() {
    CommonAsyncRequestCall('validate',OnSuccessValidate,OnFailure);
}
function btnHighlight_onclick() {
    CommonAsyncRequestCall('highlight',OnSuccess,OnFailure);
}

function AsyncRequestCall( commandName, targetText, layoutTemplateName, htmlStyleValue,quotedIdentifierValue, onSuccessHandler, onFailureHandler)
{
        if (!Validate()) return;
    					  
        var handlerUrl = urlHandler;
        
          oTextAreaHtml.value = '';
          oDivResultOutput.innerText = '';
		  oDivResultOutput.className='code';
        for (i=0;i<document.forms[0].HtmlStyle.length;i++) {
            if (document.forms[0].HtmlStyle[i].checked) {
                htmlStyleValue = document.forms[0].HtmlStyle[i].value;
            }
        }

        var request =  new Ajax.Request(handlerUrl, {   
        method: 'post',   
        parameters: {Command: commandName, 
                     Text: targetText,
                     HtmlStyle: htmlStyleValue,
                     LayoutTemplate: layoutTemplateName,
                     QuotedIdentifier: quotedIdentifierValue} ,
        onSuccess:onSuccessHandler,  
        onFailure: onFailureHandler
        }); 
        request = null;
}

function CommonAsyncRequestCall( commandName, onSuccessHandler, onFailureHandler)
{
        var htmlStyleValue = 0;
        var layoutTemplateName = oLayoutTemplates.value;
        var quotedIdentifierValue = "0";
		if (oQuotedIdentifierOn.checked) 
				quotedIdentifierValue = "1";
		
        
        var text =  oTextAreaInput.value;
        
        for (i=0;i<document.forms[0].HtmlStyle.length;i++) {
            if (document.forms[0].HtmlStyle[i].checked) {
                htmlStyleValue = document.forms[0].HtmlStyle[i].value;
            }
        }

        AsyncRequestCall( commandName, text, layoutTemplateName, htmlStyleValue,quotedIdentifierValue, onSuccessHandler, onFailureHandler)
}

function OnSuccess(transport)
{

    oMainForm.enable();
    oDivResult.show();
    var result = transport.responseText.evalJSON();
    if (result.suceeded)
    {
        oTextAreaHtml.value = result.output;
       // oDivResultOutput.innerHTML = result.output;
	    oDivResultOutput.innerHTML = result.output;
		oDivResultOutput.className='code';
		showResult();
		
    }
    else{
        if (result.errors){
            var errorsHtml = '';
            for (i=0;i<result.errors.length;i++) {
                errorsHtml += result.errors[i] +'<br/>';
            }
             oDivResultOutput.innerHTML = errorsHtml;
			 oDivResultOutput.className='code errors';
			 showResult();
         }
    }
};
function OnFailure()
{ 

   oMainForm.enable();
    oDivResultOutput.innerText = msgErrorProcessingRequest;

	
	showResult();
};

function OnSuccessValidate(transport)
{
    oMainForm.enable();
    oDivResult.show();
    var result = transport.responseText.evalJSON();
      
    if (result.suceeded)
    {
    
        oTextAreaHtml.value = '';
        oDivResultOutput.innerText = msgNoErrorsFoound;
		oDivResultOutput.className='code errors';
		showResult();
		
    }
    else{
        if (result.errors){
            var errorsHtml = '';
            for (i=0;i<result.errors.length;i++) {
                errorsHtml += result.errors[i] +'<br/>';
            }
             oDivResultOutput.innerHTML = errorsHtml;
			 oDivResultOutput.className='code errors';
			showResult();
         }
    }
};

function Validate()
{   
    var valid =  true;
    var text =  oTextAreaInput.value;
    if (text.length > 10*1024)
    {
        oDivResultOutput.innerText = msgScriptTooLarge;
		oDivResultOutput.className='code errors';
        valid = false;
    }
    else
    {
        if (text.length == 0)
        {
            oDivResultOutput.innerText = msgNoScriptToReformat;
			oDivResultOutput.className='code errors';
            valid = false;
        }
        
    }
    showResult();
    return valid;
}

function showHtmlSource()
{
    oDivHtmlSource.show();
	oDivResult.hide();
    oDivInputCode.hide();
	oBtnResult.className='button';
    oBtnHtmlSource.className='button selected';
    oBtnInputCode.className='button';
	oActiveTabWindow = oTextAreaHtml;
    
}
function showInputCode()
{

	oDivHtmlSource.hide();
	oDivResult.hide();
    oDivInputCode.show();
	oBtnResult.className='button';
    oBtnHtmlSource.className='button';
    oBtnInputCode.className='button selected';
	oActiveTabWindow = oTextAreaInput;
}
function showResult()
{
	oDivResult.show();
    oDivHtmlSource.hide();
    oDivInputCode.hide();
    oBtnResult.className='button selected';
	oBtnHtmlSource.className='button';
    oBtnInputCode.className='button';
	oActiveTabWindow = oDivResultOutput;
}

function SelectText(element){
	var range = null;
	if (element)
	{
			if (document.selection) {
			 range = document.body.createTextRange();
			 range.moveToElementText(element);
			 range.setEndPoint("EndToEnd",range);
			 range.select(); 
			} else {
			 var selection = window.getSelection();
			 range = document.createRange();
			 range.setStartBefore(element);
			 range.setEndAfter(element);
			 selection.addRange(range);
			}
	}
}