/* Minification failed. Returning unminified contents.
(548,11-12): run-time warning JS1005: Expected '(': {
: error : Value cannot be null.
Parameter name: key
 */
/**
* vkBeautify - javascript plugin to pretty-print or minify text in XML, JSON, CSS and SQL formats.
*  
* Version - 0.99.00.beta 
* Copyright (c) 2012 Vadim Kiryukhin
* vkiryukhin @ gmail.com
* http://www.eslinstructor.net/vkbeautify/
* 
* Dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
*
*   Pretty print
*
*        vkbeautify.xml(text [,indent_pattern]);
*        vkbeautify.json(text [,indent_pattern]);
*        vkbeautify.css(text [,indent_pattern]);
*        vkbeautify.sql(text [,indent_pattern]);
*
*        @text - String; text to beatufy;
*        @indent_pattern - Integer | String;
*                Integer:  number of white spaces;
*                String:   character string to visualize indentation ( can also be a set of white spaces )
*   Minify
*
*        vkbeautify.xmlmin(text [,preserve_comments]);
*        vkbeautify.jsonmin(text);
*        vkbeautify.cssmin(text [,preserve_comments]);
*        vkbeautify.sqlmin(text);
*
*        @text - String; text to minify;
*        @preserve_comments - Bool; [optional];
*                Set this flag to true to prevent removing comments from @text ( minxml and mincss functions only. )
*
*   Examples:
*        vkbeautify.xml(text); // pretty print XML
*        vkbeautify.json(text, 4 ); // pretty print JSON
*        vkbeautify.css(text, '. . . .'); // pretty print CSS
*        vkbeautify.sql(text, '----'); // pretty print SQL
*
*        vkbeautify.xmlmin(text, true);// minify XML, preserve comments
*        vkbeautify.jsonmin(text);// minify JSON
*        vkbeautify.cssmin(text);// minify CSS, remove comments ( default )
*        vkbeautify.sqlmin(text);// minify SQL
*
*/

(function() {

function createShiftArr(step) {

	var space = '    ';
	
	if ( isNaN(parseInt(step)) ) {  // argument is string
		space = step;
	} else { // argument is integer
		switch(step) {
			case 1: space = ' '; break;
			case 2: space = '  '; break;
			case 3: space = '   '; break;
			case 4: space = '    '; break;
			case 5: space = '     '; break;
			case 6: space = '      '; break;
			case 7: space = '       '; break;
			case 8: space = '        '; break;
			case 9: space = '         '; break;
			case 10: space = '          '; break;
			case 11: space = '           '; break;
			case 12: space = '            '; break;
		}
	}

	var shift = ['\n']; // array of shifts
	for(ix=0;ix<100;ix++){
		shift.push(shift[ix]+space); 
	}
	return shift;
}

function vkbeautify(){
	this.step = '    '; // 4 spaces
	this.shift = createShiftArr(this.step);
};

vkbeautify.prototype.xml = function(text,step) {

	var ar = text.replace(/>\s{0,}</g,"><")
				 .replace(/</g,"~::~<")
				 .replace(/\s*xmlns\:/g,"~::~xmlns:")
				 .replace(/\s*xmlns\=/g,"~::~xmlns=")
				 .split('~::~'),
		len = ar.length,
		inComment = false,
		deep = 0,
		str = '',
		ix = 0,
		shift = step ? createShiftArr(step) : this.shift;

		for(ix=0;ix<len;ix++) {
			// start comment or <![CDATA[...]]> or <!DOCTYPE //
			if(ar[ix].search(/<!/) > -1) { 
				str += shift[deep]+ar[ix];
				inComment = true; 
				// end comment  or <![CDATA[...]]> //
				if(ar[ix].search(/-->/) > -1 || ar[ix].search(/\]>/) > -1 || ar[ix].search(/!DOCTYPE/) > -1 ) { 
					inComment = false; 
				}
			} else 
			// end comment  or <![CDATA[...]]> //
			if(ar[ix].search(/-->/) > -1 || ar[ix].search(/\]>/) > -1) { 
				str += ar[ix];
				inComment = false; 
			} else 
			// <elm></elm> //
			if( /^<\w/.exec(ar[ix-1]) && /^<\/\w/.exec(ar[ix]) &&
				/^<[\w:\-\.\,]+/.exec(ar[ix-1]) == /^<\/[\w:\-\.\,]+/.exec(ar[ix])[0].replace('/','')) { 
				str += ar[ix];
				if(!inComment) deep--;
			} else
			 // <elm> //
			if(ar[ix].search(/<\w/) > -1 && ar[ix].search(/<\//) == -1 && ar[ix].search(/\/>/) == -1 ) {
				str = !inComment ? str += shift[deep++]+ar[ix] : str += ar[ix];
			} else 
			 // <elm>...</elm> //
			if(ar[ix].search(/<\w/) > -1 && ar[ix].search(/<\//) > -1) {
				str = !inComment ? str += shift[deep]+ar[ix] : str += ar[ix];
			} else 
			// </elm> //
			if(ar[ix].search(/<\//) > -1) { 
				str = !inComment ? str += shift[--deep]+ar[ix] : str += ar[ix];
			} else 
			// <elm/> //
			if(ar[ix].search(/\/>/) > -1 ) { 
				str = !inComment ? str += shift[deep]+ar[ix] : str += ar[ix];
			} else 
			// <? xml ... ?> //
			if(ar[ix].search(/<\?/) > -1) { 
				str += shift[deep]+ar[ix];
			} else 
			// xmlns //
			if( ar[ix].search(/xmlns\:/) > -1  || ar[ix].search(/xmlns\=/) > -1) { 
				str += shift[deep]+ar[ix];
			} 
			
			else {
				str += ar[ix];
			}
		}
		
	return  (str[0] == '\n') ? str.slice(1) : str;
}

vkbeautify.prototype.json = function(text,step) {

	var step = step ? step : this.step;
	
	if (typeof JSON === 'undefined' ) return text; 
	
	if ( typeof text === "string" ) return JSON.stringify(JSON.parse(text), null, step);
	if ( typeof text === "object" ) return JSON.stringify(text, null, step);
		
	return text; // text is not string nor object
}

vkbeautify.prototype.css = function(text, step) {

	var ar = text.replace(/\s{1,}/g,' ')
				.replace(/\{/g,"{~::~")
				.replace(/\}/g,"~::~}~::~")
				.replace(/\;/g,";~::~")
				.replace(/\/\*/g,"~::~/*")
				.replace(/\*\//g,"*/~::~")
				.replace(/~::~\s{0,}~::~/g,"~::~")
				.split('~::~'),
		len = ar.length,
		deep = 0,
		str = '',
		ix = 0,
		shift = step ? createShiftArr(step) : this.shift;
		
		for(ix=0;ix<len;ix++) {

			if( /\{/.exec(ar[ix]))  { 
				str += shift[deep++]+ar[ix];
			} else 
			if( /\}/.exec(ar[ix]))  { 
				str += shift[--deep]+ar[ix];
			} else
			if( /\*\\/.exec(ar[ix]))  { 
				str += shift[deep]+ar[ix];
			}
			else {
				str += shift[deep]+ar[ix];
			}
		}
		return str.replace(/^\n{1,}/,'');
}

//----------------------------------------------------------------------------

function isSubquery(str, parenthesisLevel) {
	return  parenthesisLevel - (str.replace(/\(/g,'').length - str.replace(/\)/g,'').length )
}

function split_sql(str, tab) {

	return str.replace(/\s{1,}/g," ")

				.replace(/ AND /ig,"~::~"+tab+tab+"AND ")
				.replace(/ BETWEEN /ig,"~::~"+tab+"BETWEEN ")
				.replace(/ CASE /ig,"~::~"+tab+"CASE ")
				.replace(/ ELSE /ig,"~::~"+tab+"ELSE ")
				.replace(/ END /ig,"~::~"+tab+"END ")
				.replace(/ FROM /ig,"~::~FROM ")
				.replace(/ GROUP\s{1,}BY/ig,"~::~GROUP BY ")
				.replace(/ HAVING /ig,"~::~HAVING ")
				//.replace(/ SET /ig," SET~::~")
				.replace(/ IN /ig," IN ")
				
				.replace(/ JOIN /ig,"~::~JOIN ")
				.replace(/ CROSS~::~{1,}JOIN /ig,"~::~CROSS JOIN ")
				.replace(/ INNER~::~{1,}JOIN /ig,"~::~INNER JOIN ")
				.replace(/ LEFT~::~{1,}JOIN /ig,"~::~LEFT JOIN ")
				.replace(/ RIGHT~::~{1,}JOIN /ig,"~::~RIGHT JOIN ")
				
				.replace(/ ON /ig,"~::~"+tab+"ON ")
				.replace(/ OR /ig,"~::~"+tab+tab+"OR ")
				.replace(/ ORDER\s{1,}BY/ig,"~::~ORDER BY ")
				.replace(/ OVER /ig,"~::~"+tab+"OVER ")

				.replace(/\(\s{0,}SELECT /ig,"~::~(SELECT ")
				.replace(/\)\s{0,}SELECT /ig,")~::~SELECT ")
				
				.replace(/ THEN /ig," THEN~::~"+tab+"")
				.replace(/ UNION /ig,"~::~UNION~::~")
				.replace(/ USING /ig,"~::~USING ")
				.replace(/ WHEN /ig,"~::~"+tab+"WHEN ")
				.replace(/ WHERE /ig,"~::~WHERE ")
				.replace(/ WITH /ig,"~::~WITH ")
				
				//.replace(/\,\s{0,}\(/ig,",~::~( ")
				//.replace(/\,/ig,",~::~"+tab+tab+"")

				.replace(/ ALL /ig," ALL ")
				.replace(/ AS /ig," AS ")
				.replace(/ ASC /ig," ASC ")	
				.replace(/ DESC /ig," DESC ")	
				.replace(/ DISTINCT /ig," DISTINCT ")
				.replace(/ EXISTS /ig," EXISTS ")
				.replace(/ NOT /ig," NOT ")
				.replace(/ NULL /ig," NULL ")
				.replace(/ LIKE /ig," LIKE ")
				.replace(/\s{0,}SELECT /ig,"SELECT ")
				.replace(/\s{0,}UPDATE /ig,"UPDATE ")
				.replace(/ SET /ig," SET ")
							
				.replace(/~::~{1,}/g,"~::~")
				.split('~::~');
}

vkbeautify.prototype.sql = function(text,step) {

	var ar_by_quote = text.replace(/\s{1,}/g," ")
							.replace(/\'/ig,"~::~\'")
							.split('~::~'),
		len = ar_by_quote.length,
		ar = [],
		deep = 0,
		tab = this.step,//+this.step,
		inComment = true,
		inQuote = false,
		parenthesisLevel = 0,
		str = '',
		ix = 0,
		shift = step ? createShiftArr(step) : this.shift;;

		for(ix=0;ix<len;ix++) {
			if(ix%2) {
				ar = ar.concat(ar_by_quote[ix]);
			} else {
				ar = ar.concat(split_sql(ar_by_quote[ix], tab) );
			}
		}
		
		len = ar.length;
		for(ix=0;ix<len;ix++) {
			
			parenthesisLevel = isSubquery(ar[ix], parenthesisLevel);
			
			if( /\s{0,}\s{0,}SELECT\s{0,}/.exec(ar[ix]))  { 
				ar[ix] = ar[ix].replace(/\,/g,",\n"+tab+tab+"")
			} 
			
			if( /\s{0,}\s{0,}SET\s{0,}/.exec(ar[ix]))  { 
				ar[ix] = ar[ix].replace(/\,/g,",\n"+tab+tab+"")
			} 
			
			if( /\s{0,}\(\s{0,}SELECT\s{0,}/.exec(ar[ix]))  { 
				deep++;
				str += shift[deep]+ar[ix];
			} else 
			if( /\'/.exec(ar[ix]) )  { 
				if(parenthesisLevel<1 && deep) {
					deep--;
				}
				str += ar[ix];
			}
			else  { 
				str += shift[deep]+ar[ix];
				if(parenthesisLevel<1 && deep) {
					deep--;
				}
			} 
			var junk = 0;
		}

		str = str.replace(/^\n{1,}/,'').replace(/\n{1,}/g,"\n");
		return str;
}


vkbeautify.prototype.xmlmin = function(text, preserveComments) {

	var str = preserveComments ? text
							   : text.replace(/\<![ \r\n\t]*(--([^\-]|[\r\n]|-[^\-])*--[ \r\n\t]*)\>/g,"")
									 .replace(/[ \r\n\t]{1,}xmlns/g, ' xmlns');
	return  str.replace(/>\s{0,}</g,"><"); 
}

vkbeautify.prototype.jsonmin = function(text) {

	if (typeof JSON === 'undefined' ) return text; 
	
	return JSON.stringify(JSON.parse(text), null, 0); 
				
}

vkbeautify.prototype.cssmin = function(text, preserveComments) {
	
	var str = preserveComments ? text
							   : text.replace(/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+\//g,"") ;

	return str.replace(/\s{1,}/g,' ')
			  .replace(/\{\s{1,}/g,"{")
			  .replace(/\}\s{1,}/g,"}")
			  .replace(/\;\s{1,}/g,";")
			  .replace(/\/\*\s{1,}/g,"/*")
			  .replace(/\*\/\s{1,}/g,"*/");
}

vkbeautify.prototype.sqlmin = function(text) {
	return text.replace(/\s{1,}/g," ").replace(/\s{1,}\(/,"(").replace(/\s{1,}\)/,")");
}

window.vkbeautify = new vkbeautify();

})();

;var input, output;

function HtmlBeautifier() {
    //alert(editor.session.getValue);
    //alert(EditorValue());
    input = EditorValue();
    if (looks_like_html(input)) {
        output = html_beautify(input, getOptions());
        //output = html_beautify(input);
        //$("#output").val(output);

    }
    else {
    }
    //            else {
    //                if ($('#detect-packers').prop('checked')) {
    //                    source = unpacker_filter(source);
    //                }
    //                output = js_beautify(source, opts);
    //            }
    Print();
}

function JSBeautifier() {
    input = EditorValue();

    if (looks_like_html(input))
        output = html_beautify(input, getOptions());
    else {
        //if ($('#detect-packers').prop('checked'))
        //    input = unpacker_filter(input);

        output = js_beautify(input, getOptions());

    }
    Print();
}

function getOptions() {
    var opts = {};

    opts.indent_size = $('#tabsize').val();
    opts.indent_char = parseInt(opts.indent_size, 10) === 1 ? '\t' : ' ';
    opts.max_preserve_newlines = $('#max-preserve-newlines').val();
    opts.preserve_newlines = opts.max_preserve_newlines !== "-1";
    opts.wrap_line_length = $('#wrap-line-length').val();
    opts.brace_style = $('#brace-style').val() + ($('#brace-preserve-inline').prop('checked') ? ",preserve-inline" : "");
    opts.indent_scripts = $('#indent-scripts').val();


    opts.end_with_newline = $('#end-with-newline').prop('checked');
    opts.e4x = $('#e4x').prop('checked');
    opts.comma_first = $('#comma-first').prop('checked');

    //brace-preserve-inline
    opts.keep_array_indentation = $('#keep-array-indentation').prop('checked');
    opts.break_chained_methods = $('#break-chained-methods').prop('checked');
    opts.space_before_conditional = $('#space-before-conditional').prop('checked');
    opts.unescape_strings = $('#unescape-strings').prop('checked');
    opts.jslint_happy = $('#jslint-happy').prop('checked');
    opts.indent_inner_html = $('#indent-inner-html').prop('checked');

    return opts;
}

function JSDeobfuscator() {
    input = EditorValue();
    input = unpacker_filter(input);
    output = js_beautify(input);
    Print();
}

function unpacker_filter(source) {
    var trailing_comments = '',
                comment = '',
                unpacked = '',
                found = false;

    // cut trailing comments
    do {
        found = false;
        if (/^\s*\/\*/.test(source)) {
            found = true;
            comment = source.substr(0, source.indexOf('*/') + 2);
            source = source.substr(comment.length).replace(/^\s+/, '');
            trailing_comments += comment + "\n";
        } else if (/^\s*\/\//.test(source)) {
            found = true;
            comment = source.match(/^\s*\/\/.*/)[0];
            source = source.substr(comment.length).replace(/^\s+/, '');
            trailing_comments += comment + "\n";
        }
    } while (found);

    var unpackers = [P_A_C_K_E_R, Urlencoded, JavascriptObfuscator, MyObfuscate];
    for (var i = 0; i < unpackers.length; i++) {
        if (unpackers[i].detect(source)) {
            unpacked = unpackers[i].unpack(source);
            if (unpacked != source) {
                source = unpacker_filter(unpacked);
            }
        }
    }

    return trailing_comments + source;
}

function JSMinifier() {
    input = EditorValue();
    var model = { HtmlInput: input };

    $.ajax({
        type: "POST",
        url: rootUrl + "WebTool/JSMinify",
        contentType: "application/json",
        data: JSON.stringify({ webTool: model }),
        success: function (resp) {
            output = resp.HtmlOutput;
            Print();
        }
    });
}

function JSObfuscator() {
    input = EditorValue();
    var model = { HtmlInput: input };

    $.ajax({
        type: "POST",
        url: rootUrl + "WebTool/JSObfuscator",
        contentType: "application/json",
        data: JSON.stringify({ webTool: model }),
        success: function (resp) {
            output = resp.HtmlOutput;
            Print();
        }
    });
}

function XSDGenerator() {
    input = EditorValue();
    var model = { HtmlInput: input };

    $.ajax({
        type: "POST",
        url: rootUrl + "CodeConverter/XSDSchema",
        contentType: "application/json",
        data: JSON.stringify({ xml: input }),
        success: function (xsd) {
            output = xsd;
            Print();
        }
    });
}

$(document).ready(function () {
    $('body').on('keyup', '#textIndent', function () {
        if ($("#textIndent").val().length > 0 && !isNaN(parseInt($("#textIndent").val())))
            $("#indentPattern").val('');
    });

    $('body').on('keyup', '#indentPattern', function () {
        if ($("#indentPattern").val().length > 0)
            $("#textIndent").val('');
    });
});

function XMLBeautifier() { beautify('XML'); Print(); }
function JSONBeautifier() { beautify('JSON'); Print(); }
function CSSBeautifier() { beautify('CSS'); Print(); }
function SQLBeautifier() { beautify('SQL'); Print(); }

function HtmlMinifier() { minify('XML'); Print(); }
function XMLMinifier() { minify('XML'); Print(); }
function JSONMinifier() { minify('JSON'); Print(); }
function CSSMinifier() { minify('CSS'); Print(); }
function SQLMinifier() { minify('SQL'); Print(); }

function getvkBeautifyOptions() {
    var opt;

    try {
        if ($("#indentPattern").val().length > 0)
            opt = $("#indentPattern").val();
        else if ($("#textIndent").val() && !isNaN($("#textIndent").val()))
            opt = parseInt($("#textIndent").val());
        else
            opt = 4;
    }
    catch {

    }

    return opt;
}


function beautify(mode) {

    input = EditorValue();

    var opt = getvkBeautifyOptions();

    switch (mode) {
        case 'XML':
            output = vkbeautify.xml(input, opt);
            break;
        case 'JSON':
            try {
                var result = jsonlint.parse(input);

                if (result) {
                    output = vkbeautify.json(input, opt);
                }
            } catch (e) {
                output = e.message;
            }
            break;
        case 'CSS':
            output = vkbeautify.css(input, opt);
            break;
        case 'SQL':
            output = vkbeautify.sql(input, opt);
            break;
    }
    //countChars();
}

function minify(mode) {
    input = EditorValue();

    var opt = $("#preserveComments").is(':checked');

    switch (mode) {
        case 'XML':
            output = vkbeautify.xmlmin(input, opt);
            break;
        case 'JSON':
            output = vkbeautify.jsonmin(input);
            break;
        case 'CSS':
            output = vkbeautify.cssmin(input, opt);
            break;
        case 'SQL':
            output = vkbeautify.sqlmin(input);
            break;
    }
    //countChars();
}

function countChars() {

    //document.getElementById('count').value = document.getElementById('ta').value.length;

}

//CSV
function CSVToJSON() {
    input = EditorValue();
    output = CSV2JSON(input);
    output = vkbeautify.json(output);
    Print();
}

function CSVToHTML() {
    input = EditorValue();
    output = csv2html(input);
    Print();
}

function CSVToMultilineData() {
    input = EditorValue();
    output = csv2multiline(input);
    Print();
}

//modify c-b
function CSVToXML() {
    input = EditorValue();
    var jsn = CSV2JSON(input);
    output = json2xml(JSON.parse(jsn));
    Print();
}

function CSVToYAML() {
    input = EditorValue();
    input = CSV2JSON(input);
    output = json2yaml(JSON.parse(input));
    Print();
}

//modify c-b
function CSVToSQL() {
    input = EditorValue();
    sql = csv2sql(input, "u");
    SQLFormatter(sql, function (sqloutput) {
        output = sqloutput;
        Print();
    });
}

function CSVToEXCEL() {
    input = EditorValue();
    json2excel(input);
}

function CSVToPDF() {
    input = EditorValue();
    var jsn = CSV2JSON(input);
    json2pdf(jsonobj2array(JSON.parse(jsn)));
}

function CSVToTSV() {
    input = EditorValue();
    output = csv2tsv(input);
    Print();
}

//JSON
function JSONToXML() {
    try {
        input = EditorValue();
        output = json2xml(JSON.parse(input));
    } catch (e) {
        output = e.toString();
    }
    Print();
}

function JSONToCSV() {
    try {
        input = EditorValue();
        output = json2csv(JSON.parse(input));
    } catch (e) {
        output = e.toString();
    }
    Print();
}
function JSONToYAML() {
    input = EditorValue();
    output = json2yaml(JSON.parse(input));
    Print();
}

function JSONToCSHARP() {
    input = EditorValue();
    //var model = { HtmlInput: input };

    $.ajax({
        type: "POST",
        url: rootUrl + "CodeConverter/JSONToCSHARP",
        contentType: "application/json",
        data: JSON.stringify({ json: input }),
        success: function (csharp) {
            output = csharp;
            Print();
        }
    });
}

function JSONToTSV() {
    try {
        input = EditorValue();
        input = json2csv(JSON.parse(input));
        output = csv2tsv(input);
    } catch (e) {
        output = e.toString();
    }
    Print();
}

function JSONToExcel() {
    try {
        input = EditorValue();
        json2excel(json2csv(JSON.parse(input)));
        //output = csv2tsv(input);
    } catch (e) {
        output = e.toString();
    }
    Print();
}

function JSONToPdf() {
    try {
        input = EditorValue();
        input = jsonobj2array(JSON.parse(input));
        json2pdf(input);
        //output = csv2tsv(input);
    } catch (e) {
        output = e.toString();
    }
    Print();
}

function JSONSort() {
    try {
        input = EditorValue();
        output = sort(input, { sortArray: $("#sortArray").is(':checked') });
        output = output[0] ? output[1] : "Invalid JSON object."
    } catch (e) {
        output = e.toString();
    }
    Print();
}

function JSONDiff() {
    jdd.compare(iEditor.getValue(), oEditor.getValue());
    Analytics();
}

//XML
function XMLToJSON() {

    //var xml = editorAce.getValue();

    input = EditorValue();
    output = xml2json(input);
    Print();
}

function XMLToYAML() {

    //var xml = editorAce.getValue();

    input = EditorValue();
    var jsn = xml2json(input);
    output = json2yaml(JSON.parse(jsn));
    Print();
}

//XML TO CSV
function XMLToCSV() {
    var input = EditorValue();
    var jsn = xml2json(input);
    output = json2csv(JSON.parse(jsn));
    Print();
}

function XMLToTSV() {
    input = EditorValue();
    var jsn = xml2json(input);
    var csv = json2csv(JSON.parse(jsn));
    output = csv2tsv(csv);
    Print();
}

function XMLToExcel() {

    var input = EditorValue();
    var jsn = xml2json(input);
    output = json2csv(JSON.parse(jsn));
    json2excel(output);
}

function XMLToPdf() {
    try {
        input = EditorValue();
        var jsn = xml2json(input);

        input = jsonobj2array(JSON.parse(jsn));
        json2pdf(input);

        //json2pdf(JSON.parse(jsn));
    } catch (e) {
        output = e.toString();
    }
    Print();
}

$(document).ready(function () {

    
    $("#specificAttributes").click(function () {
        XMLSortAttributes();
        //if ($(this).is(":checked")) {
        //    $.each($("#xmlAttributes input[type='checkbox']:checked"), function () {
        //        attributes.push($(this).val());
        //    });
        //}
        //else {
        //    attributes = [];
        //}
    });

});

function XMLSort() {
    input = EditorValue();

    var attributes = [];
    $.each($("#xmlAttributes input[type='checkbox']:checked"), function () {
        attributes.push($(this).val());
    });
    var model = { XMLContent: input, SortAttributes: $("#sortAttributes").is(':checked'), SortByTagName: $("#tagName").is(':checked'), SortBySpecificAttributes: $("#specificAttributes").is(':checked'), AttributesToSort: attributes }; //AttributesToSort - array of attributes to sort.

    //XMLSortAttributes(); todo:

    $.ajax({
        type: "POST",
        url: rootUrl + "CodeConverter/XMLSort",
        contentType: "application/json",
        data: JSON.stringify(model),
        success: function (xml) {
            output = xml;
            Print();
        }
    });
}

function XMLSortAttributes() {
    input = EditorValue();
    var attributes = [];
    $.ajax({
        type: "POST",
        url: rootUrl + "CodeConverter/XMLSortAttributes",
        contentType: "application/json",
        data: JSON.stringify({ xml: input }),
        success: function (attributes) {
            if (attributes && attributes.length > 0) {
                $('.attr-val').html('');
                attributes.forEach(function (val) {
                    $('.attr-val').append('<div class="checkbox"><label><input type="checkbox" value="' + val + '">' + val + '</label></div>');
                });                
            }
        }
    });
}

//YAMLToJSON
function YAMLToJSON() {
    input = EditorValue();
    output = yaml2json(input);
    Print();
}

//YAMLToXML
function YAMLToXML() {
    input = EditorValue();
    var jsn = yaml2json(input);
    output = json2xml(JSON.parse(jsn));
    Print();
}
//YAMLToCSV
function YAMLToCSV() {
    input = EditorValue();
    var jsn = yaml2json(input);
    output = json2csv(JSON.parse(jsn));
    Print();
}

//SQL
function SQLToJSON() {
    input = EditorValue()
    input = sql2json(input.trim());
    output = vkbeautify.json(input);
    Print();
}
function SQLToHTML() {
    input = EditorValue()
    output = sql2html(input.trim());
    Print();
}
function SQLToXML() {
    input = EditorValue()
    var jsn = sql2json(input.trim());
    output = json2xml(jsn);
    Print();
}
function SQLToYAML() {
    input = EditorValue()
    var jsn = sql2json(input.trim());
    output = json2yaml(jsn);
    Print();
}
function SQLToCSV() {
    input = EditorValue()
    var jsn = sql2json(input.trim());
    output = json2csv(jsn);
    Print();
}
function SQLToTSV() {
    input = EditorValue();
    var jsn = sql2json(input.trim());
    input = json2csv(jsn);
    output = csv2tsv(output);
    Print();
}

function SQLToEXCEL() {
    input = EditorValue()
    var jsn = sql2json(input.trim());
    input = json2csv(jsn);
    json2excel(input);
}

function SQLToPDF() {
    input = EditorValue()
    var jsn = sql2json(input.trim());
    input = json2csv(jsn);
    json2pdf(jsonobj2array(JSON.parse(jsn)));
    Print();
}

//Html
function HTMLToCSV() {
    input = EditorValue();
    if (isTableExist(input, true)) {
        output = html2csv(input);
        Print();
    } 
}

function HTMLToJSON() {
    input = EditorValue();
    if (isTableExist(input, true)) {
        var csv = html2csv(input);
        if (csv && csv.length > 0) {
            var csv = html2csv(input);
            output = CSV2JSON(csv);
            output = vkbeautify.json(output);
            Print();
        }
    }
}
function HTMLToXML() {
    input = EditorValue();
    if (isTableExist(input, true)) {
        var csv = html2csv(input);
        if (csv && csv.length > 0) {
            var csv = html2csv(input);
            var jsn = CSV2JSON(csv);
            output = json2xml(JSON.parse(jsn));
            Print();
        }
    }
}
function HTMLToYAML() {
    input = EditorValue();
    if (isTableExist(input, true)) {
        var csv = html2csv(input);
        if (csv && csv.length > 0) {
            var jsn = CSV2JSON(csv);
            output = json2yaml(JSON.parse(jsn));
            Print();
        }
    }
}
function HTMLToEXCEL() {
    input = EditorValue();
    if (isTableExist(input, true)) {
        html2excel(input);
    }
//    var csv = html2csv(input);

//    if (csv == null)
//        return;

//    var csvParser = new SimpleExcel.Parser.HTML()
//    // write an XLSX file            
//    var xlsxWriter = new SimpleExcel.Writer.XLSX();
//    var xlsxSheet = new SimpleExcel.Sheet();
//    var Cell = SimpleExcel.Cell;
//    xlsxSheet.setRecord([
//                [new Cell('ID', 'TEXT'), new Cell('Nama', 'TEXT'), new Cell('Kode Wilayah', 'TEXT')],
//                [new Cell(1, 'NUMBER'), new Cell('Kab. Bogor', 'TEXT'), new Cell(1, 'NUMBER')],
//                [new Cell(2, 'NUMBER'), new Cell('Kab. Cianjur', 'TEXT'), new Cell(1, 'NUMBER')],
//                [new Cell(3, 'NUMBER'), new Cell('Kab. Sukabumi', 'TEXT'), new Cell(1, 'NUMBER')],
//                [new Cell(4, 'NUMBER'), new Cell('Kab. Tasikmalaya', 'TEXT'), new Cell(2, 'NUMBER')]
//            ]);

//    var records = new Array();
//    var rows = csv.split("\n");


//    if (rows != null && rows.length > 0) {
//        for (var i = 0; i <= rows.length; i++) {
//            var row = rows[i].split(",");
//            var rowRecord = new Array();
//            for (var j = 0; j <= rows.length; j++) {
//                rowRecord.push(new Cell(row[0], 'TEXT'));
//            }
//            records.push(rowRecord);
//        }

//        xlsxSheet.setRecord(records);
//        xlsxWriter.insertSheet(xlsxSheet);
//        // export when button clicked
//        xlsxWriter.saveFile(); // pop! ("Save As" dialog appears)
//    }
}

function HTMLToPHP() {
    input = EditorValue();
    output = html2php(input);
    Print();
}
function HTMLToTSV() {
    input = EditorValue();
    if (isTableExist(input, true)) {
        output = html2csv(input);
        output = csv2tsv(output);
        Print();
    }
}

function SQLFormatter(sqlText, handleData) {
    var fsql;
    $.ajax({
        type: "Get",
        url: rootUrl + "Php/SqlFormat.php",
        //contentType: "application/json",
        data: { sql: sqlText },
        success: function (resp) {
            handleData(resp);
        },
        error: function (e) {
            handleData(sqlText);
        }
    });
}

//TSV
//function tsvTojson(isReturn) {
//    var input = editorAce.getValue();
//    if (input.trim().length == 0) {
//        return false;
//    }
//    var info = input.replace(/['"]/g, ''),
//        lines = info.split('\n'),
//        firstLine = lines.shift().split('\t'),
//        json = [];

//    $.each(lines, function (index, item) {
//        var lineItem = item.split('\t'),
//            jsonLineEntry = {};

//        $.each(lineItem, function (index, item) {
//            jsonLineEntry[firstLine[index].replace("\r", '')] = removeQuotes(item);
//        });
//        json.push(jsonLineEntry);

//    });

//    if (isReturn == undefined) {
//        editorResult.setValue(vkbeautify.json(json));
//        return false;
//    }
//    return json;
//}

function removeQuotes(string) {
    string = string.replace(/(['"])/g, "\\$1");
    if (!isNaN(string)) {
        string = parseFloat(string);
    }
    return string;
}

function addQuotes(value) {
    if (isNaN(value)) {
        return '"' + value + '"';
    }
    return value;
};

//TSV
function TSVToCSV() {
    input = EditorValue();
    output = tsv2csv(input);
    Print();
}

function TSVToXML() {
    input = EditorValue();
    input = tsv2csv(input);
    var jsn = CSV2JSON(input);
    output = json2xml(JSON.parse(jsn));
    Print();
}

function TSVToJSON() {
    input = EditorValue();
    input = tsv2csv(input);
    var jsn = CSV2JSON(input);
    output = vkbeautify.json(jsn);
    Print();
}

function TSVToHTML() {
    input = EditorValue();
    input = tsv2csv(input);
    output = csv2html(input);
    Print();
}

function TSVToYAML() {
    input = EditorValue();
    input = tsv2csv(input);
    var jsn = CSV2JSON(input);
    input = vkbeautify.json(jsn);
    output = json2yaml(JSON.parse(input));
    Print();
}

function TSVToEXCEL() {
    input = EditorValue();
    input = tsv2csv(input);
    json2excel(input);
}

function TSVToPDF() {
    input = EditorValue();
    input = tsv2csv(input);
    var jsn = CSV2JSON(input);
    json2pdf(jsonobj2array(JSON.parse(jsn)));
}

function EditorValue() {
    return iEditor.getValue();
}

function Print() {
    //Util.set("#output", output);
    //Util.setEditor(oeditor, output);
    fillEditor(oEditor, output);
    Analytics();
}

function Download() {
    if (output != null && output.length > 0)
        SaveFile(output, "code");
}

;