// Add event handler to body when window loads
function addLoadEvent(func) {
	var oldonload = window.onload;
	
	if (typeof window.onload != "function") {
		window.onload = func;
	} else {
		window.onload = function () {
			oldonload();
			func();
		}
	}
}

addLoadEvent(function () {
	Callouts.fix();
	Cursors.init();
	GoogleLinkTracker.init();
});

/*---------------------------------------------------------------------------+
| Cookie - Create/read/erase cookies                                         |
+---------------------------------------------------------------------------*/
var Cookie = {
    create: function (name, value, days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            var expires = "; expires=" + date.toGMTString();
        }
        else var expires = "";
        document.cookie = name + "=" + value + expires + "; path=/";
    },

    read: function (name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    },

    remove: function (name) {
        Cookie.create(name, "", -1);
    }
}


/*------------------------------------------------------------------------+
 | Callouts - Adjust widths of callouts depending on size of image within |
 +------------------------------------------------------------------------*/
var Callouts = {
    fix: function() {
        // Check for functionality
        if (!document.getElementById || !document.getElementsByTagName) return false;

        var bin = document.getElementById("content-primary");
        if (bin == null)
            return;

        var arrBins = bin.getElementsByTagName("*");
        var classRE = /call-[lr]/gi;

        // Set div width = largest image width
        for (var i = 0; i < arrBins.length; i++) {
            if (classRE.test(arrBins[i].className)) {
                var images = arrBins[i].getElementsByTagName("img");

                if (images.length >= 1) {
                    var maxWidth = images[0].offsetWidth;

                    for (var j = 0; j < images.length; j++) {
                        var curWidth = images[j].offsetWidth;
                        if (curWidth > maxWidth) maxWidth = curWidth;
                    }

                    //if (maxWidth > 100) {
                    arrBins[i].style.width = maxWidth + "px";
                    //}
                }
            }
        }

        return false;
    }
};


/*--------------------------------------------+
 | Cursors - Change cursor for sortable lists |
 +--------------------------------------------*/
var Cursors = {
	init : function() {
		// Check for functionality
		if (!document.getElementById || !document.getElementsByTagName) return false;
		
		var lists = document.getElementsByTagName("ul");
		
		for (var i = 0; i < lists.length; i++) {
			var curList = lists[i];
			
			if (curList.className.indexOf("sequence") > -1) {
				var listItems = curList.getElementsByTagName("li");
				for (var j = 0; j < listItems.length; j++) {
					listItems[j].onmousedown = function() { this.style.cursor = "url(/images/shared/grabbing.cur), move"; };
					listItems[j].onmouseup = function() { this.style.cursor = "url(/images/shared/grab.cur), move"; };
				}
			}
		}
	}
};


/*----------------------------------------------------------------+
 | DidMouseMove - Only use, prevent lightbox from showing on drag |
 +----------------------------------------------------------------*/
var DidMouseMove = {
	hash : {},

	recordDown : function(event)
	{
		var element = Event.element(event);
		DidMouseMove.hash[element.id] = new Array();
		DidMouseMove.hash[element.id][0] = event.screenX;
		DidMouseMove.hash[element.id][1] = event.screenY;
	},
	
	stopEventIfItDid : function(event)
	{
		var element = Event.element(event);
		if (!(DidMouseMove.hash[element.id][0] == event.screenX
			&& DidMouseMove.hash[element.id][1] == event.screenY))
			event.stop();
	}
};


/*-----------------------------------------------------------------------------------------+
 | GoogleLinkTracker - Add click tracking for Google Analytics to files and outgoing links |
 +-----------------------------------------------------------------------------------------*/
var GoogleLinkTracker = {
	init : function() {
		var links = document.getElementsByTagName("a");
		
		for (var i = 0; i < links.length; i++) {
			var theLink = links[i];
			var theURL = theLink.href.toLowerCase();
			
			if (typeof(pageTracker) != "undefined")
			{
				if (/\.(bmp|doc|docx|gif|jpg|pdf|png|xls|xlsx|ppt|pptx|zip)/.test(theURL)) {
					var func = function () { if (pageTracker) pageTracker._trackPageview("/files/" + this.href); };
					
					if (typeof(jQuery) != "undefined")
						jQuery(theLink).click(func);
					else
						theLink.onclick = func;
				}
					
				if (theURL.indexOf("metroplanning.org") == -1) {
					var func = function () { if (pageTracker) pageTracker._trackPageview("/outbound/" + this.href); };
					
					if (typeof(jQuery) != "undefined")
						jQuery(theLink).click(func);
					else
						theLink.onlick = func;
				}
			}
		}
	}
};


/*--------------------------------------------------+
 | Tog - Toggle visibility of two opposing elements |
 +--------------------------------------------------*/
var Tog = {
    swap: function(a, b) {
        Tog.toggle(a);
        Tog.toggle(b);
    },
    toggle: function(a) {
        if (typeof a == "string")
            a = document.getElementById(a);
        if (!a) return false;

        if (a.className.indexOf("closed") != -1) {
            Tog.toggleOn(a);
        } else {
            Tog.toggleOff(a);
        }
    },
    firstParamToggleOn: function(a, b, c) {
        Tog.toggleOn(a);
        Tog.toggleOff(b);
        Tog.toggleOff(c);
    },    
    toggleOn: function(a) {
        if (typeof a == "string")
            a = document.getElementById(a);
        if (!a) return false;

        oldClass = a.className;
        newClass = oldClass.replace(/closed/g, "");
        a.className = newClass;
    },
    toggleOff: function(a) {
        if (typeof a == "string")
            a = document.getElementById(a);
        if (!a) return false;

        a.className += " closed";
    },
    togglePropertyValue: function(a, prop, value1, value2) {
        if (typeof a == "string")
            a = document.getElementById(a);

        if (!a) return false;

        if (a[prop].indexOf(value1) != -1) {
            a[prop] = value2;
        } else {
            a[prop] = value1;
        }
    }
};

jQuery(document).ready(function(){
	// Add icons to links to files
    jQuery("a[href$='.doc':not(a.action)").addClass("icon icon-doc");
    jQuery("a[href$='.doc']").attr({ title: "Word document - Opens in a new window" });

    jQuery("a[href$='.pdf']:not(a.action)").addClass("icon icon-pdf");
    jQuery("a[href$='.pdf']").attr({ title: "Adobe PDF - Opens in a new window" });

    jQuery("a[href$='.ppt']:not(a.action)").addClass("icon icon-ppt");
    jQuery("a[href$='.ppt']").attr({ title: "PowerPoint presentation - Opens in a new window" });

    jQuery("a[href$='.xls']:not(a.action)").addClass("icon icon-xls");
    jQuery("a[href$='.xls']").attr({ title: "Excel spreadsheet - Opens in a new window" });

    jQuery("a[href$='.zip']:not(a.action), a[href$='.rar']:not(a.imglink)").addClass("icon icon-zip");
    jQuery("a[href$='.zip']").attr({ title: "ZIP file - Opens in a new window" });
    jQuery("a[href$='.rar']").attr({ title: "RAR file - Opens in a new window" });
	
	// Make links to files open in new windows
    jQuery("a[href$='.doc'], a[href$='.pdf'], a[href$='.xls'], a[href$='.zip'], a[href$='.rar']").attr({ target: "_blank" });
});