// Ronald Huereca (www.ronalfy.com)
// Custom Reading Container 1.0
// Last Updated: 01/21/2007
// Find updates to this script at: http://www.devlounge.net/articles/custom-reading-containers
function CRCCollection() { 
	this.Add = Add;
	this.Containers = new Array();
	this.ContainerCount = 0;
	this.StopDrag = StopDrag;
	this.GetDistance = GetDistance;
	this.GetLeftOffset = GetLeftOffset;
	this.IsLeftClick = IsLeftClick;
	this.CreateCookie = CreateCookie;
	this.ReadCookie = ReadCookie;
	this.CookieName = "customContainers";
	this.Cookie = null;
	this.CookieArray = null;
	
	//Read in a saved cookie if available
	this.Cookie = this.ReadCookie(this.CookieName);
	if (this.Cookie != null) {
		this.CookieArray = this.Cookie.split(',');
	}
	
}
CRCCollection.instance = null;
CRCCollection.GetInstance = function() {
	if (CRCCollection.instance == null) {
		this.instance = new CRCCollection();
	}
		
	//Return the instance
	return this.instance;
}
function Add(container, defaultWidth, IsFixed, minWidth, maxWidth, IsPercentage) {
	var newContainer = 	new CRCWidth(container, defaultWidth, IsFixed, minWidth, maxWidth, IsPercentage);
	this.Containers[this.ContainerCount] = newContainer;
	this.ContainerCount += 1;
	return newContainer;
}
function StopDrag(e) {
	var myObj = this;
	if (!e) var e = window.event;
	if (myObj.IsLeftClick(e)) {
		for (var i = 0; i < myObj.ContainerCount; i++) {
				var container = myObj.Containers[i];
				container.IsDrag = false;
				document.body.style.cursor = "auto";
						
			//Save the data in the Cookie Array
			if (container.IsSaved) {
				var cookies = myObj.CookieArray;
				if (cookies == null) {
					cookies = new Array();
				}
				var cookieCount = cookies.length;
				if (cookieCount == 0) {
					cookies[cookies.length] = container.containerName;
					cookies[cookies.length] = container.lastSavedWidth;
				} else {
					var found = false;
					for (var b = 0; b < cookieCount; b++) {
						if (cookies[b] == container.containerName) {
							cookies[b+1] = container.lastSavedWidth;
							var found = true;
							break;
						} 
					}
					if (found == false) {
						cookies[cookies.length] = container.containerName;
						cookies[cookies.length] = container.lastSavedWidth;
					}
				}
			}
			if (cookies != null) { myObj.CookieArray = cookies; }
		} //end for
		
		//Create the cookie string
		var cookieString = "";
		if (myObj.CookieArray != null) {
			for (var i = 0; i < myObj.CookieArray.length; i++) {
				if ( i + 1 == myObj.CookieArray.length) {
					cookieString += myObj.CookieArray[i] + "";
				} else {
					cookieString += myObj.CookieArray[i] + "" + ",";
				}
			}
			//set the cookie with cookieString
			if (cookieString != "") {
				myObj.CreateCookie(myObj.CookieName, cookieString, 365);
			}
		}
		
	}
}
function GetDistance(e) {
	var myObj = this;
	//From http://www.quirksmode.org/js/events_properties.html
	//Calculates the mouse position relative to the document in pixels
	var posx = 0;
	var posy = 0;
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
	//Find the Element that has dragging enabled, if any
	var container = null;
	for (var i = 0; i < myObj.Containers.length; i++) {
			
			var container = myObj.Containers[i];
			if (container.IsDrag == true) {
				
				break;
			} else { 
				container = null;
			}
	}
	if (container == null) { return; }
	
	//Get the number to subtract from the container element
	var difference = ((posx - this.GetLeftOffset(container.container)) - container.containerWidth);
	
	//Pass the difference to the container object for resizing
	container.WidthChanged(difference);
	}
//From http://www.quirksmode.org/js/findpos.html
function GetLeftOffset(element) {
	var myObj = this;
	var curleft = 0;
	if (element.offsetParent) {
		curleft = element.offsetLeft
		while (element = element.offsetParent) {
			curleft += element.offsetLeft
		}
	}
	return curleft;
}
function IsLeftClick(e) { 
//Code snippet from Prototype
		if (e.button) {
			return ((e.button) && (e.button == 1))
		} else if (e.which) {
			return ((e.which) && (e.which == 1));
		} else { 
			return false;
		}
}
//From http://www.quirksmode.org/js/cookies.html
function CreateCookie(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=/";
}
function ReadCookie(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;
}
//End Class CRCCollection
//Start Class CRCWidth
/* Parameters:
			readingContainer - The ID of the container to be resized
			defaultWidth - The default width of the container (i.e., 1024px)
			IsFixed - Whether the default width is a fixed size (true or false)
			minWidth - Integer value of the minWidth (i.e., 20)
			maxWidth - Integer value of the maxWidth (i.e., 100)
			IsPercentage - True if the min and maxwidth are percentages, false if in pixels. 
			*/
function CRCWidth(readingContainer, defaultWidth, IsFixed, minWidth, maxWidth, IsPercentage) {
	var myObj = this;
	this.overlay = null;
	this.containerName = readingContainer;
	this.defaultWidth = 0;
	this.container = null;
	this.IsPercentage = true;
	this.IsFixed = IsFixed;
	this.minWidth = 0;
	this.maxWidth = 100;
	this.lastSavedWidth = null;
	this.IsSaved = false;
	this.IsDrag = false;
	this.containerWidth = 0;
	
	//Functions
	this.GetElementWidth = GetElementWidth;
	this.GetElementHeight = GetElementHeight;
	this.GetBrowserWidth = GetBrowserWidth;
	this.IsLeftClick = IsLeftClick;
	this.StartDrag = StartDrag;
	this.WidthChanged = WidthChanged;
	
	//Set whether the passed minwidth and maxwidth is a percentage
	(typeof( IsPercentage ) == 'boolean') ? this.IsPercentage = IsPercentage : this.IsPercentage = false;
	
	//Set the min amd max widths
	if (this.IsPercentage == true) {
		if (typeof(minWidth) == 'number' && minWidth <= 100 && minWidth >= 0) { this.minWidth = minWidth; }
		(typeof(maxWidth) == 'number' && maxWidth <= 100 && maxWidth > this.minWidth) ? this.maxWidth = maxWidth : this.maxWidth = 100;
	} else {
		if (typeof(minWidth) == 'number' && minWidth >= 0) { this.minWidth = minWidth;}
		(typeof(maxWidth) == 'number' && maxWidth > this.minWidth) ? this.maxWidth = maxWidth : this.maxWidth = this.GetBrowserWidth();
		}
			
	//Find the readingContainer
	this.container = document.getElementById(this.containerName);
		
	this.defaultWidth = defaultWidth;
	this.lastSavedWidth = this.container.style.width;
	
	//Perform the overlay
	this.overlay = document.createElement('div');
	var overlayID = 'crc-overlay-' + this.containerName;
	this.overlay.id = overlayID;
	this.overlay.className = 'crc-overlay';
  this.overlay.style.height = this.GetElementHeight(this.container) + "px";
	this.container.appendChild(this.overlay);
	this.overlay.onmousedown = function(e) { myObj.StartDrag(myObj, e)};
	
	//Get the width of the container
	this.containerWidth = this.GetElementWidth(this.container);
													 
}
function StartDrag(myObj, e) { 
	var myObj = this;
	if (!e) var e = window.event;
	
	if (myObj.IsLeftClick(e)) {
		myObj.IsDrag = true;
		document.body.style.cursor = "e-resize";
		
	}
}
function IsLeftClick(e) { 
//Code snippet from Prototype
		if (e.button) {
			return ((e.button) && (e.button == 1))
		} else if (e.which) {
			return ((e.which) && (e.which == 1));
		} else { 
			return false;
		}
}
function WidthChanged(pixelDifference) {
	var myObj = this;
	if (myObj.IsDrag == false) { return; }
	if (typeof(pixelDifference) == 'number') {
		
		myObj.IsSaved = true;
		
		//Convert everything to pixels
		var newmaxWidth = 0, mewminWidth = 0, elementWidth = 0;
		
		(myObj.container.parentNode) ? elementWidth = myObj.GetElementWidth(myObj.container.parentNode) : elementWidth = myObj.GetBrowserWidth();
		//alert(elementWidth);
		(myObj.IsPercentage == true) ? newmaxWidth = (myObj.maxWidth/100) * elementWidth : newmaxWidth =  myObj.maxWidth;
		(myObj.IsPercentage == true) ? newminWidth =  (myObj.minWidth/100) * elementWidth : newminWidth =  myObj.minWidth;
		
		var finalWidth =  myObj.containerWidth + pixelDifference;
			
		//Compare to maximum values
		if (finalWidth > newmaxWidth) { finalWidth = newmaxWidth;}
		if (finalWidth < newminWidth) { finalWidth = newminWidth;}
		
		//Stay with pixels or convert to percentages
		if (myObj.IsFixed == false) {
				finalWidth = Math.round((finalWidth/elementWidth)*100);
				myObj.container.style.width = finalWidth + "%";
				myObj.lastSavedWidth = finalWidth + "%";
		} else {
			finalWidth = Math.round(finalWidth);
			myObj.container.style.width = finalWidth + "px";
			myObj.lastSavedWidth = finalWidth + "px";
		}
		//myObj.container.innerHTML = myObj.container.style.width;
		//Match the overlay's height with the container's height
		myObj.overlay.style.height = myObj.GetElementHeight(myObj.container) + "px";
	}	
}
//Returns the Browser Width
//From: http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
function GetBrowserWidth() {
	var myWidth = 0;
	
	if( typeof( window.innerWidth ) == 'number' ) {
	//Non-IE
		myWidth = window.innerWidth - 20;
	} else if( document.documentElement && ( document.documentElement.clientWidth) ) {
	//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth-4;
	} else if( document.body && ( document.body.clientWidth) ) {
	//IE 4 compatible
		myWidth = document.body.clientWidth;
	}
	return myWidth;
}
//Returns an element's width
//Credit:  Alejandro Gervasio 2005
//From: http://www.devarticles.com/c/a/Web-Design-Standards/Matching-div-heights-with-CSS-and-JavaScript/3/
function GetElementWidth(element) { 
	if(element.offsetWidth){
	
		return element.offsetWidth;
	
	}
	
	else if(element.style.pixelWidth){
	
		return element.style.pixelWidth;
	
	} 
}	
//Returns an element's height
//Credit:  Alejandro Gervasio 2005
//From: http://www.devarticles.com/c/a/Web-Design-Standards/Matching-div-heights-with-CSS-and-JavaScript/3/
function GetElementHeight(element) { 
	if(element.offsetHeight){
	
		return element.offsetHeight;
	
	}
	
	else if(element.style.pixelHeight){
	
		return element.style.pixelHeight;
	
	} 
}
//End Class CRCWidth

//Credit: Simon Willison 2004
//From: http://simon.incutio.com/archive/2004/05/26/addLoadEvent
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}
//Adds a load event to make the link to resize the page visible
addLoadEvent(function() {
var containerCollection = CRCCollection.GetInstance();

var container1 = containerCollection.Add("sidebar", "30%", false, 10, 30, true);
var container2 = containerCollection.Add("footer", "70%", false, 50, 100, true);
var container3 = containerCollection.Add("header", "70%", false, 50, 100, true);
var container4 = containerCollection.Add("content", "70%", false, 50, 100, true);

//Setup the events
document.onmousemove = function(e) { containerCollection.GetDistance(e); }
document.onmouseup = function(e) { containerCollection.StopDrag(e); }
	
});

