/**
 * This file controls the resolution switching based on screen/window size
 * These are called on load, resize and at <refreshRate> intervals
 */
//checkBrowserWidth();

//addEvent(window, "load", function() { linkCss.init(); });
addEvent(window, "resize", checkBrowserWidth);
//addEvent(window, "load", checkBrowserWidth); // Added to load because of menu switcher

//addLoadListener(function() { linkCss.init(); });
//addLoadListener(checkBrowserWidth);

/* Attempt at setting CSS *after* DOM is loaded but *before* page is loaded (images, etc)
if(document.addEventListener && !window.opera) // Mozilla only. Triggers on DOM - not page - load
{
	document.addEventListener("DOMContentLoaded", checkBrowserWidth, null);
}
else if(window.opera)// Non-Mozilla, non-IE fallback. Triggers on page load
{
	addLoadListener(checkBrowserWidth);
}
*/

// Check the browser width every <refreshRate> in case the resize/loads aren't being called
// EDIT: was causing pages to jump a bit in Fx when not at top of page (scrolled down a bit)
//var refreshRate = 5000;
//var autoSize = setInterval('checkBrowserWidth()', refreshRate);

function checkBrowserWidth()
{
	var theWidth = getBrowserWidth();
	
	DropdownVisibility(theWidth);
	
	if (theWidth == 0)
	{
		var resolutionCookie = document.cookie.match(/(^|;)res[^;]*(;|$)/);
		
		// TODO: revisit to pull more info from cookies and pass to linkCss.SetStyleSheet();
		if (resolutionCookie != null)
		{
			//alert('going from cookie');
			setStylesheet(unescape(resolutionCookie[0].split("=")[1]));
		}
		
		//addLoadListener(checkBrowserWidth);
		//addEvent(window, "load", checkBrowserWidth);
		return false;
	}
	
	if (theWidth >= 450)
	{
	    setStylesheet("css_800");
	    //linkCss.AddStyleSheet({'href': '../css/layout_800.css', 'rel': 'alternate stylesheet', 'title': '800 x 600'});
	    //linkCss.SetStyleSheet('800 x 600');
	    //linkCss.SetStyleSheet('chrome');
	    //linkCss.SetStyleSheet('ie fixes');
	    //alert('800 activated'); //IE will not work without alerting something?
	    document.cookie = "res=" + escape("800");
	}
	else
	{
		setStylesheet("");
		//linkCss.SetStyleSheet('ie fixes');
		document.cookie = "res=";
	}
	
	//linkCss.Activate();
		
	return true;
};




function getBrowserWidth()
{
	if (window.innerWidth)
	{
		return window.innerWidth;
	}
	else if (document.documentElement && document.documentElement.clientWidth)
	{
		return document.documentElement.clientWidth;
	}
	else if (document.body)
	{
		return document.body.clientWidth;
	}
	
	return 0;
};




function setStylesheet(styleTitle)
{
	var currTag;

	if (document.getElementsByTagName)
	{
		/*
		var p = document.createElement('p');
		p.appendChild(document.createTextNode("set stylesheet"));
		var head = document.getElementsByTagName('body')[0];
		head.insertBefore(p, head.firstChild);
		*/
		
		for (var i = 0; (currTag = document.getElementsByTagName("link")[i]); i++)
		{
			if (currTag.getAttribute("rel").indexOf("style") != -1 && currTag.getAttribute("id"))
			{
				currTag.disabled = true;
				//currTag.rel = "alternate stylesheet";
				
				if(currTag.getAttribute("id") == styleTitle)
				{
					currTag.disabled = false;
					//currTag.rel = "stylesheet";
				}
				
				if(styleTitle != "" && currTag.getAttribute("id") == "css_chrome")
				{
					currTag.disabled = false;
					//currTag.rel = "stylesheet";
				}
				
				if(styleTitle != "" && currTag.getAttribute("id") == "ie_fixes")
				{
					currTag.disabled = false;
				}
			}
		}
	}
	
	return true;
};

/**
 * Originally started as a runtime <link /> stylesheet creator
 * which created or deleted sheets as called for.
 * Adjusted (for now) to simply enable or disable existing sheets.
 */
var linkCss = new Object();
Object.extend(linkCss, {
	
    init: function ()
    {
        this.sheets = this.GetSheets();
        this.head = document.getElementsByTagName("head")[0];
        this.headName = this.head.nodeName;
        this.QueuedSheets = new Array();
        this.DisableAllSheets();
    },
    
    Activate: function()
    {
    	if(!this.ThrottleState)
    	{
    		alert('begin set');
    		
	    	for(var i=0; (sheet = this.QueuedSheets[i]); i++)
	    	{
	    		this.EnableSheet(sheet);
	    	}
	    	
    		this.EnableThrottle();
    	}
    },
    
    AddStyleSheet: function(sheet)
    {
        if(!this.head) { alert('add init'); this.init(); }
        
        if(!sheet.href) return false;
        
        var rel         = sheet.rel || 'alternate stylesheet';
        var title       = sheet.title || 'stylesheet_' + this.FileName(sheet);
        var type        = sheet.type || 'text/css';
        var disabled    = sheet.disabled || 'false';
        var id          = escape(sheet.id || 'id_' + title);
        var media       = sheet.media || 'screen';
        
        // Gets seconds from epoch for js querystring to trick/force daily reloads
        var fullDate = Math.floor(new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()).getTime()/1000);
        fullDate = Math.ceil(Math.random() * 10000); // Debug
        
        sheet.href += "?" + fullDate;

        var link = document.createElement('link');
        link.setAttribute('href', href);
        link.setAttribute('rel', rel);
        link.setAttribute('title', title);
        link.setAttribute('type', type);
        link.setAttribute('disabled', disabled);
        link.setAttribute('id', id);
        link.setAttribute('media', media);
        
        return this.head.appendChild(link);
    },
    
    ClearThrottle: function()
    {
    	window.clearTimeout(this.ThrottleState);
    	delete this.ThrottleState;
    	alert('timeout cleared');
    },
    
    DisableSheet: function(sheet)
    {
    	sheet.disabled = true;
    	//sheet.rel = "alternative stylesheet"; // All versions of IE FREAK OUT when attempting to set rel (infinite reloading)
    },
    
    DisableAllSheets: function()
    {
    	for(var i=0; (sheet = this.sheets[i]); i++)
    	{
    		this.DisableSheet(sheet);
    	}
    },
    
    EnableSheet: function(sheet)
    {
    	sheet.disabled = false;
    	//sheet.rel = "stylesheet"; // All versions of IE FREAK OUT when attempting to set rel (infinite reloading)
    },
    
    EnableThrottle: function()
    {
    	//if(typeof this.ThrottleState == "number")
    	if(!this.ThrottleState)
    	{
    		alert('throttle enabled');
    		var self = this;
    		this.ThrottleState = window.setTimeout(function() { self.ClearThrottle(); }, 2000);
    	}
    },
    
    FileName: function(href) {
    	var name = href.split("?")[0];
        return name.substring(name.lastIndexOf("/")+1, name.length);
    },
	
    GetSheets: function()
    {
        return document.getElementsByTagName('link');
    },
    
    RemoveStyleSheet: function(name)
    {
        var sheet = this.SheetExists(name);
        
        //if(sheet = this.SheetExists(name) !== false)
        if(sheet !== false)
        {
            this.head.removeChild(sheet);
        }
    },
    
    SetStyleSheet: function(sheetTitle)
    {
    	if(sheet = this.SheetExists(sheetTitle))
    	{
	    	this.QueuedSheets.push(sheet);
    	}
    },
    
    SheetExists: function(sheetTitle)
    {
        if(!this.sheets) { this.init(); }
        
        for(var i=0; i<this.sheets.length; i++)
        {
            if(this.sheets[i].getAttribute("title") == sheetTitle)
            {
                 return this.sheets[i];
                 //return true;
            }
        }
        
        return false;
    }
});

/**
 * Turns menu dropdowns off for small screens
 * xxx hack -- to be integrated in linkCss for atomic res/css changes
 */
function DropdownVisibility(screenSize)
{
    var menus = Array($('menu0'), $('menu1'), $('menu2'), $('menu3'), $('menu4'));
    
    for(var i=0; i<menus.length; i++)
    {
       var menu = menus[i];
       if(menu) {
           menu.style.display = (screenSize < 450) ? "none" : "block";
       }
    }
};