## -*- coding: utf-8 -*-
<%inherit file="/base/base.html"/>
<%def name="title()">
    ${_('Journal')} &middot; ${c.rhodecode_name}
</%def>
<%def name="breadcrumbs()">
    <h5>
    <form id="filter_form">
    <input class="q_filter_box ${'' if c.search_term else 'initial'}" id="j_filter" size="15" type="text" name="filter" value="${c.search_term or _('quick filter...')}"/>
    <span class="tooltip" title="${h.tooltip(h.journal_filter_help())}">?</span>
    <input type='submit' value="${_('filter')}" class="ui-btn" style="padding:0px 2px 0px 2px;margin:0px"/>
    ${_('journal')} - ${ungettext('%s entry', '%s entries', c.journal_pager.item_count) % (c.journal_pager.item_count)}
    </form>
    ${h.end_form()}
    </h5>
</%def>
<%def name="page_nav()">
    ${self.menu('journal')}
</%def>
<%def name="head_extra()">
<link href="${h.url('journal_atom', api_key=c.rhodecode_user.api_key)}" rel="alternate" title="${_('ATOM journal feed')}" type="application/atom+xml" />
<link href="${h.url('journal_rss', api_key=c.rhodecode_user.api_key)}" rel="alternate" title="${_('RSS journal feed')}" type="application/rss+xml" />
</%def>
<%def name="main()">

    <div class="box box-left">
        <!-- box / title -->
        <div class="title">
         ${self.breadcrumbs()}
         <ul class="links">
           <li>
             <span><a id="refresh" href="${h.url('journal')}"><img class="icon" title="${_('Refresh')}" alt="${_('Refresh')}" src="${h.url('/images/icons/arrow_refresh.png')}"/></a></span>
           </li>
           <li>
             <span><a href="${h.url('journal_atom', api_key=c.rhodecode_user.api_key)}"><img class="icon" title="${_('ATOM feed')}" alt="${_('ATOM feed')}" src="${h.url('/images/icons/rss_16.png')}"/></a></span>
           </li>
         </ul>
        </div>
        <div id="journal">${c.journal_data}</div>
    </div>
    <div class="box box-right">
        <!-- box / title -->

        <div class="title">
            <h5>
            <input class="q_filter_box" id="q_filter" size="15" type="text" name="filter" placeholder="${_('quick filter...')}" value="" style="display: none"/>
            <input class="q_filter_box" id="q_filter_watched" size="15" type="text" name="filter" placeholder="${_('quick filter...')}" value="" style="display: none"/>
            </h5>
             <ul class="links" style="color:#DADADA">
               <li>
                 <span><a id="show_watched" class="link-white current" href="#watched">${_('Watched')}</a> </span>
               </li>
               <li>
                 <span><a id="show_my" class="link-white" href="#my">${_('My repos')}</a> </span>
               </li>
             </ul>
        </div>

        <!-- end box / title -->
        <div id="my_container" style="display:none">
            <div class="table yui-skin-sam" id="repos_list_wrap"></div>
            <div id="user-paginator" style="padding: 0px 0px 0px 20px"></div>
        </div>

        <div id="watched_container">
            <div class="table yui-skin-sam" id="watched_repos_list_wrap"></div>
            <div id="watched-user-paginator" style="padding: 0px 0px 0px 20px"></div>
        </div>
    </div>

    <script type="text/javascript">

    YUE.on('j_filter','click',function(){
        var jfilter = YUD.get('j_filter');
        if(YUD.hasClass(jfilter, 'initial')){
            jfilter.value = '';
        }
    });
    var fix_j_filter_width = function(len){
        YUD.setStyle(YUD.get('j_filter'),'width',Math.max(80, len*6.50)+'px');
    }
    YUE.on('j_filter','keyup',function(){
        fix_j_filter_width(YUD.get('j_filter').value.length);
    });
    YUE.on('filter_form','submit',function(e){
        YUE.preventDefault(e)
        var val = YUD.get('j_filter').value;
        window.location = "${url.current(filter='__FILTER__')}".replace('__FILTER__',val);
    });
    fix_j_filter_width(YUD.get('j_filter').value.length);

    YUE.on('refresh','click',function(e){
        ypjax("${h.url.current(filter=c.search_term)}","journal",function(){
            show_more_event();
            tooltip_activate();
            show_changeset_tooltip();
            });
        YUE.preventDefault(e);
    });

    var show_my = function(e){
        YUD.setStyle('watched_container','display','none');
        YUD.setStyle('my_container','display','');
        YUD.setStyle('q_filter','display','');
        YUD.setStyle('q_filter_watched','display','none');

        YUD.addClass('show_my', 'current');
        YUD.removeClass('show_watched','current');

        if(!YUD.hasClass('show_my', 'loaded')){
            table_renderer(${c.data |n});
            YUD.addClass('show_my', 'loaded');
        }
    }
    YUE.on('show_my','click',function(e){
        show_my(e);
    })
    var show_watched = function(e){
        YUD.setStyle('my_container','display','none');
        YUD.setStyle('watched_container','display','');
        YUD.setStyle('q_filter_watched','display','');
        YUD.setStyle('q_filter','display','none');

        YUD.addClass('show_watched', 'current');
        YUD.removeClass('show_my','current');
        if(!YUD.hasClass('show_watched', 'loaded')){
            watched_renderer(${c.watched_data |n});
            YUD.addClass('show_watched', 'loaded');
        }

        return
        var nodes = YUQ('#watched_container .watched_repo a');
        var target = 'q_filter';
        var func = function(node){
            return node.parentNode.parentNode;
        }
        q_filter(target,nodes,func);
    }
    YUE.on('show_watched','click',function(e){
        show_watched(e);
    })
    //init watched
    show_watched();

    var tabs = {
        'watched': show_watched,
        'my': show_my,
    }
    var url = location.href.split('#');
    if (url[1]) {
        //We have a hash
        var tabHash = url[1];
        var func = tabs[tabHash]
        if (func){
            func();
        }
    }
    function watched_renderer(data){
        var myDataSource = new YAHOO.util.DataSource(data);
        myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;

        myDataSource.responseSchema = {
            resultsList: "records",
            fields: [
               {key:"menu"},
               {key:"raw_name"},
               {key:"name"},
               {key:"last_changeset"},
               {key:"action"},
            ]
         };
        myDataSource.doBeforeCallback = function(req,raw,res,cb) {
            // This is the filter function
            var data     = res.results || [],
                filtered = [],
                i,l;

            if (req) {
                req = req.toLowerCase();
                for (i = 0; i<data.length; i++) {
                    var pos = data[i].raw_name.toLowerCase().indexOf(req)
                    if (pos != -1) {
                        filtered.push(data[i]);
                    }
                }
                res.results = filtered;
            }
            return res;
        }
        // main table sorting
        var myColumnDefs = [
            {key:"menu",label:"",sortable:false,className:"quick_repo_menu hidden"},
            {key:"name",label:"${_('Name')}",sortable:true,
                sortOptions: { sortFunction: nameSort }},
            {key:"last_changeset",label:"${_('Tip')}",sortable:true,
                sortOptions: { sortFunction: revisionSort }},
            {key:"action",label:"${_('Action')}",sortable:false},
        ];

        var myDataTable = new YAHOO.widget.DataTable("watched_repos_list_wrap", myColumnDefs, myDataSource,{
          sortedBy:{key:"name",dir:"asc"},
          paginator: YUI_paginator(25, ['watched-user-paginator']),

          MSG_SORTASC:"${_('Click to sort ascending')}",
          MSG_SORTDESC:"${_('Click to sort descending')}",
          MSG_EMPTY:"${_('No records found.')}",
          MSG_ERROR:"${_('Data error.')}",
          MSG_LOADING:"${_('Loading...')}",
        }
        );
        myDataTable.subscribe('postRenderEvent',function(oArgs) {
            tooltip_activate();
            quick_repo_menu();
        });

        var filterTimeout = null;

        updateFilter  = function () {
            // Reset timeout
            filterTimeout = null;

            // Reset sort
            var state = myDataTable.getState();
            state.sortedBy = {key:'name', dir:YAHOO.widget.DataTable.CLASS_ASC};

            // Get filtered data
            myDataSource.sendRequest(YUD.get('q_filter_watched').value,{
                success : myDataTable.onDataReturnInitializeTable,
                failure : myDataTable.onDataReturnInitializeTable,
                scope   : myDataTable,
                argument: state
            });

        };
        YUE.on('q_filter_watched','click',function(){
            if(!YUD.hasClass('q_filter_watched', 'loaded')){
                //TODO: load here full list later to do search within groups
                YUD.addClass('q_filter_watched', 'loaded');
            }
         });

        YUE.on('q_filter_watched','keyup',function (e) {
            clearTimeout(filterTimeout);
            filterTimeout = setTimeout(updateFilter,600);
        });
      }

    function table_renderer(data){
        var myDataSource = new YAHOO.util.DataSource(data);
        myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;

        myDataSource.responseSchema = {
            resultsList: "records",
            fields: [
               {key:"menu"},
               {key:"raw_name"},
               {key:"name"},
               {key:"last_changeset"},
               {key:"action"},
            ]
         };
        myDataSource.doBeforeCallback = function(req,raw,res,cb) {
            // This is the filter function
            var data     = res.results || [],
                filtered = [],
                i,l;

            if (req) {
                req = req.toLowerCase();
                for (i = 0; i<data.length; i++) {
                    var pos = data[i].raw_name.toLowerCase().indexOf(req)
                    if (pos != -1) {
                        filtered.push(data[i]);
                    }
                }
                res.results = filtered;
            }
            return res;
        }
        // main table sorting
        var myColumnDefs = [
            {key:"menu",label:"",sortable:false,className:"quick_repo_menu hidden"},
            {key:"name",label:"${_('Name')}",sortable:true,
                sortOptions: { sortFunction: nameSort }},
            {key:"last_changeset",label:"${_('Tip')}",sortable:true,
                sortOptions: { sortFunction: revisionSort }},
            {key:"action",label:"${_('Action')}",sortable:false},
        ];

        var myDataTable = new YAHOO.widget.DataTable("repos_list_wrap", myColumnDefs, myDataSource,{
          sortedBy:{key:"name",dir:"asc"},
          paginator: YUI_paginator(25, ['user-paginator']),

          MSG_SORTASC:"${_('Click to sort ascending')}",
          MSG_SORTDESC:"${_('Click to sort descending')}",
          MSG_EMPTY:"${_('No records found.')}",
          MSG_ERROR:"${_('Data error.')}",
          MSG_LOADING:"${_('Loading...')}",
        }
        );
        myDataTable.subscribe('postRenderEvent',function(oArgs) {
            tooltip_activate();
            quick_repo_menu();
        });

        var filterTimeout = null;

        updateFilter = function () {
            // Reset timeout
            filterTimeout = null;

            // Reset sort
            var state = myDataTable.getState();
            state.sortedBy = {key:'name', dir:YAHOO.widget.DataTable.CLASS_ASC};

            // Get filtered data
            myDataSource.sendRequest(YUD.get('q_filter').value,{
                success : myDataTable.onDataReturnInitializeTable,
                failure : myDataTable.onDataReturnInitializeTable,
                scope   : myDataTable,
                argument: state
            });

        };
        YUE.on('q_filter','click',function(){
            if(!YUD.hasClass('q_filter', 'loaded')){
                //TODO: load here full list later to do search within groups
                YUD.addClass('q_filter', 'loaded');
            }
         });

        YUE.on('q_filter','keyup',function (e) {
            clearTimeout(filterTimeout);
            filterTimeout = setTimeout(updateFilter,600);
        });

        if(YUD.get('q_filter').value) {
            updateFilter();
        }
    }

    </script>
</%def>
