<mt:setvarblock name="page_title"><__trans phrase="Select a [_1] Style" params="<mt:if name="is_blog"><__trans phrase="Blog"><mt:else><__trans phrase="Website"></mt:if>"></mt:setvarblock>
<mt:setvarblock name="html_head" append="1">
<!-- stylecatcher -->
<link rel="stylesheet" type="text/css" title="Default Layout" href="<mt:var name="plugin_static_uri">templates.css" />

<script type="text/javascript" src="<mt:var name="static_uri">js/tc/mixer.js"></script>
<script type="text/javascript" src="<mt:var name="static_uri">js/tc/mixer/tagmatch.js"></script>
<script type="text/javascript" src="<mt:var name="static_uri">js/tc/mixer/display.js"></script>
<script type="text/javascript" src="<mt:var name="static_uri">js/tc/client.js"></script>

<!-- javascripts for this page -->

<script type="text/javascript">
/* <![CDATA[ */
    var repoImg = "<mt:var name="plugin_static_uri">images/mixed-media.gif";
    var selected;
    var blog_id = '<mt:var name="blog_id" escape="js">';
    var dynamic_blog = <mt:if name="dynamic_blog">true<mt:else>false</mt:if>;
    var mixer;          
    var matchCategory = /^category-/;
    var categories = [];
    var firstCategoryId;
    var repo_urls = {};
    var repos = [];
    var libraries = <mt:var name="style_library" to_json="1">;
    var current_theme = '<mt:var name="current_theme" escape="js">';
    var current_layout = '<mt:var name="current_layout" escape="js">';
    var layout_names = {
        "layout-wtt": "<__trans phrase="3-Columns, Wide, Thin, Thin" escape="js">",
        "layout-twt": "<__trans phrase="3-Columns, Thin, Wide, Thin" escape="js">",
        "layout-ttw": "<__trans phrase="3-Columns, Thin, Thin, Wide" escape="js">",
        "layout-tw": "<__trans phrase="2-Columns, Thin, Wide" escape="js">",
        "layout-wt": "<__trans phrase="2-Columns, Wide, Thin" escape="js">",
        "layout-wm": "<__trans phrase="2-Columns, Wide, Medium" escape="js">",
        "layout-mw": "<__trans phrase="2-Columns, Medium, Wide" escape="js">",
        "layout-w-b": "<__trans phrase="1-Column, Wide, Bottom" escape="js">"
    };

    TC.attachLoadEvent( init );

    function init() {
        initMixer();

<mt:if name="themes_json">
        var data = <mt:var name="themes_json">;
        if (data.categories) {
            for (var i = 0; i < data.categories.length; i++)
                enableCategory(data.categories[i]);
        }
</mt:if>

        initCategories();
        chooseCategory( firstCategoryId );

        if (data.themes) {
            loadThemes(data.themes);
            if (current_theme) {
                mixer.name = current_theme;
                selectDesign();
            } else {
                showDetails();
            }
        }

        <mt:if name="auto_fetch">
        getStyles(null, '<mt:var name="auto_fetch" remove_html="1" encode_js="1">');
        </mt:if>
    }

    function enableCategory(cat) {
        mixer.addTagIndexDisplay('display-'+cat, 1000, 'collection:'+cat);
        var el = getByID('category-' + cat);
        if (el)
            el.style.display = 'block';
    }

    function initMixer() {
        mixer = new TC.Mixer();
        // initialize mixer object
        var display = mixer.addSelectedDisplay( "display-details-content" );
        display.entryProperties['template_set'] = 'Template Set';
        mixer.onselect = selectDesign;
    }

    function initCategories() {
        var element = getByID( "categories" );
        if( !element )
            return;
        
        categories.length = 0;
        var elements = element.childNodes;
        for( var i = 0; i < elements.length; i++ )
        {
            element = elements[ i ];
            var categoryId = element.id;
            if( !categoryId )
                continue;
            
            if( !firstCategoryId ) {
                if (element.style.display != 'none') {
                    firstCategoryId = categoryId;
                }
            }
            
            var displayId = categoryId.replace( matchCategory, "display-" );
            var display = getByID( displayId );

            element.onclick = chooseCategoryClosure( categoryId );
            TC.removeClassName( element, "category-selected" );

            categories[ categoryId ] = {
                "element" : element,
                "display" : display
            };
        }
    }

    function chooseCategoryClosure( categoryId ) {
        var func = function() { return chooseCategory( categoryId ); };
        return func;
    }

    function chooseCategory( categoryId ) {
        var titleElement = getByID( "selected-category-title" );

        for( var id in categories ) {
            var element = categories[ id ].element;
            if (!element) continue;
            var display = categories[ id ].display;

            if( id == categoryId ) {
                var repo_match = element.id.match(/^category-repo-(.+)$/);
                if (repo_match) {
                    var repo_id = repo_match[1];
                    var repo;
                    for (var i = 0; i < libraries.length; i++) {
                        if (libraries[i].key == repo_id) {
                            repo = libraries[i];
                            break;
                        }
                    }
                    if (repo.url && !repo.loaded) {
                        getStyles(repo_id, repo.url);
                    }
                }
                TC.addClassName( element, "category-selected" );
                display.style.display = "block";
                
                if( titleElement )
                    titleElement.innerHTML = trans(element.firstChild.nextSibling.innerHTML);
            }
            else {
                TC.removeClassName( element, "category-selected" );
                if (display) display.style.display = "none";
            }
        }

        // select first theme in category
        mixer.name = '';
        var select_design = getByID("select-design-controls");
        TC.addClassName(select_design, "hidden");
        mixer.display();
        mixer.remix();
    }

    function showDetails() {
        mixer.remix();
    }

    function selectDesign() {
        var apply_button = getByID("apply-button");
        var layout_select = getByID("layout-list");

        var layouts;
        if (mixer.name && mixer.entries[mixer.name])
            layouts = mixer.entries[mixer.name].layouts;
        var layout_list;
        if (layouts) layout_list = layouts.split(/\s*,\s*/);
        if (layouts && layout_list && layout_list.length) {
            layout_select.options.length = 0;
            var selected_layout = 0;
            for (var i = 0; i < layout_list.length; i++) {
                var opt = new Option(layout_names[layout_list[i]] ? layout_names[layout_list[i]] : layout_list[i], layout_list[i]);
                layout_select.options[layout_select.options.length] = opt;
                if (layout_list[i] == current_layout) {
                    selected_layout = i;
                }
            }
            layout_select.selectedIndex = selected_layout;
            layout_select.disabled = false;
        } else {
            layout_select.options.length = 0;
            layout_select.options[0] = new Option("<__trans phrase="None available" escape="js">", "");
            layout_select.disabled = true;
        }
        showDetails();
        var select_design = getByID("select-design-controls");
        TC.removeClassName(select_design, "hidden");
        updateApplyButton();
    }

    function updateApplyButton() {
        var apply_button = getByID("apply-button");
        var layout_select = getByID("layout-list");
        var new_layout;
        if (layout_select && layout_select.selectedIndex != -1) {
            new_layout = layout_select.options[layout_select.selectedIndex].value;
        }
        var current_entry = mixer.entries[mixer.name];
        if ((mixer.name == current_theme) && ((!new_layout || !current_layout) || ((new_layout && current_layout) && (new_layout == current_layout)))) {
            // same theme, same layout. don't allow apply design to be enabled
            apply_button.disabled = true;
            TC.addClassName(apply_button, "disabled");
        } else {
            apply_button.disabled = false;
            TC.removeClassName(apply_button, "disabled");
        }
    }

    function applyDesign() {
        // disable apply button; change text to "Applying..."
        var btn = getByID("apply-button");
        var layout = getByID("layout-list");
        if (layout && layout.selectedIndex != -1) {
            layout = layout.options[layout.selectedIndex].value;
        }

        selected = mixer.name;
        var url = mixer.entries[mixer.name].url;
        var tset = mixer.entries[mixer.name].template_set;

        TC.addClassName(btn, "disabled");
        btn.disabled = true;
        btn.value = "<__trans phrase="Applying..." escape="js">";

        var args = {
            '__mode': 'stylecatcher_apply',
            'url': url,
            'magic_token': '<mt:var name="magic_token">',
            'blog_id': blog_id,
            'name': mixer.name,
            'template_set': tset
        };
        if (layout)
            args['layout'] = layout;
        var client = TC.Client.call({
            'load': designApplied,
            'uri': '<mt:var name="script_url">',
            'method': 'POST',
            'arguments': args
        });
    }

    function designApplied(client, result) {
        var btn = getByID("apply-button");
        btn.value = "<__trans phrase="Apply Design" escape="js">";

        var res;
        try {
            res = eval('(' + result + ')');
        } catch (e) {
        }
        if (res && res.error) {
            showMsg("<p class=\"msg-text\"><__trans phrase="Error applying theme: " escape="js"></p>" + res.error, "theme-applied", "error");
            TC.removeClassName(btn, "disabled");
            btn.disabled = false;
            return;
        }

        var layout = getByID("layout-list");
        var new_layout;
        if (layout && layout.selectedIndex != -1) {
            new_layout = layout.options[layout.selectedIndex].value;
        }
        var entry = mixer.entries[selected];
        if (entry) {
            // make this the new 'current' theme
            var found = false;
            for (var i = 0; i < entry.tags.length; i++) {
                if (entry.tags[i] == 'collection:current')
                    found = true;
            }
            if (!found)
                entry.tags[entry.tags.length] = 'collection:current';
            /* we need to add the blog id of the blog that was
               applied to for this entry */

            found = false;
            if (entry.blogs && entry.blogs.length) {
                for (var i = 0; i < entry.blogs.length; i++) {
                    if (entry.blogs[i] == blog_id)
                        found = true;
                }
            }
            if (!found)
                entry.blogs[entry.blogs.length] = blog_id;

            /* loop through all the 'current' themes and strip
               this blog id from any that don't match the
               selected theme */
            for (var i in mixer.entries) {
                if (i == selected)
                    continue;
                for (var j = 0; j < mixer.entries[i].blogs.length; j++) {
                    if (mixer.entries[i].blogs[j] == blog_id) {
                        mixer.entries[i].blogs.splice(j,1);
                        break;
                    }
                }
                if (mixer.entries[i].blogs.length == 0) {
                    // no longer 'current'
                    for (var j = 0; j < mixer.entries[i].tags.length; j++) {
                        if (mixer.entries[i].tags[j] == 'collection:current') {
                            mixer.entries[i].tags.splice(j,1);
                            break;
                        }
                    }
                }
            }
            mixer.createTagIndexes();
        }

        chooseCategory('category-current');
        current_theme = selected;
        mixer.name = selected;
        var layout_changed = (current_layout && new_layout) && (current_layout != new_layout);
        current_layout = new_layout;
        selectDesign();

        if (layout_changed && (!dynamic_blog)) {
            showMsg("<p class=\"msg-text\"><__trans phrase="The selected theme has been applied, but as you have changed the layout, you will need to republish your blog to apply the new layout." escape="js"></p>", 'theme-applied', "info", "all", blog_id);
        } else {
            showMsg("<p class=\"msg-text\"><__trans phrase="The selected theme has been applied!" escape="js"></p>", 'theme-applied', "info");
        }
    }

    function stylesLoaded(client, styles, repo_id) {
        var btn = getByID("find-button");
        TC.addClassName(TC.elementOrId("loading-styles"), "hidden");
        TC.removeClassName(btn, "hidden");

        var repo_num;
        var cat;

        var data;
        try {
            data = eval('('+styles+')');
        } catch (e) {
            showMsg("<p class=\"msg-text\"><__trans phrase="Error loading themes! -- [_1]" params="ERROR" escape="js"></p>".replace(/ERROR/, styles), "error", "error");
            return;
        }
        if (data.error) {
            showMsg("<p class=\"msg-text\"><__trans phrase="Error loading themes! -- [_1]" params="ERROR" escape="js"></p>".replace(/ERROR/, data.error), "error", "error");
            return;
        }
        log(data.result);
        if (!repo_id) {
            if (data.result.repo) {
                url = data.result.repo['url'];
                if (repo_urls[url] != undefined) {
                    repo_num = repo_urls[url];
                    cat = 'repo_' + repo_num;
                } else {
                    repo_num = repos.length;
                    repo_urls[url] = repo_num;

                    // new repo -- create new
                    // category for it
                    cat = 'repo_' + repo_num;
                    createCategory(cat, data.result.repo['display_name'], url);
                }
                repos[repo_num] = url;
            }
            if (data.result.auto) {
                cat = 'more';
                enableCategory(cat);
            }
            chooseCategory('category-' + cat);
        } else {
            var repo;
            for (var i = 0; i < libraries.length; i++) {
                if (libraries[i].key == repo_id) {
                    repo = libraries[i];
                    break;
                }
            }
            if (repo) {
                repo.loaded = true;
                cat = 'repo-' + repo_id;
                enableCategory(cat);
                chooseCategory('category-' + cat);
            }
        }
        if (data.result.themes)
            loadThemes(data.result.themes, cat);
    }

    function createCategory(cat_name, cat_title, url) {
        // things to create...
        //   #1: new scrollbox under id 'categories'
        /*
                <div class="category" id="category-repo" title="Remote Styles" style="display: none">
                    <img src="<mt:var name="plugin_static_uri">images/mixed-media.gif" alt="" /><span id="repo-name">Remote Styles</span>
                </div>
        */
        var cats = getByID("categories");

        element = document.createElement( "div" );
        element.title = url;
        element.className = "category";
        element.id = "category-" + cat_name;

        var img = document.createElement( "img" );
        img.src = repoImg;
        img.alt = "";
        element.appendChild( img );

        var spn = document.createElement( "span" );
        spn.appendChild( document.createTextNode( cat_title ) );
        element.appendChild( spn );

        cats.appendChild( element );

        //   #2: new div under id templates-wrapper
        /*
            <div class="scrollbox" id="display-repo" style="display: none;"></div>
        */

        var wrapper = getByID("templates-wrapper");

        var div = document.createElement( "div" );
        div.className = "scrollbox";
        div.id = "display-" + cat_name;
        wrapper.appendChild(div);
        element.onclick = chooseCategoryClosure( element.id );

        categories[ element.id ] =
        {
            "element" : element,
            "display" : div
        };

        enableCategory(cat_name);
    }

    function loadThemes(themes, pfx) {
        var names = {};
        for (var i = 0; i < themes.length; i++) {
            var prefix = themes[i]['prefix'];
            if (!prefix) prefix = pfx;
            var name = prefix + ':' + themes[i]['name'];
            if (names[themes[i]['name']]) {
                names[themes[i]['name']]++;
                name += "_" + names[themes[i]['name']];
            } else {
                names[name] = 1;
            }
            themes[i]['name'] = name;
            themes[i].tags[themes[i].tags.length] = "collection:"+prefix;
            if (mixer.entries[name]) {
                // merge in tags
                var existing_tags = mixer.entries[name].tags;
                if (existing_tags && existing_tags.length) {
                    var new_tag_names = {};
                    for (var j in themes[i].tags)
                        new_tag_names[j] = true;
                    for (var j = 0; j < existing_tags.length; j++) {
                        if (!new_tag_names[existing_tags[j]]) {
                            themes[i].tags[themes[i].tags.length] = existing_tags[j];
                        }
                    }
                }
            } else {
                mixer.addEntries(themes[i]);
            }
        }
        mixer.display();
    }

    function downloadStyles() {
        var url;
        if (url = prompt("<__trans phrase="Stylesheet or Repository URL" escape="js">")) {
            getStyles(null, url);
        }
    }

    function getStyles(repo_id, url) {
        var btn = getByID("find-button");
        TC.addClassName(btn, "hidden");
        TC.removeClassName(TC.elementOrId("loading-styles"), "hidden");

        var client = TC.Client.call({
            'load': function(c,s) { stylesLoaded(c,s,repo_id) },
            'uri': '<mt:var name="script_url">',
            'method': 'POST',
            'arguments': {
                '__mode': 'stylecatcher_js',
                'magic_token': '<mt:var name="magic_token">',
                'url': url,
                'blog_id': blog_id
            }
        });
    }
/* ]]> */
</script>
<!-- end stylecatcher script section -->
</mt:setvarblock>
<mt:include name="include/header.tmpl">

<div id="msg-block">
</div>

<div id="wrapper">

<!--
<form method="get" action="<mt:var name="script_url">">
    <strong><__trans phrase="Stylesheet or Repository URL:"></strong>
    <input class="repo-url" style="width:350px;" name="url" id="repo-url" value="<mt:var name="last_theme_url">" />
    <input type="button" id="find-button" value="<__trans phrase="Download Styles">" onclick="getStyles()" />
    <span class="hidden" id="loading-styles">
        <img src="<mt:var name="static_uri">images/indicator.white.gif" height="16" width="16" alt="" />
        <__trans phrase="Loading...">
    </span>
</form>
-->

<p id="status-message" class="message" style="display: none"></p>

<div id="template-picker">
    <div id="categories-wrapper">
        <h2>
            <span id="find-category">
                <a href="javascript:void(0)" id="find-button" onclick="return downloadStyles()" class="icon-right icon-create" title="Download new styles">&nbsp;</a>
                    <span class="hidden" id="loading-styles">
                        <img src="<mt:var name="static_uri">images/indicator.white.gif" height="16" width="16" alt="" />
                    </span>
            </span>

            <__trans phrase="Categories">
        </h2>

        <div class="scrollbox" id="categories">
            <div class="category" id="category-current" title="<__trans phrase="Current theme for your weblog">" style="display: none"><img src="<mt:var name="plugin_static_uri">images/top-rated.gif" alt="Your Current Style" /><span><__trans phrase="Current Style"></span>
            </div>
            <div class="category" id="category-my-designs" title="<__trans phrase="Locally saved themes">" style="display: none"><img src="<mt:var name="plugin_static_uri">images/my-designs.gif" alt="my-designs" /><span><__trans phrase="Saved Styles"></span>
            </div>
            <div class="category" id="category-mt-designs" title="<__trans phrase="Default Styles">" style="display: none"><img src="<mt:var name="plugin_static_uri">images/gear.gif" alt="mt-designs" /><span><__trans phrase="Default Styles"></span>
            </div>
            <div class="category" id="category-more" title="<__trans phrase="Single themes from the web">" style="display: none"><img src="<mt:var name="plugin_static_uri">images/featured.gif" alt="my-designs" /><span><__trans phrase="More Styles"></span>
            </div>
            <mt:loop name="style_library">
            <div class="category" id="category-repo-<mt:var name="key">" title="<mt:var name="description_label" escape="html">"><img src="<mt:var name="plugin_static_uri">images/featured.gif" alt="more-designs" /><span><mt:var name="label" escape="html"></span>
            </div>
            </mt:loop>
        </div>
    </div>

    <div id="templates-wrapper">
        <h2 id="selected-category-title"><__trans phrase="Templates"></h2>
        <div class="scrollbox" id="display-current" style="display: none;"></div>
        <div class="scrollbox" id="display-my-designs" style="display: none;"></div>
        <div class="scrollbox" id="display-mt-designs" style="display: none;"></div>
        <div class="scrollbox" id="display-more" style="display: none;"></div>
        <mt:loop name="style_library">
        <div class="scrollbox" id="display-repo-<mt:var name="key">" style="display: none;"></div>
        </mt:loop>
    </div>

    <div id="details-wrapper">
        <h2><__trans phrase="Selected Design"></h2>
        <div id="display-details">
        <div id="select-design-controls" class="actions-bar">
            <form method="get" action="">
                <p>
                    <label for="layout-list"><__trans phrase="Layout">:</label>
                    <select id="layout-list" onchange="updateApplyButton()">
                    </select>
                </p>

                <span class="button-actions actions">
                <button
                    type="button"
                    accesskey="s"
                    id="apply-button"
                    title="<__trans phrase="Apply Design"> (s)"
                    onclick="applyDesign()"
                    class="apply action primary button"><__trans phrase="Apply Design"></button>
                </span>
            </form>
        </div>

        <div id="display-details-content"></div>


    </div>

</div>

</div>

</div>

<mt:include name="include/footer.tmpl">
