//
// TODO - Convert this to a Jitsu App!!!
//


function Tours() {

    this.preamble = function(current, title, subtitle) {
		document.title = "Jitsu Quicktours: " + title;
        docs.mainNav("../", "quicktours");
        document.write('<div id="content">');
        this.toursNav(current);

        pr('<table width="100%">');
        pr('<tr><td valign="baseline"><h1 id="tour_title">'); pr(title); pr('</h1></td>');
        pr('<td valign="baseline"><div id="tour_subtitle">'); pr(subtitle); pr('</div></td></tr></table>');

        pr('<div><br/><table width="100%"><tr><td>');
        flush();
        docs.box('lightblue','small');
        pr('<div class="paddedlight lightblue">');
        pr('<div id="tour_source_tabs">');
        pr('<a href="#" class="tour_bold_tab current" id="show_app" onclick="showApp(); return false;" class="current" >Running App</a> &nbsp; | &nbsp; ');
        pr('<a href="#" class="tour_bold_tab" id="show_source" onclick="showSource(); return false;" class="current" >Source Markup</a> &nbsp; | &nbsp; ');
        pr('<a href="#" class="tour_light_tab" id="show_compiled_html" onclick="showCompiledHtml(); return false;" >Generated HTML</a> &nbsp; | &nbsp; ');
        pr('<a href="#" class="tour_light_tab" id="show_compiled_js" onclick="showCompiledJS(); return false;" >Generated Script</a> &nbsp; | &nbsp; ');
        pr('<a href="#" class="tour_light_tab" id="show_html" onclick="showFinalHtml(); return false;" >Final HTML</a> ');
        pr('</div>');
        flush();
        docs.box('white','small');
        pr('<div class="padded white">');
        pr('<div id="tour_app_container" style="border: 1px solid white;">');
        flush();
    }

    this.description = function(title) {
        pr('</div>');
        pr('<div id="tour_sourcecode_container">');
        pr('<div id="tour_sourcecode"></div>');
        pr('</div>');
        pr('</div>');
        flush();
        docs.endBox();
        pr('</div>');
        flush();
        docs.endBox();
        pr('</td></tr></table><div style="text-align: right">');
        pr('<a href="#" onclick="_INSPECT(); return false;" >&raquo; Open Inspector</a>');
        pr('</div><br/><h2>');
        pr(title ? title : 'Description');
        pr('</h2><div id="tour_notes">');
        flush();
    }
    this.endamble = function() {        
        pr('</div></div></div>'); flush();
        docs.footer();
    }

    this.toursNav = function(current) {
        var menuGroups = [
            {
                title: "Getting Started",
                menuItems: [ 
                    { title: "Hello World", href: "basic_helloworld.html" },
                    { title: "Button", href: "basic_button.html" },
                    { title: "The Inspector", href: "basic_inspector.html" }
                ]
            },
            {
                title: "JSON Data Services",
                menuItems: [ 
                    { title: "Getting Connected", href: "active.html" },
                    { title: "Paged Lists", href: "active_paging.html" },
                    { title: "Editing", href: "active_bookmarks.html" },
                    { title: "Tables", href: "active_tables.html" },
                ]
            },
            {
                title: "Controls",
                menuItems: [ 
                    { title: "List", href: "controls_list.html" },
                    { title: "CardDeck", href: "controls_carddeck.html" },
                    { title: "DockPanel", href: "controls_dockpanel.html" },
                    { title: "Popup", href: "controls_popup.html" },
//                    { title: "Date Picker", href: "controls_datepicker.html" },
                    { title: "RoundedPanel", href: "controls_roundedpanel.html" },
//                    { title: "Auto Suggest", href: "controls_autosuggest.html" }
                    { title: "PropertyGrid", href: "custom_grid.html" },
                    { title: "Slider", href: "custom_slider1.html" },
                    { title: "Form Controls", href: "controls.html" }
                ]
            },
            {
                title: "Control Features",
                menuItems: [ 
                    { title: "The Back Button", href: "controls_backbutton.html" },
                    { title: "Drag and drop", href: "controls_dragdrop.html" },
                    { title: "More Drag Drop", href: "controls_dragdrop2.html" },
                    { title: "Submitters", href: "controls_submitter.html" },
                    { title: "Validation", href: "controls_validation.html" },

                ]
            },
            {
                title: "Data Binding",
                menuItems: [ 
                    { title: "Simple Binding", href: "binding.html" },
                    { title: "Two Way Binding", href: "binding_twoway.html" },
                    { title: "Defining Datasets", href: "binding_datasets.html" },
                    { title: "Relative Binding", href: "binding_relative.html" },
                    { title: "Binding Lists", href: "binding_list.html" },
                    { title: "Master Detail", href: "binding_master.html" },
//                    { title: "Active Binding", href: "binding_active.html" },
                    { title: "Data Snapshots", href: "binding_snapshots.html" }
                ]
            },
            {
                title: "Animation",
                menuItems: [ 
                    { title: "Basic Animation", href: "animator.html" },
                    { title: "Fade Rollover", href: "animator_fade.html" },
                    { title: "Duration and Ease", href: "animator_ease.html" },
                    { title: "Animator Groups", href: "animator_group.html" }
                ]
            },
            {
                title: "Markup Controls",
                menuItems: [ 
                    { title: "Setting Defaults", href: "custom_setup.html" },
                    { title: "Reusable Button", href: "custom_button.html" },
                    { title: "Reusable Panel", href: "custom_panel.html" },
                    { title: "Slider Revisited", href: "custom_slider2.html" },
                ]
            },
            {
                title: "Scripted Controls",
                menuItems: [ 
                    { title: "Lister", href: "custom_lister.html" },
                    { title: "Slideshow", href: "custom_slideshow.html" },
                    { title: "Lookless Controls", href: "custom_clock.html" },
                    { title: "Animated Lister", href: "custom_lister2.html" },
                    { title: "CSS and Script", href: "basic_css.html" }
                ]
            },
            {
                title: "Advanced Binding",
                menuItems: [ 
                    { title: "Converters", href: "expr_converters.html" },
                    { title: "Complex Expressions", href: "expr_complex.html" },
                    { title: "Read only Binding", href: "expr_get.html" }
                ]},
        ];
        
        
        clear();
        pr('<div id="secondarynav">');
        flush();
        docs.box('lightblue','small');
        pr('<div class="padded lightblue">');
        docs.devTabs("../", "quicktours", true);
        pr('<ul>');
        for (var i=0, menuGroup; menuGroup = menuGroups[i]; i++) {
            var isCurrent = false;
            for (var j=0, menu; menu = menuGroup.menuItems[j]; j++) {
                if (menu.href == current) {
                    isCurrent = true;
                    break;
                }
            }
            outputMenuGroup(menuGroup.title, menuGroup.menuItems[0].href, isCurrent);
            if (isCurrent) {
                for (var j=0, menu; menu = menuGroup.menuItems[j]; j++) {
                    outputMenu(menu.title, menu.href, current);
                }
            }
            outputEndMenuGroup();
        }
        pr('</ul>');
        docs.devTabs("../", "quicktours", false);
        pr('</div>');
        flush();
        docs.endBox();
        clear();
        pr('</div>');
        flush();
    }
    
    function outputMenuGroup(title, href, isCurrent) {
        pr('<h3 class="accordian">');
        pr('<a href="'); pr(href); pr('"> <img id="a_expr" src="images/');
        pr(isCurrent ? 'down' : 'right');
        pr('_arrow.gif">');
        pr(title);
        pr('</a></h3>');
        pr('<ul id="g_expr" class="accordian_items">');        
    }
    
    function outputEndMenuGroup() {
         pr('</ul>');
    }

    function outputMenu(title, href, currentHref) {
        pr('<li>');
        pr('<a href="'); pr(href); pr('" '); 
        if (currentHref==href) pr('class="navbar_current"');
        pr('>'); pr(title); pr('</a></li>');
    }
    
}

var tours = new Tours();



// We developed this before the framework, so we don't use
// the framework for this UI. Should switch at some point.

function retrieveData(url, async) {
	var isIE = document.all && window.ActiveXObject && (navigator.userAgent.toLowerCase().indexOf('msie') > -1);
	var myXMLHTTPRequest;
    
	if (isIE) {
		myXMLHTTPRequest = new ActiveXObject('Microsoft.XMLHTTP');
	}
	else
	{
		myXMLHTTPRequest = new XMLHttpRequest();
	}
    
	myXMLHTTPRequest.open('GET', url, async);
	myXMLHTTPRequest.setRequestHeader('Cache-Control', 'no-cache');
	myXMLHTTPRequest.setRequestHeader('Expires', 'Fri, 30 Oct 1998 14:19:41 GMT');
	myXMLHTTPRequest.send(null);
	return myXMLHTTPRequest.responseText;
}
function colorCodeXml(str)
{
    // Trim
    str = str.replace(/^\s+/g, '').replace(/\s+$/g, '');
    // Turn every space into a tab char (later we replace with a hard space)
    str = str.replace(/\t/g, '    ');
    str = str.replace(/ /g, '\t');

    // Turn < and > into &LT; and &GT; (case matters)
    str = str.replace(/\<([^!])/g, '&LT;$1');
    str = str.replace(/([^-])\>/g, '$1&GT;');

    // Handle attribute="value" - make the attribute red and value blue
    str = str.replace(/([a-zA-Z0-9:]+)\=\"([^"]*)"/g, '<font color="red">$1</font><font color="mauve">="$2"</font>');

    // highlight namespaced tags
    str = str.replace(/\&LT\;([a-z]+\:)([a-zA-Z0-9]+)/g, '\&LT\;<span style="font-family:courier new;font-size:90%;color:#c22;">$1</span><font color="maroon">$2</font>');
    str = str.replace(/\&LT\;\/([a-z]+\:)([a-zA-Z0-9]+)/g, '\&LT\;/<span style="font-family:courier new;font-size:90%;color:#c22;">$1</span><font color="maroon">$2</font>');

    // Color tag openers and closers brown                
    str = str.replace(/\&LT\;([a-zA-Z0-9:]+)/g, '&LT;<font color="maroon">$1</font>');
    str = str.replace(/\&LT\;\/([a-zA-Z0-9:]+)/g, '&LT;/<font color="maroon">$1</font>');


    // Comments are green
    str = str.replace(/\<\!--/g, '<font color="green">&lt;!--');
    str = str.replace(/--\>/g, '--&gt;</font>');
                    
    // The < and > characters are blue
    str = str.replace(/\&LT\;/g, '<font color="mauve">&lt;</font>');
    str = str.replace(/\/\&GT\;/g, '<font color="mauve">/&gt;</font>');
    str = str.replace(/\&GT\;/g, '<font color="mauve">&gt;</font>');

    // Turn tabs into nbsp, newlines into li
    str = str.replace(/\t/g, '&nbsp;');
    str = str.replace(/\n/g, '<br/>');
    
    return ('<ol class="source_html"><li><code>' + str + '</code></li></ol>');
}

function colorCodeScript(str)
{
    // Trim
    str = str.replace(/^\s+/g, '').replace(/\s+$/g, '');
    // Turn every space into a tab char (later we replace with a hard space)
    str = str.replace(/\t/g, '    ');
    str = str.replace(/ /g, '\t');

    // Turn < and > into &LT; and &GT; (case matters)
    str = str.replace(/\</g, '&LT;');
    str = str.replace(/\>/g, '&GT;');
    str = str.replace(/\bfunction\t/g, '<font color="blue">function\t</font>');
    str = str.replace(/\bvar\t/g, '<font color="blue">var\t</font>');
    str = str.replace(/\breturn\t/g, '<font color="blue">return\t</font>');
    str = str.replace(/\/\/(.*)/g, '<font color="green">//$1</font>');
    str = str.replace(/\&LT\;/g, '&lt;');
    str = str.replace(/\/\&GT\;/g, '&gt;');

    // Turn tabs into nbsp, newlines into li
    str = str.replace(/\t/g, '&nbsp;');
    str = str.replace(/\n/g, '<br/>');

    return ('<ol class="source_html"><li><code>' + str + '</code></li></ol>');
}

function setClass(elemName, className)
{
    var elem = document.getElementById(elemName);
    elem.setAttribute("class", className);
    elem.setAttribute("className", className);            
}

function showApp()
{
    setAppVisible(true);
    setCurrentTab("show_app");
}
function showSource()
{
    loadSource("markup");
    setAppVisible(false);
    setCurrentTab("show_source");
}
function showCompiledHtml()
{                
    loadSource("html");
    setAppVisible(false);
    setCurrentTab("show_compiled_html");
}            
function showCompiledJS()
{                
    loadSource("js");
    setAppVisible(false);                
    setCurrentTab("show_compiled_js");
}

function showFinalHtml()
{
    setAppVisible(false);

    setCurrentTab("show_html");

    var tempTextArray = new Array(500);
    tempTextArray.push('<html>\n    <body onload="init();">');
    var container = document.getElementById('tour_app_container');
    // Filter out the tours.description() script tag.
    for (var c = container.firstChild; c != null; c = c.nextSibling) {
        if (c.tagName != "SCRIPT") {
            dumpNode(c, tempTextArray, 8);
        }
    } 
    tempTextArray.push('    </body>\n</html>');
    var txt = tempTextArray.join('');
    document.getElementById("tour_sourcecode").innerHTML = '<pre>' + colorCodeXml(txt) + '</pre>';
}   

function setAppVisible(show)
{
    document.getElementById("tour_app_container").style.display = show ? "block" : "none";
    document.getElementById("tour_sourcecode_container").style.display = !show ? "block" : "none";
}

function setCurrentTab(current) {
    var tabs = ["show_app", "show_source","show_compiled_html","show_compiled_js","show_html"];
    for (var i = 0, tab; tab = tabs[i]; i++) {
        var className = (i == 0 || i == 1) ? "tour_bold_tab" : "tour_light_tab";
        if (tabs[i] == current) className += " current";        
        setClass(tabs[i], className);
    }
}

function loadSource(sourceSuffix)
{
    var src = document.getElementById("tour_sourcecode");
    
    var href = document.location.toString();
    var matchResult = href.match(/.*\/([a-z_0-9A-Z]*)\.html/);
    var baseName = matchResult[1];
    
    var text = retrieveData("/jitsu/quicktours/gen/" + baseName + "." + sourceSuffix + ".html", false);
    src.innerHTML = text;   
}

function trimString(str) {
    str = str.replace( /^\s+/g, "" );// strip leading
    str = str.replace( /\s+$/g, "" );// strip trailing
    return str;
}

function spaces(textArray, amount)
{
    for (var i = 0; i < amount; i++) textArray.push(' ');
}

function dumpChildren(node, textArray, indent) {
    for (var c = node.firstChild; c != null; c = c.nextSibling)
        dumpNode(c, textArray, indent);
}

function dumpNode(node, textArray, indent) {
    if (node.tagName == 'HEAD') return;
    if (node.nodeType == 1) { // element
        spaces(textArray, indent);
        textArray.push('<');
        textArray.push(node.tagName.toLowerCase());
        var attrs = node.attributes;
        if (attrs != null && attrs.length != 0) {
        
            for (var i = 0, count = 0; i < attrs.length; i++) {
                if (attrs[i].value == "null" || attrs[i].value == "") continue;
                if (count % 3 == 0 && count != 0) {
                    textArray.push('\n');
                    spaces(textArray, indent + 6);
                }
                count++;
                textArray.push(' ');
                textArray.push(attrs[i].name.toLowerCase());
                var str = attrs[i].value;
                var quot = '"';
                var hasDbl = (str.indexOf('"') != -1);
                if (hasDbl) {
                    str = str.replace(/\"/g, "'");
                }
                textArray.push('=');
                textArray.push(quot);
                textArray.push(str);
                textArray.push(quot);
            }                    
        }
    
        if (node.firstChild != null) {
            textArray.push('>\n');
            dumpChildren(node, textArray, indent + 4);
            spaces(textArray, indent);
            textArray.push('</');
            textArray.push(node.tagName.toLowerCase());
            textArray.push('>\n');                                            
        } else {
            textArray.push('/>\n');                
        }
        return;
    } else if (node.nodeType == 3) {
        var str = trimString(node.nodeValue);
        if (str.length != 0) 
        {
            spaces(textArray, indent);
            textArray.push(node.nodeValue);
            textArray.push('\n');
        }
    }
    dumpChildren(node, textArray, indent);
}
