
//  Implement filter controller
$(function(){
    $.hotkeys.add('f', {type: 'keydown', propagate: true},$.hotkeys.delegate(
            function(e){
                $('a#lnkApplyFilter').trigger('click');
            }

            ));
    var isOpen=false;
    var statusChosen=null;

    function onSaveFilterChecked(){
        $('#saveOldFilterPanel').slideToggle();
        return false;
    }

    $('a#saveOldFilter').bind('click',onSaveFilterChecked);
    $('input#cancelSaveFilter').bind('click',onSaveFilterChecked);


    function onFilterNameChanged(){
        if($(this).val().length==0){
            $('input#btnApplyFilter').attr('disabled',true);
        }else{
            $('input#btnApplyFilter').attr('disabled','');
        }
    }

    $('input#fldFilterName').bind('keyup',onFilterNameChanged);
    //  Inner Class :   Filter Item
    var clone=$('div.ClonableFilter').clone()[0];

    function onApplyFilterClicked(){
        if(!isOpen){
            $('div.FilterList').html('');
            $('input#fldFilterName').val('');
            onAddFilterClicked();

            $(this).parent().addClass('current');
            $('div#iFilterPanelDialog').slideDown(function(){
                isOpen=true;
            });

        }
    }

    function onCancelClicked(){
        $('div#iFilterPanelDialog').slideUp(function(){
            isOpen=false;
            statusChosen=null;
            $('a#lnkApplyFilter').parent().removeClass('current');
        });
        return false;
    }



    function onAddFilterClicked(){
        var newClone=$(clone).clone()[0];

        if(statusChosen!=null){
            $("option[value='qStatus']",newClone).attr('disabled','true');
        }

        $(newClone).removeClass('hide');

        $('div.FilterList').append($(newClone));

        function onRemoveClicked(){
            $(newClone).remove();
            if(statusChosen==newClone){
                $('div.ClonableFilter option.toHide').attr('disabled','');
                statusChosen=null;
            }
        }

        $('a#iRemoveFilter',newClone).bind('click',onRemoveClicked);

        //  Configure dropdown
        function onDropdownChanged(){
            if($(this).val()=='qStatus'){
                statusChosen=newClone;
                $('div.ClonableFilter option.toHide').attr('disabled','true');
            }else{
                //  Rmove hide from all dropdfownds
                if(statusChosen==newClone){
                    $('div.ClonableFilter option.toHide').attr('disabled','');
                }
            }

            var fields=$('span#'+$(this).val(),'div#templateFilterParams').clone()[0];

            //  If project was selected then
            if($(this).val()=='qProject'){
                function onChange(){
                    var select=$('select',fields)[0];
                    var si=$(select).val();

                    if(si!=-1){
                        //  @todo - Add code for more/less action and hide show below!
                        if($('span.ParamField a#actLess',newClone).hasClass('hide')){
                            $('span.ParamField a#actMore',newClone).removeClass('hide');
                        }

                        //  Do AJAX Magic
                        ajaxCheckList('/api/projects/'+si+'/areas',$("span.ParamField div.bonus dl.area dd",newClone)[0],'qArea','area');
                        ajaxCheckList('/api/projects/'+si+'/versions?type=fixfor',$("span.ParamField div.bonus dl.fixed_for dd",newClone)[0],'qFixFor','version',{"id":"-1","name":"Not set"});
                        ajaxCheckList('/api/projects/'+si+'/versions',$("span.ParamField div.bonus dl.found_in dd",newClone)[0],'qAffected','version',{"id":"-1","name":"Not set"});
                        ajaxCheckList('/api/projects/'+si+'/issue-types',$("span.ParamField div.bonus dl.type dd",newClone)[0],'qType','issueType');
                        ajaxCheckList('/api/projects/'+si+'/resolutions',$("span.ParamField div.bonus dl.resolution dd",newClone)[0],'qResolution','resolution');

                    }else{
                        $('span.ParamField a#actMore',newClone).addClass('hide');
                        $('span.ParamField a#actLess',newClone).addClass('hide');
                        $('span.ParamField div.bonus',newClone).addClass('hide');
                    }
                }
                $("select[name='qProject']",fields).bind('change',onChange);
            }

            $('span.ParamField',newClone).html(fields);

            function showMore(){
                $(this).addClass('hide');
                $('span.ParamField div.bonus',newClone).removeClass('hide');
                $('span.ParamField a#actLess',newClone).removeClass('hide');

            }
            $('span.ParamField a#actMore',newClone).bind('click',showMore);

            function showLess(){
                $(this).addClass('hide');
                $('span.ParamField div.bonus',newClone).addClass('hide');
                $('span.ParamField a#actMore',newClone).removeClass('hide');

            }
            $('span.ParamField a#actLess',newClone).bind('click',showLess);

            $('span.ParamField span input.hasDatepicker').removeClass('hasDatepicker');

            //  Bind behaviours to them
            //alert("KJ");
            //alert($('span.ParamField span input.DateField',newClone)[0]);


            

            $('span.ParamField span input.DateField',newClone).datepicker({clickInput:true});
            $('span.ParamField span input.DateFieldLowerThan',newClone).datepicker({clickInput:true,maxDate: new Date()});
            $('span.ParamField span input.DateFieldGreaterThan',newClone).datepicker({clickInput:true,minDate: new Date()});


        }
        $('select',newClone).bind('change',onDropdownChanged);
    }

    function onApplyClicked(){
        var frm=$('form#frmFilterResults')[0];
        var com="";
        //  Clear the form fields from the form
        $(frm).html(' ');

        //  Get all fields in the filter list
        var fields=$('div#FilterPanel span.ParamField select,div#FilterPanel span.ParamField input');


        function getField(name,include){
            var field=$("input[name='"+name+"']",frm)[0];


            if(field==null && include==true){
                field=$('<input type="text" name="'+name+'" value=""/>');
                $(frm).append(field);
                com="";
            }

            return field;
        }
        //  For each query field in the filter list
        $(fields).each(function(i,n){
            //  Get the fields name
            var fieldName=$(n).attr('name');
            var _include=false;
            //  Check wether we should include this field
            if($(n).attr('type')=="checkbox"){
                if($(n).attr('checked')==true){
                    _include=true;
                }
            }else{
                if($(n).val()!='-1'){
                    _include=true;

                }
            }


            //  Get the field
            com=",";
            var field=getField(fieldName,_include);

            //  Else it already exists so append the new value to the fields existing values

            if(_include){
                $(field).val($(field).val()+com+$(n).val());

            }

        });


        //  Append name of filter to form
        $(frm).append($('input#fldFilterName').clone());

        //  Submit the form
        $(frm).submit();
        return false;
    }



    $('a#lnkCancelApplyFilter').bind('click',onCancelClicked);
    $('a#lnkApplyFilter').bind('click',onApplyFilterClicked);
    $('a#lnkAddFilter').bind('click',onAddFilterClicked);
    $('a#lnkAddFilter').bind('keydapress',onAddFilterClicked);
    $('input#btnApplyFilter').bind('click',onApplyClicked);
    $('input#btnSaveFilter').bind('click',onApplyClicked);

});


$(function(){

    //  Issue Items
        $.each($('table#issueList tbody tr'),function(i,n){
            new IssueItemComponent(n);
        })

        function IssueItemComponent(n){
            var _n=n;
            var _h=$(_n);
            var _hoverFlag=false;
            var _moving=false;
            var _hovering=false;
            var _canUpdate=false;
            var isAdded=false;
            var _event=null;
            var _hasBeenClicked=false;
            var href=$('td.colID a',_n)[0];
            var td=$('td.colID ',_n)[0];
            var title=$('td.Title',_n).html();


            function setCanUpdate(){
                _canUpdate=true;
            }

            function onCallback(query,url,cb){
                query.load(url,cb);
            }

            function showDetails(){
                if(_hovering && _moving==false  && _canUpdate==true && isAdded==false){
                    var id=$(href).html();
                    var t="Issue "+id+": "+String(title).substr(0,30)+"..."
                    JT_show('/snippets/issues/'+id+'?ajax=true',td,t,_event,onCallback,$(td));
                    isAdded=true;
                }else{
                    hideDetails();
                }
            }

            function hideDetails(){
                if(_moving==true){
                    isAdded=false;
                    $('#JT').remove();
                }
            }


            function isMoving(){
                if(_moving==false && _hovering==true){
                    _canUpdate=true;
                    showDetails();
                }
            }

            $(td).bind('mousemove',function(e){
                _event=e;
                _moving=true;
                if(_canUpdate){
                     _canUpdate=false;
                    hideDetails();
                    setTimeout(isMoving,1000);
                }

                setTimeout(clearMovingFlag,1000);
            });


            function clearMovingFlag(){
                _moving=false;

            }

            $(_n).bind('mouseover',function(){$(_n).addClass('itemHover');});
            $(_n).bind('mouseout',function(){$(_n).removeClass('itemHover');});
            $('a',td).bind('mouseover',function(e){

                _event=e;

                _canUpdate=true;
                _hovering=true;
                setTimeout(setCanUpdate,10);
            });

            $('a',td).bind('mouseout',function(){
                $(_n).removeClass('itemHover');
                _hovering=false;
                _moveFlag=false;

                hideDetails();
            });

            $(_n).bind('click',function(){
                if($.isCtrl()){
                    window.open(href);
                }else{
                    location.href=href;
                }


                return false;
            })

        }
});


//  Hotkeys
$(function(){
    
    var pageLinks=$('span.pagelinks ul li.page');
    var currentPage=null,prevPage=null,nextPage=null;

    $(pageLinks).each(function(i,n){
        if($('span',n)[0]!=null){
            if(!(i>=pageLinks.length-1)){
                nextPage=$('a',pageLinks[i+1]);

                $.hotkeys.add('n', {type: 'keydown', propagate: true},$.hotkeys.delegate(
                    function(e){
                        $(nextPage).parent().html('<span class="Selected">'+$(nextPage).html()+'</span>');
                        location.href=$(nextPage).attr('href');
                    }
                ));
            }

            if(!(i<=0)){
                prevPage=$('a',pageLinks[i-1]);//.;

                $.hotkeys.add('p', {type: 'keydown', propagate: true},$.hotkeys.delegate(
                    function(e){
                        $(prevPage).parent().html('<span class="Selected">'+$(prevPage).html()+'</span>');
                        location.href=$(prevPage).attr('href')
                    }
                ));
            }
        }
    });
});

