self.wh = {};

wh.Common = {
	
	// find all image input elements and sets the mouseover and mouseout
	// handlers to swap the rollover images.
	// By convention all images in the html source must be of the form
	// *_off.* and there must exist a second image of the form
	// *_on.* in the same directory to swap it with.
	// NOTE for mozilla (firefox) this function attaches the event and
	// for IE it replaces any existing event.
	attachRollovers: function() {
		var inputElements = document.getElementsByTagName('input');
		
		for (var i = 0; i < inputElements.length; i++) {
			
			// is this a rollover button?
			if(wh.Common.hasCssClass(inputElements[i], 'withRollover')) {
				
				// does the rollover button have an appropriately 
				// named image for the 'off' state?
				if (inputElements[i].src.indexOf('_off.') != -1) {

					// then save a copy of the image.					
					inputElements[i].offImage = new Image();
					inputElements[i].offImage.src = inputElements[i].src;
						
					// create and preload an image with the 'on' state src.
					inputElements[i].onImage = new Image();
					inputElements[i].onImage.src = inputElements[i].src.replace(/_off\./, '_on.');

					// attach/replace the actual rollover functions.
					wh.Common.replaceEvent(inputElements[i],'mouseover', 						
						function () {
							wh.Common.changeSrc(this, this.onImage.src);
						}
					);
					// attach/replace the actual rollover functions.
					wh.Common.replaceEvent(inputElements[i],'mouseout', 
						function () {
							wh.Common.changeSrc(this, this.offImage.src);
						}
					);
				}
			}
		}
	},
		
	hasCssClass: function(o, css_class) {
		return o.className.match(new RegExp("\\b" + css_class + "\\b")) == css_class;
	},
	addCssClass: function(o, css_class) {
        if (!o || typeof o != "object") {
            return false;
        }
        if (o.className == null) {
            return false;
        }
        if (this.hasCssClass(o, css_class)) {
            return false;
        }
        o.className = o.className.trim() + " " + css_class.trim();
        return true;
    },
    removeCssClass: function(o, css_class) {
        if (!o || typeof o != "object") {
            return false;
        }
        if (!o.className) {
            return false;
        }
        if (!this.hasCssClass(o, css_class)) {
            return false;
        }
        o.className = o.className.replace(css_class.trim(), "").trim();
        return true;
    },
    setCssClass: function(o, css_class) {
        if (!o || typeof o != "object") {
            return false;
        }
        if (!o.className) {
            return false;
        }
        o.className = css_class;
        return true;
    },
    getClientDimensions: function() {
        var x,y;
        if (self.innerHeight) {
                x = self.innerWidth;
                y = self.innerHeight;
        }
        else if (document.documentElement && document.documentElement.clientHeight) {
                x = document.documentElement.clientWidth;
                y = document.documentElement.clientHeight;
        }
        else if (document.body) {
                x = document.body.clientWidth;
                y = document.body.clientHeight;
        }
        return { "x":x, "y":y };
    },
    getVerticalScrollPosition: function() {
        var de = document.documentElement;
        return self.pageYOffset || (de && de.scrollTop) || document.body.scrollTop;
    },
	getAbsolutePosition: function(o, stop_at_element) {
        if (!o || typeof o != "object") {
            return false;
        }
        if (!o.offsetParent) {
            return false;
        }
        var position = new Object();
        position["left"] = parseInt(o.offsetLeft);
        position["top"] = parseInt(o.offsetTop);
        while (o = o.offsetParent) {
            if (o == stop_at_element) {
                break;
            }
            position["left"] += parseInt(o.offsetLeft);
            position["top"] += parseInt(o.offsetTop);
        }
        return position;
    },
    getParentNodeByTagName: function(o, parent_tag) {
        if (!o || typeof o != "object") {
            return false;
        }
        while (o = o.parentNode) {
            if (o.nodeType != 1) {
                continue;
            }
            if (o.tagName.toLowerCase() == parent_tag.toLowerCase()) {
                return o;
            }
        }
        return null;
    },
    getElementsByTagNames: function(o, list) {
        if (!o || typeof o != "object") {
            return false;
        }
        var tag_names = list.split(",");
        var results = new Array();
        for (var i=0; i<tag_names.length; i++) {
            var elements = o.getElementsByTagName(tag_names[i]);
            for (var j=0, k=elements.length; j<k; j++) {
                results.push(elements[j]);
            }
        }
        return results;
    },
    getElementsByTagNameClass: function(o, tag_name, css_class) {
        if (!o || typeof o != "object") {
            return false;
        }
        var child_elements = new Array();
        var elements = o.getElementsByTagName( tag_name );
        for (var i = 0, j = elements.length; i<j; i++) {
            if (this.hasCssClass(elements[i], css_class) || css_class == "" || css_class == null) {
                child_elements.push(elements[i]);
            }
        }
        return child_elements;
    },
    getParentByStyleProperty: function(o, property, value) {
        if (!o || typeof o != "object") {
            return false;
        }
        while (o = o.parentNode) {
            if (this.getComputedStyle(o, property) == value) {
                return o;
            }
        }
        return null;
    },
    getComputedStyle: function(o, property) {
        if (!o || typeof o != "object") {
            return false;
        }
        var property_value = null;
        if (o.currentStyle) {
            property_value = o.currentStyle[property];
        } else if (window.getComputedStyle) {
            property_value = document.defaultView.getComputedStyle(o,null).getPropertyValue(property);
        }
        return property_value;
    },
    removeAllChildren: function(o) {
        if (!o || o == null) {
            return false;
        }
        while (o.hasChildNodes()) {
            o.removeChild(o.firstChild);
        }
    },
	changeSrc: function(o, newSrc) {
		if (!o) {
			return false;
		}
		if (!o.src) {
	        return false;
	    }
	    o.src = newSrc;
	    return true;
	},
	
	// use add event where your fuction needs to work in IE but the function does not make
	// use of the 'this' object.
	addEvent: function(element, ev_type, fn) {
		if (element.addEventListener) {
			
			element.addEventListener(ev_type, fn, false);
	        return true;
	        
	    } else if (element.attachEvent) {
		    
		    // this is the key line for IE. Any function attached here will not be able to make
		    // use of 'this'. This is a design flaw in MSFTs attachEvent function.
	        var r = element.attachEvent('on' + ev_type, fn);
	        return r;
	        
	    } else {
	        element['on' + ev_type] = fn;
	    }
	},

	// use replace event where your fuction to pass *must* make use
	// of the 'this' object, and you want it to work in IE	
	// NOTE: despite being named replace event, for firefox this method
	// still adds the event to the object.
	replaceEvent: function(element, ev_type, fn) {
		if (element.addEventListener) {
			
			element.addEventListener(ev_type, fn, false);
	        return true;
	        
	    } else {
		    
		    // this is the key line for IE. A function given here *can* make use of 'this'
		    // because the attachment is a simple assignment. Unfortunately this means
		    // any previously attached functions will be deleted and overwritten.
		    // That's why this method is called 'replaceEvent'
	        element['on' + ev_type] = fn;
	        
	    }
	}
}

wh.Implementation = {
	
	openInNewWindow: function(e) {
		var event;
		if (!e) event = window.event;
		else event = e;
		// Abort if a modifier key is pressed
		if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) {
			return true;
		}
		else {
			// Change "_blank" to something like "newWindow" to load all links in the same new window
			var newWindow = window.open(this.getAttribute('href'), '_blank');
			if (newWindow) {
				if (newWindow.focus) {
					newWindow.focus();
				}
				return false;
			}
			return true;
		}		
	},
	
	getNewWindowLinks: function() {
		// Check that the browser is DOM compliant
		if (document.getElementById && document.createElement && document.appendChild) {
			// Change this to the text you want to use to alert the user that a new window will be opened
			var strNewWindowAlert = " (opens in a new window)";
			// Find all links
			var links = wh.Common.getElementsByTagNames(document,'a');
			var objWarningText;
			var link;
			for (var i = 0; i < links.length; i++) {
				link = links[i];
				// Find all links with a class name of "newwin"
				if (/\bnewwin\b/.test(link.className)) {
					// Create an em element containing the new window warning text and insert it after the link text
					//objWarningText = document.createElement("em");
					//objWarningText.appendChild(document.createTextNode(strNewWindowAlert));
					//link.appendChild(objWarningText);
					link.title = "This link will open in a new window";
					link.onclick = wh.Implementation.openInNewWindow;
				}
			}
			objWarningText = null;
		}
	},
	
	fadeIn: function(o) {
		if (!document.getElementById || !document.getElementById(o)) return false;
		subject = document.getElementById(o)
		var temp = parseFloat(subject.style.opacity);
		if (temp < 1) {
			newval = temp + 0.1;
			subject.style.opacity = newval;
			setTimeout( function() { wh.Implementation.fadeIn(o) }, 66);
		} else {
			subject.style.opacity = 1;	
		}
	},	
	fadeTwitter: function() {
		o = "twitTwitTwooo";
		subject = document.getElementById(o)
		subject.style.opacity = 0;
		wh.Implementation.fadeIn(o);
	}
	
}

String.prototype.trim = function () {
    return this.replace(/^\s*|\s*$/g,'');
}

// Load Events
wh.Common.addEvent(window, 'load', wh.Implementation.getNewWindowLinks);

/* Sifr Headings
-----------------------------------*/
	sIFR.delayCSS  = true;
	
	var square = {
	  src: '/assets/fonts/square.swf'
	};
	
	sIFR.activate(square); // From revision 209 and onwards
	
	sIFR.replace(square, {
		selector: 'h1'
		,css: [
		  '.sIFR-root { color: #A9253B; text-transform: lowercase; }'
		  ,'em { display: block; font-size: 55px; font-style: normal;}'
		]
	});





/* Twitter
-----------------------------------*/
function relative_time(time_value) {
	var values = time_value.split(" ");
	time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
	var parsed_date = Date.parse(time_value);
	var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
	delta = delta + (relative_to.getTimezoneOffset() * 60);
	
	var blurb = " I was... ";
	
	if (delta < 60) {
	  return "I'm currently ";
	} else if(delta < 120) {
	  return 'about a minute ago'+blurb;
	} else if(delta < (45*60)) {
	  return (parseInt(delta / 60)).toString() + ' minutes ago'+blurb;
	} else if(delta < (90*60)) {
	  return 'about an hour ago'+blurb;
	} else if(delta < (24*60*60)) {
	  return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago'+blurb;
	} else if(delta < (48*60*60)) {
	  return '1 day ago'+blurb;
	} else {
	  return (parseInt(delta / 86400)).toString() + ' days ago'+blurb;
	}
}

function twitterCallback(obj) {		
	if (!document.getElementById) return false;
	if(document.getElementById("home")) {
		
		// Setup content holder
		twitPara = document.createElement("p");
		twitPara.id = "twitTwitTwooo";
		twitImg = document.createElement("span");
		twitImg.id = "twitThumb";
		twitStatus = document.createElement("span");
		twitStatus.id = "my_twitter_status";
		twitTime = document.createElement("span");
		twitTime.id = "my_twitter_status_time";			
		twitPara.appendChild(twitImg);
		twitPara.appendChild(twitTime);
		twitPara.appendChild(twitStatus);			
		
		// Insert twitter block
		document.getElementById("header").appendChild(twitPara);
		
		
		// Do what twitter does and populate the twitter block
		var id = obj[0].user.id;
		document.getElementById('my_twitter_status').innerHTML = obj[0].text;
		document.getElementById('my_twitter_status_time').innerHTML = relative_time(obj[0].created_at);
		
		// Fade it in
		wh.Common.addEvent(window, 'load', wh.Implementation.fadeTwitter);
	}
}
	
	