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 oDivErrors = null;
var oDivErrorsOutput = null;

var urlHandler = "_handler.php";
var msgErrorProcessingRequest = "Error during the request processing .";
var msgScriptTooLarge = "Script larger than 20K cannot be processed.";
var msgNoScriptToReformat = "No script to process.";
var msgNoErrorsFoound = "No errors found.";

var funcOnCreateRequest = function() { jQuery('#loadingMessage').show(); oMainForm.attr('disabled', 'disabled'); }
var funcOnCompleteRequest = function() { jQuery('#loadingMessage').hide(); oMainForm.removeAttr('disabled'); }

var initializationDone = false;
function InitializePage() {

    //debugger;

    if (initializationDone) return;
    
	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 = jQuery('#LayoutTemplates');
     layoutTemplatesList[0].options.length = 0; 

	 for(var i=0;i<templates.length;i++)
	 {
		var option = new Option(templates[i],templates[i]);
		option.text = templates[i];
		option.value = templates[i];
		option.innerText = templates[i];
	    layoutTemplatesList.append(option); 
	 }
	 if (templates.length>0) layoutTemplatesList[0].selected="selected";

	 oLayoutTemplates = layoutTemplatesList;
	 oTextAreaHtml = jQuery('#taHtml');
	 oMainForm = jQuery('#mainForm');
	 oPostForm = jQuery('#postForm');
	 oTextAreaInput = jQuery('#taInput');


	 
	 oDivResult = jQuery('#divResult');
	 oDivHtmlSource = jQuery('#divHtmlSource');
	 oDivInputCode = jQuery('#divInputCode');
	 oDivResultOutput = jQuery('#divResultOutput');
	 oBtnResult = jQuery('#btnResult');
	 oBtnHtmlSource = jQuery('#btnHtmlSource');
	 oBtnInputCode = jQuery('#btnInputCode');
	 oActiveTabWindow = oTextAreaInput;
	 oQuotedIdentifierOn= jQuery('#QuotedIdentifierOn');
	 oDivErrors = jQuery('#divErrors');
	 oDivErrorsOutput = jQuery('#divErrorsOutput');
	 oDivResultOutput.select = function() { 
	    SelectText(oDivResultOutput);
	 };
	 
	 
// Register global responders that will occur on all AJAX requests 
//Ajax.Responders.register
//    ({
//        onCreate: funcOnCreateRequest,
//        onComplete: funcOnCompleteRequest
//    });

    initializationDone = true;
};



function btnReformat_onclick() {
    if (!ValidateInput()) return;
    CommonAsyncRequestCall('reformat', OnSuccess, OnFailure);
    try {
        pageTracker._trackPageview('/products/t-sql-beautifier/reformat.php');
    }
    catch (err) { }
}
function btnValidate_onclick() {
    if (!ValidateInput()) return;
    CommonAsyncRequestCall('validate', OnSuccessValidate, OnFailure);
    try {
        pageTracker._trackPageview('/products/t-sql-beautifier/validate.php');
    }
    catch (err) { }
}

function btnHighlight_onclick() {
    if (!ValidateInput()) return;
    CommonAsyncRequestCall('highlight', OnSuccess, OnFailure);
    try {
        pageTracker._trackPageview('/products/t-sql-beautifier/highlight.php');
    }
    catch (err) { }
}

function btnGotoAnalyzer_onclick() {

    try {
        oMainForm[0].method = "post";
        oMainForm[0].action = "/products/t-sql-analyzer/index.php";
        oMainForm[0].submit();
    }
    catch (err) { }
}


function AsyncRequestCall( commandName, targetText, layoutTemplateName, htmlStyleValue,quotedIdentifierValue, onSuccessHandler, onFailureHandler)
{
        if (!ValidateInput()) return;
    					  
        var handlerUrl = urlHandler;
        
          oTextAreaHtml[0].value = '';
          oDivResultOutput[0].innerText = '';
		  oDivResultOutput[0].className='code';
		  
		  var htmlStylrRadioButtons = jQuery("input[name='HtmlStyle']:radio");
		  for (i = 0; i < htmlStylrRadioButtons.length; i++) {
            if (htmlStylrRadioButtons[i].checked) {
                htmlStyleValue = htmlStylrRadioButtons[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
//    });

    var request = jQuery.ajax({
        url: urlHandler,
        type: "post",
        cache: false,
        success: onSuccessHandler,
        error: onFailureHandler,
        beforeSend: funcOnCreateRequest,
        complete: funcOnCompleteRequest,
        dataType: "json",
        data: { Command: commandName,
            Text: targetText,
            HtmlStyle: htmlStyleValue,
            LayoutTemplate: layoutTemplateName,
            QuotedIdentifier: quotedIdentifierValue
        }
    });
        request = null;
}

function CommonAsyncRequestCall( commandName, onSuccessHandler, onFailureHandler)
{
        var htmlStyleValue = 0;
        var layoutTemplateName = oLayoutTemplates.val();
        var quotedIdentifierValue = "0";
		if (oQuotedIdentifierOn.checked) 
				quotedIdentifierValue = "1";
		
        
        var text =  oTextAreaInput.val();

          var htmlStylrRadioButtons = jQuery("input[name='HtmlStyle']:radio");
        for (i = 0; i < htmlStylrRadioButtons.length; i++) {
            if (htmlStylrRadioButtons[i].checked) {
                htmlStyleValue = htmlStylrRadioButtons[i].value;
            }
        }

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

function OnSuccess(data, textStatus, jqXHR) {

    oMainForm.removeAttr('disabled');
    oDivResult.show();
    var result = data;
    if (result.suceeded) {
        oTextAreaHtml[0].value = result.output;
        oDivResultOutput[0].innerHTML = result.output;
        oDivResultOutput[0].className = 'code';
        ShowResult();

    }
    else {
        if (result.errors) {
            var errorsHtml = GetErrorsTableHTML(result.errors);
            oDivResultOutput[0].innerHTML = errorsHtml;
            oDivResultOutput[0].className = 'code errors';
            ShowResult();
        }
    }
}

function GetErrorsTableHTML(errors) {

    var errorsHtml = '';
    if (!errors) return '';
    if (errors.length > 0) {

        var errorsCount = 0, warningsCount = 0; infoCount = 0;
        errorsHtml = '<table>';
        for (i = 0; i < errors.length; i++) {

            var errorClassName = "analysis-result-error";
            switch (errors[i].type) {
                case "Error":
                    errorClassName = "analysis-result-error";
                    errorsCount++;
                    break;
                case "Warning":
                    errorClassName = "analysis-result-warning";
                    warningsCount++;
                    break;
                case "Info":
                    errorClassName = "analysis-result-info";
                    infoCount++;
                    break;
            }
            errorsHtml += '<td class="' + errorClassName + '">&nbsp;</td><td style="text-align:left;"><a href="javascript:void(0);" onclick="HighlightRange(oTextAreaInput,' + errors[i].line + ',' + errors[i].column + ',' + errors[i].length + ');">' + errors[i].message + ' (' + errors[i].line + ',' + errors[i].column + ')</a></td></tr>';
        }
        errorsHtml += "</table>"
        errorsHtml += "<br/>";
    }
    else {
        errorsHtml = "No rule violations were found."
    }
    return errorsHtml;
}


function OnFailure(data, textStatus, jqXHR) {

    oMainForm.removeAttr('disabled');
    oDivResultOutput[0].innerText = msgErrorProcessingRequest;
    ShowResult();
}

function OnSuccessValidate(data, textStatus, jqXHR) {

    oMainForm.removeAttr('disabled');
    oDivResult.show();
    var result = data;

    if (result.suceeded) {

        oTextAreaHtml.value = '';
        oDivResultOutput[0].innerText = msgNoErrorsFoound;
        oDivResultOutput[0].className = 'code errors';
        ShowResult();

    }
    else {
        if (result.errors) {
            var errorsHtml = GetErrorsTableHTML(result.errors);
            oDivResultOutput[0].innerHTML = errorsHtml;
            oDivResultOutput[0].className = 'code errors';
            ShowResult();
        }
    }
}

function ValidateInput() {
    var valid = true;
    var text = oTextAreaInput.val();
    if (text.length > 20 * 1024) {
        oDivResultOutput[0].innerText = msgScriptTooLarge;
        oDivResultOutput[0].className = 'code errors';
        valid = false;
    }
    else {
        if (text.length == 0) {
            oDivResultOutput[0].innerText = msgNoScriptToReformat;
            oDivResultOutput[0].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);
	    }
	}
}


function GetTextAreaLines(textArea) {
    var lines;
    var text = textArea.value;

    if (document.all) { // IE
        lines = text.split('\r\n');
    }
    else { //Mozilla
        lines = text.split('\n');
    }
    return lines;
}

function HighlightRange(textArea, lineNumber, columnOffset, length) {
    ShowInputCode();
    var element = textArea;
    var lines = GetTextAreaLines(element);
    var startIndex = 0;
    for (var i = 0; i < lineNumber - 1; i++) {
        startIndex += lines[i].length;
    }
    startIndex += columnOffset;
    startIndex += lineNumber - 1;

    SelectTextRange(element, startIndex, startIndex + length, lineNumber, columnOffset);
    element.focus();
}

function SelectTextRange(element, startCharNo, endCharNo, lineNumber, columnOffset) {
    var range = null;
    if (element) {
        element.focus();

        if (element.createTextRange) {
            var r = element.createTextRange();
            r.collapse(true);
            r.moveEnd('character', endCharNo);
            r.moveStart('character', startCharNo);
            r.select();
        }
        else
            if (element.selectionStart) {

            var lineHeight = 14;

            element.scrollTop = lineHeight * (lineNumber - 1);
            element.scrollLeft = 7 * columnOffset;
            element.selectionStart = startCharNo;
            element.selectionEnd = endCharNo;

        }
        else {

            var selection = window.getSelection();
            range = document.createRange();
            range.setStartBefore(element);
            range.setStart(element, startCharNo);
            range.setEnd(element, endCharNo);
            selection.removeAllRanges();
            selection.addRange(range);

        }
    }
}
