
$(function(){
    var focus=false;

    function onFieldFocus(){focus=true;}

    function onFieldBlur(){focus=false;}

    $('input,select,textarea').bind('focus',onFieldFocus);
    $('input,select,textarea').bind('blur',onFieldBlur);

    $("input[type='file']").each(function(i,n){
        var d=$(n).attr('disabled');

        $(n).bind('keydown',function(){
            onFieldFocus();
        });
    });

    $.fieldFocus=function(){return focus;}
    $.addToFieldFocus=function(el){
        $(el).bind('focus',onFieldFocus);
        $(el).bind('blur',onFieldBlur);
        $(el).bind('keydown',onFieldFocus);
    }
    //  Hotkeys delegate method
    //  Acts as a proxy allowing the shortcut to perform if no field is focused and sorts out issue with
    //  The keycode value populating a field if given focus
    $.hotkeys.delegate=function(callback){
        return function(){};

        return function(){
            if(focus==false){
                setTimeout(callback,2);
                return false;
            }
        }
    }

    $('body').click(onFieldBlur);
    //  Search

    $.hotkeys.add('s', {type: 'keydown', propagate: true},$.hotkeys.delegate(
                function(e){
                    $('#iSearchQuery').trigger('focus');
                }
           ));

    $.hotkeys.add('i', {type: 'keydown', propagate: true},$.hotkeys.delegate(
            function(e){
                location.href=$('a#actIssues').attr('href');
            }
            ));

    $.hotkeys.add('d', {type: 'keydown', propagate: true},$.hotkeys.delegate(
            function(e){
                location.href=$('a#actDashboard').attr('href');
            }
            ));

    $.hotkeys.add('space', {type: 'keydown', propagate: true},$.hotkeys.delegate(
            function(e){
               location.href=$('a#actNewIssue').attr('href');
            }
            ));


});


function toggleCurrentLink(link){
    $(link).parent('li').siblings('li').removeClass('current');
    $(link).parent('li').addClass('current');
}

function returnFalse(){
    return false;
}

function getmetaContents(mn){
    var t=$("meta");
    var ret="";

    $.each(t,function(i,n){
        if(n.name==mn){ret=String(n.content);}
    });

    return ret;
}


function HistoryList(options){
    var fixx_cookie= $.cookieJar('fixx');
    var data=fixx_cookie.toObject();

    prepareFreqData();

    function prepareFreqData(){
        if(!data.history) data.history=[];
        if(data.history.length==null) data.history=[];

        var oldHis=data.history;
        var dups={};
        var id=$('input#this_issue_id').val();
        var title=$('input#this_issue_title').val();

        if(id!=null){
            var newHis=[];
            var oldlast=oldHis[0];

            if(oldlast!=null){
                oldHis.splice(0,1,{'id':id,freq:1,title:title},oldlast);
            }else{
                oldHis.push({'id':id,freq:1,title:title});
            }

            for(iCount=0;iCount<options.items-1;iCount++){
                if(oldHis[iCount]!=null){
                    if(dups[oldHis[iCount].id]!=true){
                        dups[oldHis[iCount].id]=true;
                        newHis.push(oldHis[iCount]);
                    }else{

                    }
                }
            }

            data.history=newHis;
        }

       fixx_cookie.setFromObject(data);
    }

    this.getHistory=function(){
        return data.history;
    }

    this.clear=function(){
        data.history={};
        fixx_cookie.setFromObject(data);
    }
}

function HistoryFrequency(){
    var fixx_cookie= $.cookieJar('fixx');
    var data=fixx_cookie.toObject();

    prepareFreqData();



    function prepareFreqData(){
        if(!data.history) data.history={};

        var id=$('input#this_issue_id').val();
        var title=$('input#this_issue_title').val();

        if(id!=null){
            if(data.history[id]==null){
              data.history[id]={'id':id,freq:1,title:title};
            }else{
                var freq=parseInt(data.history[id].freq);
                data.history[id].freq=freq+1;
            }
        }

       fixx_cookie.setFromObject(data);
    }

    this.getHistory=function(){
        return data.history;
    }

    this.clear=function(){
        data.history={};
        fixx_cookie.setFromObject(data);
    }
}

$(function(){
    var stickies=$('li.sticky-actions');
    var historySticky=$('li.history',stickies);
    var ul=$('ul.the-history');

    var his_toggle=false;


    var his_freq = new HistoryList({items:10});

    function sortByFreq(a,b){
        return a.freq<b.freq;
    }

    var ar=$.makeArray(his_freq);

    ar=ar.sort(sortByFreq);

    var count=0;
    for(each in his_freq.getHistory()){
        count++;
        var issue=his_freq.getHistory()[each];
        ul.append('<li class="his"><a href="/issues/'+issue.id+'/"><span style=\"width:3em;float:left;display:block;\" >'+issue.id+'</span> : '+String(issue.title).substr(0,20)+"..."+'</a></li>');
    }


    function onClearHistory(){
        his_freq.clear();
        onHistoryClick();
        $('li.his',ul).remove();
        $('li.sep',ul).hide();
        $('span',historySticky).html('');
        count=0;
    }

    var a=$('<a href="#">Clear History</a>');

    $(a).bind('click',onClearHistory);

    var t=$('<li class="sep"></li>');

    t.append(a);

    ul.append(t);


    function onOverUl(){

    }
    var _hideFlag=true;

    function startTimer(){

            $('li',ul).bind('mouseover',function(){
            _hideFlag=false;

          });

            function setForFadeout(){
                setTimeout(function(){
                    if(_hideFlag) ul.fadeOut();
                },3000);
            }

          $('li',ul).bind('mouseout',function(){
              _hideFlag=true;
              setForFadeout();
          });
      setTimeout(function(){
      },1000);
    }
    function onHistoryClick(e){
        if(count>0){
        	ul.fadeIn();
        }
    }

    if(count==0) $('span',historySticky).hide();

    $('span',historySticky).bind('mouseover',onHistoryClick);
    $('span',historySticky).bind('mouseout',startTimer);
});

/**
*   Hook onto submit button, disable on post, and, after 3 seconds enable if the page has posted enable
*
*/


$(function(){

    var sp=$('<span class="doing">&nbsp;</span>')[0];
    //alert(sp);


    function eachForm(i,frm){
        var submits=$("input[type='submit']",frm);
        var tt=$(".Actions ul ",frm);
        var td=$(".Actions ul:last ",frm);
        var dd=$(td).parent()[0];


        var cc=tt[0];

        if(dd!=null){
            function Binding(n){
                var flip=false;
                var n=n;

                function onSubmitClick(){
                    setTimeout(function(){$(dd).append(sp);},2);

                    $(tt).addClass('intoNoWhere');
                            //  Code wrapped in thread call to ensure background image has time to load for loading effect
                            setTimeout(function(){$(frm).trigger('submit');},500);

                            //  revert after 10 seconds
                            setTimeout(function(){
                                $(sp).remove();
                                $(tt).removeClass('intoNoWhere');
                            },10000);

                    return false;

                }


                $(n).bind('click',onSubmitClick);
            }

            function forEachSubmit(i,n){
                new Binding(n);
            }

            submits.each(forEachSubmit);
        }
    }


    //  Get each form
    var form=$('form');
    $.each(form,eachForm);

});



$(function(){
    now = new Date();
    minDate = new Date(now.setDate(now.getDate() - 1));
    $('input.DateField').datepicker({clickInput:true});
    $('input.DateFieldLowerThan').datepicker({clickInput:true,maxDate: now});
    $('input.DateFieldGreaterThan').datepicker({clickInput:true,minDate: minDate});});


$(function(){
	$('input[@title]').example(function() {
	    return $(this).attr('title');
	});

    $('textarea[@title]').example(function() {
	    return $(this).attr('title');
	});
});


//  Control key
//  Control key check
(function($){

    var isCtrl = false;

    $.isCtrl=function(){
        return isCtrl;
    };

    $(document).keyup(function(e){
        if(e.which == 17) {isCtrl=false;}

    });

    $(document).keydown(function(e){
        if(e.which == 17) {isCtrl=true;}
    });

})(jQuery);

$(function(){
    var his_toggle=false;
    var hel_toggle=false;
});


$(function(){
	$('.highlight').scrollTo(100);
	$('.highlight').animate({ backgroundColor: "#FFF" }, 3500);
});



// @TODO - Mark to refactor code.

/**
* The following variables may be adjusted
*/
var active_color = '#000'; // Colour of user provided text
var inactive_color = '#ccc'; // Colour of default text

/**
* No need to modify anything below this line
*/

$(document).ready(function() {
  $("input.default-value").css("color", inactive_color);
  var default_values = new Array();
  $("input.default-value").focus(function() {
    if (!default_values[this.id]) {
      default_values[this.id] = this.value;
    }
    if (this.value == default_values[this.id]) {
      this.value = '';
      this.style.color = active_color;
    }
    $(this).blur(function() {
      if (this.value == '') {
        this.style.color = inactive_color;
        this.value = default_values[this.id];
      }
    });
  });
});


function enableFieldsInDiv(oDiv){
    $('select,input,textarea',oDiv).attr('disabled','');
}

function disableFieldsInDiv(oDiv){
    $('select,input,textarea',oDiv).attr('disabled','true');
}

function CloneableTemplateDecorator(oOptions){
    var _oOptions=oOptions;
    var _inProcess=false;
    var _oAddedSoFar={};
    var _key=0;
    var _nodeCount=0;

    this.begin=function(){
        if(_inProcess==false) cloneNew();
        _inProcess=true;
    };

    this.clone=function(){cloneNew();
    };

    this.end=function(){
        _inProcess=false;
        removeAll();
    };

    function removeAll(){
        $.each(_oAddedSoFar,function(i,n){
            if(n!=null){
                n.destroy();
            }
        });

    }

    function cloneNew(){
        _oOptions.onAdded(null);
        _nodeCount++;
        var _newNode=$(_oOptions.rootNode).clone()[0];

        _key++;
        _oAddedSoFar[_key]=new CloneItem(_newNode,_key,onRemoved);

        $(_oOptions.rootNode).before(_newNode);
        $(_newNode).show();
    }

    function onRemoved(key){
        _nodeCount--;
        _oAddedSoFar[key]=null;
        if(_nodeCount==0){
            _oAddedSoFar={};
            _key=0;
            if(_inProcess==true) {_inProcess=false;_oOptions.onAllRemoved();}

        }
    }



    function CloneableTemplateDecorator(){}

    CloneableTemplateDecorator();



    function CloneItem(oNode,key,callBack){
        var _oNode=oNode;
        var _key=key;
        var _callBack=callBack;
        var _this=this;

        //$('input,select,textarea,oNode)
        $('input,select,textarea',oNode).each(function(i,n){
            //alert("LKJ");
            $.addToFieldFocus(n);
        });
        this.destroy=function(){
            $(_oNode).remove();
            _callBack(_key);
            return false;
        };

        $(_oOptions.removeClass,_oNode).bind('click',_this.destroy);
    }
}



function JsonCall(sService,oData,callback){
    var _callback=callback;

    $.get(sService,oData,function(oData){
       _callback(oData);
    });
}

function ajaxDropdown(sService,field,option){
    var oSelect=field;
    $(oSelect).attr('disabled','true');
    new JsonCall(sService,null,function(oData){

        if(oSelect){
            $(oSelect).html('<option value="-1">'+option+'</option>');

            $.each(oData,function(i,n){
                var oOption=document.createElement('option');
                $(oOption).html(n.name);
                $(oOption).val(n.id);
                oSelect.appendChild(oOption);
            });

            $(oSelect).attr('disabled','');
        }
    });
}

function ajaxCheckList(sService,element,name,object,defaultElement){
    $(element).html("");

    var _fied=$('<input type="checkbox"name="'+name+'" id="'+ name + '"/>');
    var _label=$('<label></label>');


    $('input,label',element).addClass('hide');

    new JsonCall(sService,null,function(oData){
        if(element){
                try {
                    oData = arrayizeJSON($.parseJSON(oData)[object]);
                    if(defaultElement != undefined){
                        oData.push(defaultElement);   
                    }
                } catch (e){
                    alert(e);
                    oData = null;
                }
            if(oData != null){
              $.each(oData,function(i,n){
                f=_fied.clone();
                l=_label.clone();

                f.attr('value',n.id);

                l.html(""+n.name);

                $(element).append(f);
                $(element).append(l);
              });
            }
        }
    });

}



function TabPane(options){
    var iCurrentTab=null;

    var tabs=$(options.tabs,options.element).get();
    var panes=$(options.pane,options.element).get();
    var anchor='';

    function showTabAndPanel(oTab,oPanel){
        $(oTab).addClass(options.current);
        $(oPanel).removeClass(options.hide);
        $.cookie('pane', '#'+$(oPanel).attr('id'), {expires: 30});
    }

    function hideTabAndPanel(oTab,oPanel){
        $(oTab).removeClass(options.current);
        $(oPanel).addClass(options.hide);
    }



    function forEachTab(i,n){
        if(anchor==String($('a',n).attr('href'))){
            iCurrentTab=i;
        }

        function onTabClick(){
            showTabAndPanel(tabs[i],panes[i]);

            if(iCurrentTab!=null){
                if(iCurrentTab!=i){
                hideTabAndPanel(tabs[iCurrentTab],panes[iCurrentTab]);
                }
            }

            iCurrentTab=i;
        }

        $('a',n).bind('click',onTabClick);
    }

    var url=location.href;
    anchor=location.hash;

    if(anchor.length==0) {anchor=$.cookie('pane');}
    $.each(tabs,forEachTab);

    if(iCurrentTab==null) {iCurrentTab=0;}
    showTabAndPanel(tabs[iCurrentTab],panes[iCurrentTab]);
}



$(function(){
    var isDown=false;

    function onMouseOver(){
        if(!isDown){
            $('ul',this).slideDown(function(){
                isDown=true;
            });
        }
    }

    function onMouseOut(){
        if(isDown){
            $('ul',this).slideUp(function(){
                isDown=false;
            });
        }
    }

    $('div.navigation ul li').bind('mouseover',onMouseOver);
    $('div.navigation ul li').bind('mouseout',onMouseOut);
});


jQuery.fn.autolink = function () {
	return this.each( function(){
		var re = /((http|https|ftp|nntp|call):\/\/[\w?=&.\/-;#~%-]+(?![\w\s?&.\/;#~%"=-]*>))/g;
		$(this).html( $(this).html().replace(re, '<a href="$1">$1</a> ') );
	});
}

$(function(){
   // Auto link key XHTML elements
    $("td.issueContainer  div.entry-content").autolink();
    $("div.CommentItem  div.entry-content").autolink();
});


function arrayizeJSON(obj){
     if (obj.constructor.toString().indexOf("Array") == -1){
       return new Array(obj);
    }  else {
        return obj;
    }
}

function TagService(){


    this.getTagsMatching=function(str,callback){
        var res=[];
        function forEachDummy(i,n){
            var myregexp = new RegExp("^"+str, "gim");
            var match=String(n.value).match(myregexp);

            if(match!=null && str.length!=0) res.push(n.value);
        }

        $.each(dummy,forEachDummy)
        callback(res);
    }
}

$(function(){
    var tagService=new TagService();
    var flip=false;
    function getData(term,callback){
        function onData(data){
            var d=data;
            var res=[];
            function eachD(i,n){
                res.push(n.label);
            }

            var str="";
            function eachD(i,n){
                str+=n.label+"\n";
            }

            if(d != null){
                $.each(d.tag,eachD);
            }

            callback(str);
        }

        $.ajax({
           url:'/api/backend/tag-suggestion?tag='+term ,
            async:true,
            success:onData,
            dataType: 'json'
        });
    }

    //  "/scripts/tagtest.js"
    //  getData
    $(".TagField input").autocomplete(null, {

		max: 20,
		highlight: false,
		multiple: true,
		multipleSeparator: ",",
		scroll: true,
		scrollHeight: 200,
        selectFirst:false,
        minChars:1,
        service:getData
    });

});

