﻿/* utility functions */

// Splits a string into an Array, treating all whitespace as delimiters. Equivalent to Ruby's %w{foo bar} or Perl's qw(foo bar).
function $w(string) {
	if ($type(string) != 'string') return [];
	string = string.trim();
	return string ? string.split(/\s+/) : [];
}

function $R(start, stop) {
	if (stop <= start) return new Array();

	var ret = new Array(stop - start);
	for (var i = 0; i <= (stop - start); ++i) {
		ret[i] = i + start;
	}

	return ret;
}

function $globalDefined(variable)
{
	return (typeof(window[variable]) == "undefined") ? false: true;
}

function $isIE() {
    return /msie|MSIE/.test(navigator.userAgent) != false;
}

function $isIE6() {
    return /msie|MSIE 6/.test(navigator.userAgent) != false;
}

function $isIE8() {
    return /msie|MSIE 8/.test(navigator.userAgent) != false;
}


/* Atl_Url namespace */
var Atl_Url = function() {
	return {
		parse: function(sourceUrl)
		{
			if (($type(sourceUrl) == 'element') && (sourceUrl.nodeName == 'A')) {
			    sourceUrl = sourceUrl.href;
			}
			else if($type(sourceUrl) != 'string') {
				throw 'Only strings or anchor elements can be passed into $url()';
			}

			var urlPartNames = ["source","protocol","authority","domain","port","path","directoryPath","fileName","query","anchor"];
			var urlParts = new RegExp("^(?:([^:/?#.]+):)?(?://)?(([^:/?#]*)(?::(\\d*))?)?((/(?:[^?#](?![^?#/]*\\.[^?#/.]+(?:[\\?#]|$)))*/?)?([^?#/]*))?(?:\\?([^#]*))?(?:#(.*))?").exec(sourceUrl);
			var url = {};

			for(var i = 0; i < 10; i++){
				url[urlPartNames[i]] = (urlParts[i] ? urlParts[i] : "");
			}

			// Always end directoryPath with a trailing backslash if a path was present in the source URI
			// Note that a trailing backslash is NOT automatically inserted within or appended to the "path" key
			if(url.directoryPath.length > 0){
				url.directoryPath = url.directoryPath.replace(/\/?$/, "/");
			}

			return url;
		},
		
		build: function(parts)		
		{
		    var ret = "";
		    
		    ret += parts.protocol;
		    ret += '://';
		    ret += parts.domain;
		    
		    if (parts.port) ret += ':' + parts.port;
		    if (parts.path) ret += parts.path;
		    if (parts.query) ret += '?' + parts.query;
		    if (parts.anchor) ret += '#' + parts.anchor;
		    
		    return ret;
		}
	};
}();

/* add useful methods to existing elements */

String.implement({
	toQueryParams: function(){

		var params = {};

		this.replace('?','').split('&').each(function(kv){
		    if (kv != ''){
		        kv = kv.split('=')
		        if (kv.length == 1) params[kv[0]] = true
		        else if (kv.length == 2) params[kv[0]] = kv[1]
		   }
		});

		return params;
	},

	addQueryParams: function(params){
		return '?' + Object.toQueryString($extend(this.toQueryParams(),params.toQueryParams()));
	},

	location: function(){
		if (this.contains('?')) return this.split('?')[0]
		else return this;
	},

	params: function(){
		if (this.contains('?')) return this.split('?')[1]
		else return '';
	},

	startsWith: function(pattern) {
		return this.indexOf(pattern) === 0;
	},

	endsWith: function(pattern) {
		var d = this.length - pattern.length;
		return d >= 0 && this.lastIndexOf(pattern) === d;
	},

	empty: function() {
		return this == '';
	},

	blank: function() {
		return /^\s*$/.test(this);
	},

	_numb: '0123456789',
	_lwr: 'abcdefghijklmnopqrstuvwxyz',
	_upr: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',

	_isValid: function(parm, val) {
	    if (parm == "") return true;
	    for (var i = 0; i < parm.length; i++) {
	        if (val.indexOf(parm.charAt(i), 0) == -1) return false;
	    }
	    return true;
	},

	isNumber: function() { return this._isValid(this, this._numb); },
	isLower: function() { return this._isValid(this, this._lwr); },
	isUpper: function() { return this._isValid(this, this._upr); },
	isAlpha: function() { return this._isValid(this, this._lwr + this._upr); },
	isAlphanum: function() { return this._isValid(this, this._lwr + this._upr + this._numb); }	
});

Element._returnOffset = function(l, t) {
	var result = [l, t];
	result.left = l;
	result.top = t;
	return result;
};

Element.implement({
	visible: function() {	
	    return this.getStyle('display') != 'none';
	},

	toggle: function() {
		element = this;
		Element[Element.visible(element) ? 'hide' : 'show'](element);
		return this;
	},

	hide: function() {
		this.style.display = 'none';
		return this;
	},

	show: function() {
		this.style.display = '';
		return this;
	},

	getSiblings: function(selector) {
		return this.getParent().getChildren(selector).erase(this);
	},

	cumulativeOffset: function() {
		element = this;

		var valueT = 0, valueL = 0;
		do {
			valueT += element.offsetTop  || 0;
			valueL += element.offsetLeft || 0;
			element = element.offsetParent;
		} while (element);
		return Element._returnOffset(valueL, valueT);
	},

	getDimensions: function() {
		var display = this.getStyle('display');
		if (display != 'none' && display != null) // Safari bug
		return {width: this.offsetWidth, height: this.offsetHeight};

		// All *Width and *Height properties give 0 on elements with display none,
		// so enable the element temporarily
		var els = this.style;
		var originalVisibility = els.visibility;
		var originalPosition = els.position;
		var originalDisplay = els.display;
		els.visibility = 'hidden';
		els.position = 'absolute';
		els.display = 'block';
		var originalWidth = this.clientWidth;
		var originalHeight = this.clientHeight;
		els.display = originalDisplay;
		els.position = originalPosition;
		els.visibility = originalVisibility;
		return {width: originalWidth, height: originalHeight};
	}
});



// create an event manager to manage our Atl events.
Atl_Event_ManagerX = new Class({

    firePartialLoad: function(parentElement) {
        window.fireEvent('partialload', parentElement);
        document.fireEvent('partialload', parentElement);
    },

    fireAtlDomReady: function() {
        window.fireEvent('atldomready');
        document.fireEvent('atldomready');
    }
});

var Atl_Event_Manager = new Atl_Event_ManagerX();


function pageLoad(sender, eventArgs) {
    if (eventArgs._isPartialLoad) {
        Atl_Event_Manager.firePartialLoad($(document.body));
    }
}

/*	Useful method to add multiple event handlers to the window.onload event - should not be used directly, but is needed to call atlDomReady().
All other handlers should register with the atldomready event. */
function __addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    }
    else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

/*	Fire the mootools "domready" event replacement: "atldomready". This is needed because mootools one does not work correctly with IFRAMES */
var __atldomreadyFired = false;
function __atlDomReady() { if (!__atldomreadyFired) { __atldomreadyFired = true; Atl_Event_Manager.fireAtlDomReady(); } }
if (document.addEventListener) { // firefox
    document.addEventListener("DOMContentLoaded", function() { __atlDomReady(); }, false)
}
__addLoadEvent(function() { // catch other browsers which did hit one of the above methods
    setTimeout("__atlDomReady();", 0);
});
