﻿var ObjectPosition = {
	
	windowSize: function () {
		var myWidth = 0, myHeight = 0;
		if( typeof( window.innerWidth ) == 'number' ) {
			//Non-IE
			myWidth = window.innerWidth;
			myHeight = window.innerHeight;
		} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
			//IE 6+ in 'standards compliant mode'
			myWidth = document.documentElement.clientWidth;
			myHeight = document.documentElement.clientHeight;
		} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
			//IE 4 compatible
			myWidth = document.body.clientWidth;
			myHeight = document.body.clientHeight;
		}
		var measurements = {width: myWidth, height: myHeight};
		return measurements;
	},


	// function recursively travels from the obj up through the DOM to find out the position of an element.
	findPos: function(obj) {
		var curleft = curtop = 0;
		if (obj.offsetParent) {
			do {
				curleft += obj.offsetLeft;
				curtop += obj.offsetTop;
				obj = obj.offsetParent;
			} while (obj); // when it reaches <html> it returns '0' which results in terminating the do .. while() loop
			return [curleft, curtop]; // returns current left and top positions
		}
	},

	// Function allows more positioning options when positioning objects on a page relative to another object
	// Parameters: (obj, position)
	// obj = a jQuery object of a single element you want to position relatively to
	// position = set of key:value pairs, {top: value, left: value, bottom: value, right: value} : use maximum of two, only one horizontal and one vertical permitted at a time
	offsetPosition: function(obj, position) {
		var element = obj.get(0);
		var coords = ObjectPosition.findPos(element); // (left, top);
		if (position) {
			if (position.left) {
				coords[0] += position.left;
			} else if (position.right || position.right == 0) {
				coords[0] += obj.width() - position.right;
			} else {
				coords[0] += Math.ceil(obj.width() / 2);
			}

			if (position.top) {
				coords[1] += position.top;
			} else if (position.bottom || position.bottom == 0) {
				coords[1] += obj.height() - position.bottom;
			} else {
				coords[1] += Math.ceil(obj.height() / 2);
			}
		} else {
			coords[0] += Math.ceil(obj.width() / 2);
			coords[1] += Math.ceil(obj.height() / 2);
		}
		return coords;
	}
}