CookieManager = Class.create();
CookieManager.prototype = {
    BROWSER_IS_IE:
        (document.all
         && window.ActiveXObject
         && navigator.userAgent.toLowerCase().indexOf("msie") > -1
         && navigator.userAgent.toLowerCase().indexOf("opera") == -1),

    /**
     * I hate navigator string based browser detection too, but when Opera alone
     * chokes on cookies containing double quotes...
     */
    BROWSER_IS_OPERA:
        (navigator.userAgent.toLowerCase().indexOf("opera") != -1),

    initialize: function()
    {
        this.options =
        {
            shelfLife: 365,
            userData: false
        }

        this.cookieShelfLife = this.options.shelfLife;
        this.userDataForIE = this.options.userData;

        // Internet Explorer has a cookie handling bug - if the *combined size*
        // of all cookies stored for a given domain is greater than 4096 bytes,
        // document.cookie will return an empty string. Until this is fixed, we
        // can fall back on IE's proprietary userData behaviour if necessary.
        if (this.BROWSER_IS_IE && this.userDataForIE)
        {
            this.IE_CACHE_NAME = "storage";
            if ($(this.IE_CACHE_NAME) == null)
            {
                var div = document.createElement("DIV");
                div.id = this.IE_CACHE_NAME;
                document.body.appendChild(div);
            }
            this.store = $(this.IE_CACHE_NAME);
            this.store.style.behavior = "url('#default#userData')";
        }
    },

    /**
     * Returns the value of a cookie with the given name, or <code>null</code>
     * if no such cookie exists.
     */
    getCookie: function(aCookieName)
    {
        var result = null;
        if (this.BROWSER_IS_IE && this.userDataForIE)
        {
            this.store.load(this.IE_CACHE_NAME);
            result = this.store.getAttribute(aCookieName);
        }
        else
        {
            for (var i = 0; i < document.cookie.split('; ').length; i++)
            {
                var crumb = document.cookie.split('; ')[i].split('=');
                if (crumb[0] == aCookieName && crumb[1] != null)
                {
                    result = crumb[1];
                    break;
                }
            }
        }

        if (this.BROWSER_IS_OPERA && result != null)
        {
            result = result.replace(/%22/g, '"');
        }
        return result;
    },

    /**
     * Sets a cookie with the given name and value.
     */
    setCookie: function(aCookieName, aCookieValue)
    {
        if (this.BROWSER_IS_IE && this.userDataForIE)
        {
            this.store.setAttribute(aCookieName, aCookieValue);
            this.store.save(this.IE_CACHE_NAME);
        }
        else
        {
            if (this.BROWSER_IS_OPERA)
            {
                aCookieValue = aCookieValue.replace(/"/g, "%22");
            }
            var date = new Date();
            date.setTime(date.getTime() + (this.cookieShelfLife * 24*60*60*1000));
            var expires = '; expires=' + date.toGMTString();
            document.cookie = aCookieName + '=' + aCookieValue + expires + '; path=/';
        }
    },

    /**
     * Clears the cookie with the given name.
     */
    clearCookie: function(aCookieName)
    {
        if (this.BROWSER_IS_IE && this.userDataForIE)
        {
            this.store.load(this.IE_CACHE_NAME);
            this.store.removeAttribute(aCookieName);
            this.store.save(this.IE_CACHE_NAME);
        }
        else
        {
            document.cookie =
                aCookieName + '=;expires=Thu, 01-Jan-1970 00:00:01 GMT; path=/';
        }
    }
}
var cManager = new CookieManager();

Ajax.XMLAutocompleter = Class.create();
Object.extend(Object.extend(Ajax.XMLAutocompleter.prototype, Ajax.Autocompleter.prototype), {
    onComplete: function(req) {
        var anondiv = Builder.node('div',{}, [
            Builder.node('ul', {}, 
                $A(req.responseXML.getElementsByTagName('package')).map( function(elm) {
                    var link = elm.getElementsByTagName('link')[0].firstChild.nodeValue;
                    var name = elm.getElementsByTagName('name')[0].firstChild.nodeValue;
                    var hint = elm.getElementsByTagName('hint')[0].firstChild.nodeValue.toLowerCase();
                        
                    return Builder.node('li', {}, [
                        Builder.node('a', {href: link, style: ""}, [ 
                            Builder.node('span', {'class':'package'}, [ name ]), 
                            Builder.node('span', {'class':'hint'}, [ hint ])
                        ])
                    ]);
                })
            )
        ]);
        this.updateChoices(anondiv.innerHTML);
    }
});

// rules
var ruleset = {
	'li.oddebuildrow' : function(el) { 
		el.onmouseover = function() { 
			this.style.background='#CCD3E9';
		},
		el.onmouseout = function(){
			this.style.background='#D9D9D9';
		} 
	},
	'li.evenebuildrow' : function(el){
		el.onmouseover = function() { 
			this.style.background='#DCE3F9';
		},
		el.onmouseout = function(){
			this.style.background='transparent';
		}
	},
	'.oddrowh' : function(el) { 
		el.onmouseover = function() { 
			this.style.background='#CCD3E9';
		},
		el.onmouseout = function(){
			this.style.background='#D9D9D9';
		} 
	},
	'.evenrowh' : function(el){
		el.onmouseover = function() { 
			this.style.background='#DCE3F9';
		},
		el.onmouseout = function(){
			this.style.background='transparent';
		}
	},
	'.hilight' : function(el){
		el.onmouseover = function() { 
			this.style.background='#DCE3F9';
		},
		el.onmouseout = function(){
			this.style.background='transparent';
		}
	},
	'.hilight_gray' : function(el){
		el.onmouseover = function() { 
			this.style.background='#CCD3E9';
		},
		el.onmouseout = function(){
			this.style.background='#D9D9D9';
		}
	},
	'#loginbutton' : function(el){
		el.onclick = function(){
			loginboxEffect.toggle('height');
			document.getElementById('mainloginbox').focus();
			return false;
		}
	},
	'#listviewlink' : function(el){
		el.onclick = function(){
			if(cManager.getCookie('browse_view') == 0){
				cManager.setCookie('browse_view', '1');
			}else{
				cManager.setCookie('browse_view', '0');
			}
			
			listviewEffect.toggle('height');
			browseviewEffect.toggle('height');
			return false;
		}
	},
	'#showUntracked' : function(el){
		el.onclick = function(){
			if(cManager.getCookie('homepage_untracked') == 0){
				cManager.setCookie('homepage_untracked', '1');
			}else{
				cManager.setCookie('homepage_untracked', '0');
			}
			untracked1Effect.toggle('height');
			untracked2Effect.toggle('height');
			untracked3Effect.toggle('height');
			return false;
		}
	}
};

// page init
function init(){
	// hide the standard boxes
	if(document.getElementById('loginboxouter')){
		loginboxEffect = new fx.FadeSize(document.getElementById('loginboxouter') , {duration: 500});
		loginboxEffect.hide('height');
		document.getElementById('loginboxouter').style.display = 'block';
	}

	if(document.getElementById('listview')){
		listviewEffect = new fx.FadeSize(document.getElementById('listbox') , {duration: 500});
		browseviewEffect = new fx.FadeSize(document.getElementById('browsebox') , {duration: 500});
		
		if(document.getElementById('listbox').style.display == 'none'){
			
			if(cManager.getCookie('browse_view') == 0 || !cManager.getCookie('browse_view')){
				listviewEffect.hide('height');
			}else{
				browseviewEffect.hide('height');
			}
			
			document.getElementById('listbox').style.display = 'block';
		}else{
			browseviewEffect.hide('height');
			document.getElementById('browsebox').style.display = 'block';
		}
	}
	
	if(document.getElementById('untracked1')){
		untracked1Effect = new fx.FadeSize(document.getElementById('untracked1') , {duration: 500});
		untracked2Effect = new fx.FadeSize(document.getElementById('untracked2') , {duration: 500});
		untracked3Effect = new fx.FadeSize(document.getElementById('untracked3') , {duration: 500});
		
		if(cManager.getCookie('homepage_untracked') == 0 || !cManager.getCookie('homepage_untracked')){
			untracked1Effect.hide('height');
			untracked2Effect.hide('height');
			untracked3Effect.hide('height');
		}
	}
	
	enableTooltips("newpkgs");
	if(!window.opera){
            new Ajax.XMLAutocompleter('searchbox', 'searchbox_completion', '/AJAX/SearchSuggest', { paramName: 'search', minChars: 3 , select: 'package'});
	}
}

Event.observe(window, 'load', init);
/* window.onload = init; */
Behaviour.start();
Behaviour.register( ruleset );

