// INITIALIZE LIBRARY NAMESPACE
if (typeof window.PopJavaScriptFramework == "undefined") {
	PopJavaScriptFramework = new Object();
}
// INITIALIZE VERSION NAMESPACE
if (typeof window.PopJavaScriptFramework.v1B1 == 'undefined') {
	PopJavaScriptFramework.v1B1 = new Object();
}
// SET THE VERSION ALIASED BY $POP
PopJavaScriptFramework.setVersion = function(sVersion) {
	if (typeof PopJavaScriptFramework[sVersion] == 'undefined') {
		throw new Error(
			'Config Error: The version requested (' + sVersion +
			') has not yet been instantiated or does not exist.'
		);
	} else {
		this.version = sVersion;
		$pop =	PopJavaScriptFramework[sVersion];
		// make sure dom is present
		if (typeof $pop.dom != 'undefined') { $dom = $pop.dom; }
		// make sure event is present
		if (typeof $pop.event != 'undefined') { $event = $pop.event; }
	}
}
// FIND OUT WHICH VERSION IS CURRENTLY USED BY $POP
PopJavaScriptFramework.getVersion = function() {
	return this.version;
}

/**
 * Requires that a package be included in order to run the subsequent scripts
 * @param string sObjectName The object/package to require
 * @param string sFromScript The name of the object/package/script that requires another object/package
 * @param object oScope The scope to check in - defaults to our Library. Useful for checking for global objects
 */
PopJavaScriptFramework.require = function(sObjectName,sFromScript, oScope) {
	var scope = (typeof oScope == 'undefined') ? PopJavaScriptFramework[PopJavaScriptFramework.getVersion()] : oScope ;
	if (typeof scope[sObjectName] == 'undefined') {
		throw new Error(
			'Inclusion Error: ' +
			'You have not included [' + sObjectName + '] in your script references, ' +
			'which is required before [' + sFromScript + ']');
	}
}

/**
 * Extends the functionality of one object with the functionality of another
 * @param object oDestination The object to extend
 * @param object oSource The object to extend off of
 */
Object.extend = function(oDestination, oSource) {
	for (var property in oSource) {
		oDestination[property] = oSource[property];
	}
	return oDestination;
}

/**
 * Extends functionality but does not override if already present in oDestination
 * @param object oDestination The Object to augment
 * @param object oSource The Object Literal to augment oDestination with.
 */
Object.augment = function(oDestination, oSource) {
	for (var property in oSource) {
		if (typeof oDestination[property] == "undefined") {
			oDestination[property] = oSource[property];
		}
	}
	return oDestination;
}


/**
 * Holds reuseable bits of code for use by Library Classes and Functions
 * @author	Dan Dean
 */
PopJavaScriptFramework.v1B1.snippet = {
	// Used by String.extractScripts, String.stripScripts
	ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)'
}

/**
 * Augment the browser String capabilities, where necessary
 * Taken directly from prototype.js
 */
Object.augment(String.prototype, {
	/**
	 * Remove whitespace at the front and back of a String
	 * FROM: http://kasimchen.com/2005/03/27/javascript-trim/#comment-789
	 */
	trim: function() {
		return this.replace(/^\s*|\s*$/g,'');
	},
	
	stripTags: function() {
		return this.replace(/<\/?[^>]+>/gi, '');
	},

	stripScripts: function() {
		return this.replace(new RegExp(PopJavaScriptFramework.v1B1.snippet.ScriptFragment, 'img'), '');
	},
	
	extractScripts: function() {
		var matchAll = new RegExp(PopJavaScriptFramework.v1B1.snippet.ScriptFragment, 'img');
		var matchOne = new RegExp(PopJavaScriptFramework.v1B1.snippet.ScriptFragment, 'im');
		return (this.match(matchAll) || []).map(function(scriptTag) {
			return (scriptTag.match(matchOne) || ['', ''])[1];
		});
	},
	
	evalScripts: function() {
		return this.extractScripts().map(eval);
	},

	escapeHTML: function() {
		var div = document.createElement('div');
		var text = document.createTextNode(this);
		div.appendChild(text);
		return div.innerHTML;
	},

	unescapeHTML: function() {
		var div = document.createElement('div');
		div.innerHTML = this.stripTags();
		return div.childNodes[0] ? div.childNodes[0].nodeValue : '';
	},
	
	/**
	 * Prototype.js version of this was dependent on other Prototype.js Objects.
	 * Rewritten for Library independence.
	 * @author Dan Dean
	 * @return Object containing name/value pairs
	 * @return Value of supplied "key"
	 * @usage alert("firstname=dan&lastname=dean".toQueryParams()["lastname"]);
	 */
	toQueryParams: function() {
		var query_array =	this.substr(this.indexOf("?") + 1).split("&");
		var queryObj =		{};
		var query_count =	query_array.length;
		for (var i=0; i < query_count; i++) {
			query_pair = query_array[i].split("=");
			queryObj[query_pair[0]] = query_pair[1];
		}
		return queryObj;
	},
	
	/**
	 * Add/Update query parameter in a string
	 * Example: 'index.aspx?one=1'.addQueryParams('two',2) will return:
	 * 'index.aspx?one=1?two=2'
	 */
	addQueryParameter: function(key,value) {
		try { // get string before query params
			var front = this.match(/^.*[\?]/)[0];
		} catch (e) {
			var front = '';
		}
		var pairs = this.toQueryParams();
		pairs[key] = value;
		var i = 0;
		for (var j in pairs) {
			if (typeof pairs[j] != 'undefined') {
				front += (i>0) ? '&' : '';
				front += (j + '=' + pairs[j]); 
				i++;
			}
		}
		return front;
	},
	
	removeQueryParameter: function(key) {
		try { // get string before query params
			var front = this.match(/^.*[\?]/)[0];
		} catch (e) {
			var front = '';
		}
		var pairs = this.toQueryParams();
		for (var i in pairs) {
			if (i != key) {
				front = front.addQueryParameter(i,pairs[i]);
			}
		}
		return front;
	},
	
	toArray: function() {
		return this.split('');
	},
	
	camelize: function() { // converts css style props to js style props: 'border-color' = 'borderColor'
		var oStringList = this.split('-');
		if (oStringList.length == 1) return oStringList[0];
			
		var camelizedString = this.indexOf('-') == 0
			? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) 
			: oStringList[0];
			
		for (var i = 1, len = oStringList.length; i < len; i++) {
			var s = oStringList[i];
			camelizedString += s.charAt(0).toUpperCase() + s.substring(1);
		}
		
		return camelizedString;
	},

	inspect: function() {
		return "'" + this.replace('\\', '\\\\').replace("'", '\\\'') + "'";
	},
	
	/**
	 * C# style String.format();
	 * @param String strings Arguments to format the String with.
	 * Example: "Rock and {0} {1}!".format("Roll", "Forever") will output "Rock and Roll Forever!".
	 */
	format: function(strings) {
			var val = this;
			for (var i=0; i < arguments.length; i++) {
				// Since we're building this on the fly, we have to double escape. I think that's the case, anyways.
				var regex = new RegExp("\\{" + i + "\\}", "g");
				val = val.replace(regex, arguments[i]);
			}
			return val;
	},
	contains: function(re, str) {
		if (str.search(re) != -1) {
			return true;
		} else {
			return false;
		}
	},
	getHostname: function() {
		return this.toString().replace(/^\w+\:\/\//,'').split('/')[0];
	}
});

/**
 * Augment the browser Function capabilities, where necessary
 */
Object.augment(Function.prototype, {
	// both call() and apply() are need by IE5 for some of the Array methods to work.
	// FROM: http://www.browserland.org/scripts/dragdrop/
	apply: function(scope, args) {
		if (!args) args = [];
		var index = 0, result;
		do { -- index } while (typeof scope[index] != "undefined");
		scope[index] = this;
	
		switch (args.length) {
			case 0:
				result = scope[index]();
				break;
			case 1:
				result = scope[index](args[0]);
				break;
			case 2:
				result = scope[index](args[0], args[1]);
				break;
			case 3:
				result = scope[index](args[0], args[1], args[2]);
				break;
			case 4:
				result = scope[index](args[0], args[1], args[2], args[3]);
				break;
			default:
				result = scope[index](args[0], args[1], args[2], args[3], args[4]);
				break;
		}
	
		delete scope[index];
		return result;
	},

	// FROM: http://www.browserland.org/scripts/dragdrop/
	call: function(scope) {
		var args = new Array(Math.max(arguments.length-1, 0));
		for (var i = 1; i < arguments.length; i++)
			args[i-1] = arguments[i];
		return this.apply(scope, args);
	}
});

/**
 * Augment the browser Array capabilities, where necessary
 * For a full explanation of JS Array capabilities, see the Array documentation:
 * http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference
 */
Object.augment(Array.prototype, {
	// FROM DECONCEPT
	// Adds one or more elements to the end of an array and returns the new length of the array.
	push: function(item) { // IE5
		this[this.length] = item;
		return this.length;
	},

	/**
	 * Adds and/or removes elements from an array.
	 * @param Number index	Index at which to start changing the array.
	 * @param Number count	An integer indicating the number of old array elements to remove.
	 * 				 		If count is 0, no elements are removed. In this case, you should specify at least one new element.
	 * @return Array An array containing the removed elements.
	 * FROM http://www.webreference.com/dhtml/column33/13.html
	 */
	splice: function(index,count){
		if(arguments.length == 0) return index;
		if(typeof index != "number") index = 0;
		if(index < 0) index = Math.max(0,this.length + index);
		if(index > this.length) {
			if(arguments.length > 2) index = this.length;
			else return [];
		}
		if(arguments.length < 2) count = this.length-index;
		count = (typeof count == "number") ? Math.max(0,count) : 0;
		removeArray = this.slice(index,index+count);
		endArray = this.slice(index+count);
		this.length = index;
		for(var i=2;i < arguments.length;i++){
			this[this.length] = arguments[i];
		}
		for(var i=0;i < endArray.length;i++){
			this[this.length] = endArray[i];
		}
		return removeArray;
	},

	/**
	 * Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
	 * @param Object obj Needle
	 * @param Number si Index to start search. Optional.
	 * FROM http://erik.eae.net
	 */
	indexOf: function (obj, si) {
		if (si == null) {
			si = 0;
		} else if (si < 0) {
			si = Math.max(0, this.length + si);
		}
		for (var i=si; i < this.length; i++) {
			if (this[i] === obj) { return i; }
		}
		return -1;
	},

	/**
	 * Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.
	 * @param Object obj Needle
	 * @param Number si Index to start search. Optional.
	 * FROM http://erik.eae.net
	 */
	lastIndexOf: function (obj, si) {
		if (si == null) {
			si = this.length - 1;
		} else if (si < 0) {
			si = Math.max(0, this.length + si);
		}
		for (var i = si; i >= 0; i--) {
			if (this[i] === obj) { return i; }
		}
		return -1;
	},

	/**
	 * Calls a function for each element in the array.
	 * @param Function f Callback function to apply to each element in the array.
	 * @param Object obj Optional object to apply function to. Defaults to 'this'.
	 * FROM http://erik.eae.net
	 */
	forEach: function (f, obj) {
		obj = (obj != null) ? obj : this; // IE5 [dd]

		var l = this.length;
		for (var i = 0; i < l; i++) {
			f.call(obj, this[i], i, this);
		}
	},

	/**
	 * Creates a new array with all of the elements of this array for which the provided filtering function returns true.
	 * @param Function f Callback function to apply to each element in the array.
	 * @param Object obj Optional object to apply function to. Defaults to 'this'.
	 * FROM http://erik.eae.net
	 */
	filter: function (f, obj) {
		obj = (obj != null) ? obj : this; // IE5 [dd]

		var l = this.length;
		var res = [];
		for (var i = 0; i < l; i++) {
			if (f.call(obj, this[i], i, this)) {
				res.push(this[i]);
			}
		}
		return res;
	},
	// Creates a new array with the results of calling a provided function on every element in this array.
	map: function (f, obj) {
		obj = (obj != null) ? obj : this; // IE5 [dd]

		var l = this.length;
		var res = [];
		for (var i = 0; i < l; i++) {
			res.push(f.call(obj, this[i], i, this));
		}
		return res;
	},
	// Determines the existance of the needle in the stack
	contains: function (obj) {
		return this.indexOf(obj) != -1;
	},
	// Duplicates the subject array to a new array: var blah = myArray.copy()
	copy: function (obj) {
		return this.concat();
	},
	// Duplicates the passes array into the new array: var blah = new Array(); blah.copyFrom(arguments);
	// Useful for copying non Array types into arrays
	copyFrom: function(arr) {
		for (var i=0; i<arr.length; i++) {
			this.push(arr[i]);
		}
	},
	// Add something to stack at the specified index.
	insertAt: function (obj, i) {
		this.splice(i, 0, obj);
		// return this; // should this be here?
	},
	// Add something at the first index of obj2. Bumps everything from obj2 to the end of the stack down one index.
	// If obj2 is not found, obj is added to the end of the array
	insertBefore: function (obj, obj2) {
		var i = this.indexOf(obj2);
		if (i == -1) {
			this.push(obj);
		} else {
			this.splice(i, 0, obj);
		}
	},
	// Removes needle at specified index.
	removeAt: function (i) {
		this.splice(i, 1);
	},
	// Removes the first occurence of the supplied obj.
	remove: function (obj) {
		var i = this.indexOf(obj);
		if (i != -1) {
			this.splice(i, 1);
		}
	}
});

PopJavaScriptFramework.v1B1.objectTemplate = {
	versionable: function() {
		this.major = null;
		this.minor = null;
		this.rev = null;
	
		this.toString = function() {
			return this.major + '.' + this.minor + '.' + this.rev;
		}
		this.set = function(sVersion) {
			var v = sVersion.split('.');
			this.major =	parseInt(v[0]) || 0;
			this.minor =	parseInt(v[1]) || 0;
			this.rev =		parseInt(v[2]) || 0;
		}
		this.test = function(sVersion) { // Ex: 1.8, '1.8.1', 500, [5,2,6]
			var v = sVersion.toString().split('.');
			for (var i=0; i<3; i++) {
				v[i] = parseInt(v[i]) || 0;
			}
			switch (true) {
				case (v[0] < this.major):
					return true;
				case (v[0] <= this.major && v[1] < this.minor):
					return true;
				case (v[0] <= this.major && v[1] <= this.minor && v[2] <= this.rev):
					return true;
				default:
					return false;
			}
		}
	}
}

// ======================================================================= //
/**
 * CONFIGURATION SETTINGS
 * Must be set in order to utilize dynamic package loading
 * When POP.Core is available you can uncomment the below variables and change
 * this to an aspx file. The import statement is at the very top of this page
 * and SHOULD REMAIN COMMENTED OUT.
 */
PopJavaScriptFramework.v1B1.config = {
	root: root,
	rootSecure: rootSecure,
	rootVirtual: rootVirtual,
	cookieDomain: '.popmultimedia.com'
}
/**
 * Google Analytics Configuration information.
 */
PopJavaScriptFramework.v1B1.config.analytics = {
	enabled: true,
	clickLogging: true,	// Print clicklog instead of tracking?
	domains: [				// You must put all possible live domains in the domains array
		location.hostname,
		PopJavaScriptFramework.v1B1.config.root.getHostname(),
		'dandean.popmultimedia.com',
		'popmultimedia.com',
		'dandean'
	],
	params: {			// GA Variables
		_uacct: "UA-331898-1",
		_udn: "popmultimedia.com",
		_userv: 2
	}
}
// ======================================================================= //


// SET THE DEFUALT VERSION
PopJavaScriptFramework.setVersion('v1B1');
