var DUMAS = jQuery.extend( DUMAS,{

	/****
	* takes a url (for example from an anchor tags href attribute) calls jQuery.ajax with it and whatever other options are defined
	******/
	ajax:function(options)
	{
		var qsIndex = options.url.indexOf('?');
		if(qsIndex >= 0) {
			var fullUrl = options.url;
			options.url = fullUrl.substring(0, qsIndex);
			options.data = fullUrl.substring(qsIndex + 1) + "&js=yes";
		}
		else {
			options.data = "";
		}
		return $.ajax(options);
	},

	loadCss:function(href, condition) {
		if(!condition || DUMAS.browser(condition)) {
			var head = document.getElementsByTagName('head')[0];
			for(var i = 0; i < head.childNodes.length ; i++) {
				if(head.childNodes[i].nodeName.toLowerCase() == 'link' && head.childNodes[i].href.indexOf(href) >= 0) {
					return;
				}
			}
			var oLink = document.createElement("link")
			oLink.href = href;
			oLink.rel = "stylesheet";
			oLink.type = "text/css";
			head.appendChild(oLink);
		}
	},

	loadJs:function(src) {
		var head = document.getElementsByTagName('head')[0];
		for(var i = 0; i < head.childNodes.length ; i++) {
			if(head.childNodes[i].nodeName.toLowerCase() == 'script' && head.childNodes[i].src.indexOf(src) >= 0) {
				return;
			}
		}

		var oLink = document.createElement("script")
		oLink.src = src;
		oLink.type = "text/javascript";
		head.appendChild(oLink);
	},

	param:function(name) {
		var results = new RegExp("[\\?&]"+name+"=([^&#]*)").exec( window.location.href );
		return results == null ? null : results[1];
	},

	browser:function(browserString) {
		return (browserString == 'ie'      && $.browser.msie) ||
			   (browserString == 'mozilla' && $.browser.mozilla) ||
			   (browserString == 'safari'  && $.browser.safari) ||
			   (browserString == 'mac'     && navigator.userAgent.indexOf('Mac') >= 0) ||
			   (browserString == 'ie6' && $.browser.msie && parseInt($.browser.version) == 6) ||
			   (browserString == 'ie7' && $.browser.msie && parseInt($.browser.version) == 7) ||
			   (browserString == 'pc_mozilla' && $.browser.mozilla && navigator.userAgent.indexOf('Windows') >= 0);
	},
	//thanks dougie fresh crockford
	isArray:function(obj) {
		return obj && typeof obj === 'object' && typeof obj.length === 'number' && typeof obj.splice === 'function'
			&& !(obj.propertyIsEnumerable('length'));
	},
	//these replace/add any prop in add object to src object, return a new object... useful for settings objects esp.
	//first, shallow copy a property by assignment UNLESS they are both non-array objects (i.e. assumed to be settings), then merge their properties
	copyProperties: function(dest, src) {
		for(var prop in src) {
			if(src.hasOwnProperty(prop)) {
				dest[prop] =
					(typeof src[prop] === 'object' && typeof dest[prop] === 'object' && !this.isArray(src[prop]) && !this.isArray(dest[prop])) ?
						DUMAS.addProperties(dest[prop], src[prop]) :
						src[prop];
			}
		}
	},
	addProperties: function(src, add) {
		var dest = {};
		this.copyProperties(dest, src);
		this.copyProperties(dest, add);
		return dest;
	},
//	this thing is for doubleclick
	dblClickOrd : Math.random()*10000000000000000,

	clientWidth : function(parentWindow) {

        var theWindow = parentWindow ? window.top.window : window;
        var theDocument = parentWindow ? window.top.window.document : document;

        return this.f_filterResults (
			theWindow.innerWidth ? theWindow.innerWidth : 0,
			theDocument.documentElement ? theDocument.documentElement.clientWidth : 0,
			theDocument.body ? theDocument.body.clientWidth : 0
		);
	},
	clientHeight : function() {
	return this.f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
		);
	},
	scrollLeft: function() {
	return this.f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
		);
	},
	scrollTop : function(parentWindow) {

        var theWindow = parentWindow ? window.top.window : window;
        var theDocument = parentWindow ? window.top.window.document : document;

        return this.f_filterResults (
			theWindow.pageYOffset ? theWindow.pageYOffset : 0,
			theDocument.documentElement ? theDocument.documentElement.scrollTop : 0,
			theDocument.body ? theDocument.body.scrollTop : 0
			);
	},
	f_filterResults : function(n_win, n_docel, n_body){
		var n_result = n_win ? n_win : 0;
		if (n_docel && (!n_result || (n_result > n_docel))){
			n_result = n_docel;
		}
		return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
	},
	textColorFade : function( node, args){
		/*will hilite text to newColor then wait (pauseTime arg) fade back to original color
		or use start color, use a shorter or longer fadeStepTime to speed up or slow the fade*/
		args = jQuery.extend({
			startColor : node.css('color'),
			newColor : '#ffffff',
			fadeStepTime : 10,
			pauseTime : 3000
		}, args);
		if ( args.startColor.indexOf('rgb') == -1){ //if in rgb format convert to hex
			args.startColor = convertToRGB(args.startColor);
		}

		var orgColorStr = args.startColor;

		var parseRGB = /(?:.([0-9]+),)(?:.([0-9]+),)(?:.([0-9]+)\))/;
		var oResult = parseRGB.exec( orgColorStr);
		var oR = oResult[1];
		var oG = oResult[2];
		var oB = oResult[3];
		node.css('color', args.newColor);
		var newColorStr = convertToRGB( node.css('color') );
		var newResult = parseRGB.exec(newColorStr);

		var r = newResult[1];
		var g = newResult[2];
		var b = newResult[3];
		function convertToRGB(hexColor){
			if( hexColor.indexOf('rgb') == -1){//make sure its not rgb
				var rgbColor, i, hexArray;
				// kill the #, if it has it
				hexColor = (hexColor.charAt(0)=='#') ? hexColor = hexColor.substring(1,7) : hexColor;
				hexArray =[];
				for (i=0; i < hexColor.length ;i=i+2){
					hexArray.push( parseInt( hexColor.substring(i,i+2),16) );
				}
				rgbColor = "rgb(" + hexArray.join(', ') +")";
			} else {//if it is rgb - send that shiz back
				rgbColor = hexColor;
			}
			return rgbColor;
		}

		function step(){
			node.css('color','rgb(' + r +','+ g +','+ b +')' );
			//red
				if (r - oR > 0){
					r--;
				} else if (r - oR < 0){
					r++;
				}
			//green
				if (g - oG > 0){
					g--;
				} else if (g - oG < 0){
					g++;
				}
			//blue
				if (b - oB > 0){
					b--;
				} else if (b - oB < 0){
					b++;
				}
				if ( !(r==oR && g==oG && b ==oB)){
					setTimeout(step, args.fadeStepTime);
				} else{
					if (args.onComplete !== undefined){
						args.onComplete();
					}
				}
		};
		setTimeout(step, args.pauseTime);
	}
});

//module code
(function() {

var loadedModules = {},
	pendingModules = {},
	firstModules = [],
	lastModules = [],
	normalModules = [],
	documentReady = false,
	contextReady = false,
	baseModulesExecuted = false,
	pendingRequests = -1;

function registerModule() {
	var module, options;

	if(arguments.length == 3) {
		options = {
			name: arguments[0],
			init: arguments[1],
			handleHtml: arguments[2]
		}
	} else {
		options = arguments[0];
	}

	if(!loadedModules[options.name]) {
//		console.log('module ' + options.name + ' loaded');
		module = {
			name: options.name,
			init: options.init,
			handleHtml: options.handleHtml
		};
		loadedModules[options.name] = module;
		if(pendingModules[options.name]) {
			delete pendingModules[options.name];
			pendingModules.length--;
		}

		//todo:jmarnell depends on?
		(options.first ? firstModules : options.last ? lastModules : normalModules).push(module);
		executeModulesIfReady(module);
	}
}

function requireModule(name, url) {
	if(!loadedModules[name] && !pendingModules[name]) {
		//console.log('loading required module: ' + name);
		pendingModules[name] = true;
		pendingModules.length = (pendingModules.length || 0) + 1;
		jQuery.getScript(url); //todo:jmarnell make sure this doesn't block progressive rendering + is proper jquery method for loading a .js
	}
}

function executeModulesIfReady(newModule) {
	if((pendingRequests === -1 || (pendingRequests === 0 && pendingModules.length)) && documentReady && contextReady) {
		if(newModule && pendingRequests === -1) {
			executeModule(newModule);
		} else {
			executeModules();
		}
		pendingRequests = -1;
	}
}

function executeModule(module, root) {
	//console.log('executing ', module, ' on ', root);
	if(!module.initialized) {
		module.initialized = true;
		if(module.init) {
			module.init(DUMAS);
		}
	}
	if(module.handleHtml) {
		module.handleHtml(root || $('body'));
	}
}

function executeModuleGroup(group, modules, root) {
	//todo:jmarnell execute dependencies?
	for(var i = 0; i < group.length; i++) {
		if(modules[group[i].name]) {
			executeModule(group[i], root);
		}
	}
}

function executeModules(root, moduleList) {
	var modules, i;
	if(arguments.length === 1 && typeof root === 'string') {
		moduleList = root;
		root = undefined;
	}

	if(moduleList) {
		modules = {};
		moduleList = moduleList.split(',');
		for(i = 0; i < moduleList.length; i++) {
			modules[moduleList[i]] = true;
		}
	} else {
		modules = loadedModules;
	}
	//console.log(modules.toSource());
	executeModuleGroup(firstModules, modules, root);
	executeModuleGroup(normalModules, modules, root);
	executeModuleGroup(lastModules, modules, root);
}

window.DUMAS = jQuery.extend(window.DUMAS, {

	//modules should register themselves
	registerModule: registerModule,

	//private, don't use these... the JSP does
	_requireModule: requireModule,
	_setContextReady: function() { contextReady = true; executeModulesIfReady(); },
	_ctxData:function(context, data) {
		if(context) {
			DUMAS[context] = data;
		} else {
			jQuery.extend(DUMAS, data);
		}
	},
	_tagData:function(jq, name, val) {
		var prop, dom, data;
		if(typeof jq === 'string') {
			jq = $('#' + jq);
		}
		if(val !== undefined) {
			data = {};
			data[name] = val;
		} else {
			data = name;
		}
		//console.log(data.toSource());
		jq.each(function() {
			jQuery.data(this, 'dumas', jQuery.extend(jQuery.data(this, 'dumas'), data));
			for(prop in data) {
				$(this).attr(prop, data[prop]);
			}
			//console.log(jQuery.data(dom, 'dumas').toSource());
		});
	}
});

//function bindOver() {
//	var type = arguments[0].indexOf('.') >= 0 ? arguments[0] : arguments[0] + '.dumas';
//	this.unbind(type);
//	this.addBind(type, arguments.length > 2 ? arguments[1] : undefined, arguments[arguments.length - 1]);
//	return this;
//}

//disable jQuery event accumulation by default
//jQuery.fn.addBind = jQuery.fn.bind;
//jQuery.jqAjax = jQuery.ajax;
//function ajaxRequest(options) {
//	var success = options.success;
//
//	//jQuery.getScript is the only method we don't want to intercept, since it's just meant to load a .js file,
//	//i.e. there should be no html added to the page
//	if(options.dataType !== 'script') {
//		console.log('requesting url ' + options.url);
//		pendingRequests = Math.max(pendingRequests + 1, 1);
//		options.success = function() {
//			if(success) {
//				success.apply(options, arguments);
//			}
//			pendingRequests--;
//			console.log('finished request');
//			executeModulesIfReady();
//		}
//	}
//	//options.cache = false; //todo:jmarnell get rid of this after done debugging with it
//	jQuery.jqAjax(options);
//}
//jQuery.fn.bind = bindOver;
//jQuery.jq_ajax = jQuery.ajax;
//jQuery.ajax = ajaxRequest;
//jQuery.each(('get,getScript,getJSON,post').split(','), function(i, fn) {
//	jQuery['jq_' + fn] = function() {
//		jQuery.ajax = jQuery.jq_ajax;
//		jQuery[fn].apply(this, arguments);
//		jQuery.ajax = ajaxRequest;
//	}
//});


jQuery.fn.extend({
	update: function(moduleList) {
		executeModules(this, moduleList);
		return this;
	},
	set: function(a1, a2) {
		DUMAS._tagData(this, a1, a2);
		return this;
	},
	settings : function(data) {
		var stored, search,	results, prop, numProps, origNumProps, first = this.eq(0);

		if(typeof data === 'string') {
			prop = data.split(/,\s*/);
			numProps = prop.length;
			search = {};
			results = {};
			jQuery.map(prop, function(e) {
				search[e] = true;
			});
		} else {
			numProps = 0;
			search = jQuery.extend({}, data)
			results = jQuery.extend({}, data)
			for(prop in data) {
				numProps++;
			} //count the number of properties we're searching for
			//console.log('settings', data, 'num', numProps)
		}
		origNumProps = numProps;

		first.add(first.parents()).each(function() {
			stored = $(this).data('dumas');
			//console.log('searching ' + $(this).attr('id'));
			if(stored) {
				//console.log(stored);
				for(prop in search) {
					if(stored.hasOwnProperty(prop)) {
						results[prop] = stored[prop];
						delete search[prop];
						if((numProps--) <= 0) {
							return false;
						}
					}
				}
			}
		});
		return origNumProps > 1 ? results : results[prop];
	}
});
jQuery.extend({
	update: executeModules
});

$(function() {
	documentReady = true;
	executeModulesIfReady();
});

})();

/////////////////
// prototype overrides and extends
/////////////////

(function() {

function setClass(test, classOne, classTwo) {
	this[test ? 'addClass' : 'removeClass'](classOne);
	return (classTwo) ? this[!test ? 'addClass' : 'removeClass'](classTwo) : this;
}

jQuery.fn.extend({
	setClass : setClass,
	deserialize : function() {
		return jQuery.deserialize(this.attr('href'));
	},
	setVisible: function(visible) {
		return this.css('visibility', visible ? 'visible' : 'hidden');
	}
});
})();

jQuery.extend(String.prototype, {
	constrain: function(len) {
		return this.length < len ? this : this.substring(0, len - 3) + '...';
	},
	trim: function() {
		return jQuery.trim(this);		
	}
});

//debug
//var jqAjax = jQuery.ajax;
jQuery.extend({
	//debug
//	ajax: function(s) {
//		if(DUMAS.debug500) {
//			s.data = jQuery.extend(s.data || {},{
//				debug500: "true"
//			});
//		}
//		return jqAjax.apply(this, arguments);
//	},

	deserialize : function(url) {
		var result = {}, params, param, index, i;
		index = url.indexOf('?');
		if(index >= 0) {
			params = url.substring(index + 1).split('&');
			for(i = 0; i < params.length; i++) {
				param = params[i].split('=');
				result[param[0]] = param[1];
			}
		}
		return result;
	}
});



function addEvent( obj, type, fn ) {
	if (obj.addEventListener) {
		obj.addEventListener( type, fn, false );
		EventCache.add(obj, type, fn);
	}
	else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
		EventCache.add(obj, type, fn);
	}
	else {
		obj["on"+type] = obj["e"+type+fn];
	}
}

var EventCache = function(){
	var listEvents = [];
	return {
		listEvents : listEvents,
		add : function(node, sEventName, fHandler){
			listEvents.push(arguments);
		},
		flush : function(){
			var i, item;
			for(i = listEvents.length - 1; i >= 0; i = i - 1){
				item = listEvents[i];
				if(item[0].removeEventListener){
					item[0].removeEventListener(item[1], item[2], item[3]);
				};
				if(item[1].substring(0, 2) != "on"){
					item[1] = "on" + item[1];
				};
				if(item[0].detachEvent){
					item[0].detachEvent(item[1], item[2]);
				};
				item[0][item[1]] = null;
			};
		}
	};
}();
addEvent(window,'unload',EventCache.flush);


function goQuickLink(obj){
            var url = obj.options[obj.selectedIndex].value;
            if (url){
                        location.href = url;
            }else{
                        alert("Please make a selection.");
            }
            return false;
}

function expandCol(theTR,img){
	var dataTR = eval('document.getElementById("' + theTR +'")');
	if (dataTR.style.display=="block" || dataTR.style.display=="" ){
		dataTR.style.display="none";
		img.src='/images/butFullRev.gif';
	}else{
		dataTR.style.display="";
		img.src='/images/butCloseRev.gif';
	}
}

function pop(url,width,height,popName,resize){
	var winName = "mypop";
	if (popName){
		winName = popName;
		if (popName == "1"){
			var date = new Date();
			winName = date.getTime();
		}
	}
	if (!resize) resize="yes";
	var args = "width="+width+",height="+height+", scrollbars=yes";
	window.open(url,winName,"resizable=" + resize + ",toolbar=no,"+args);
}

function nopop(url, winName, args){window.location=url;}

function imgSwap(objImg,imgName){
	objImg.src="/images/tabs/"+imgName;
}

function HeaderImgSwap(objImg,imgName){
        objImg.src=imgName;
}


var submitClicked = false;
var activeForm = null;

function simpleDisableButton( f)
{
	if (!submitClicked)
	{
		activeForm = f;
		submitClicked = true;
		setTimeout("submitIt()", 250);
	}
	else
	{
		return false;
	}
}

function disableButton(b, f, bt)
{
	if (!submitClicked)
	{
		if (bt != null)
		{
			bt.value="1";
		}
		else
		{
			var submitMessage = "  Please Wait...  ";
			b.value = submitMessage;
		}
		activeForm = f;
		b.disabled = true;
		submitClicked = true;
		setTimeout("submitIt()", 250);
	}
	else
	{
		return false;
	}
}

function submitIt()
{
	activeForm.submit();
	return false;
}

function checkandsubmit(submitForm)
{
	if (submitClicked)
	{
		return false;
	}
	else
	{
		submitClicked = true;
		submitForm.submit();
		return false;
	}
}

// called from some old flashes - SV 1/6/06
function stopPitch()
{
	window.location.href="/registration/1.html";
}

function doPopups() {

	if (!document.getElementsByTagName) return;
	var links = document.getElementsByTagName("a");
	for (var i=0; i < links.length; i++) {
		if (links[i].className.match("terms"))  {
			links[i].onclick = function() {
				window.open(this.href,'','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=565,height=620');
				return false;
			}
		}
		else if (links[i].className.match("privacy")) {
			links[i].onclick = function() {
				window.open(this.href,'','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=765,height=500');
				return false;
			}
		}

		else if (links[i].className.match("dlmScreenshot")) {
			links[i].onclick = function() {
				window.open(this.href,'','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=320,height=310');
				return false;
			}
		}

		else if (links[i].className.match("showMe")) {
			links[i].onclick = function() {
				window.open(this.href, "","top=40,left=40,width=630,height=350");
				return false;
			}
		}
	}
}

//add disable button function to upgrade buttons
function disableSub() {
	var inputs = document.getElementsByTagName('input');
	for (var i=0; i<inputs.length; i++) {
		if (/disableButton2/.test(inputs[i].className)) {
			var thisForm = inputs[i].parentNode;
			while (thisForm.nodeName.toLowerCase() != "form") {
				thisForm = thisForm.parentNode;
			}
			inputs[i].onclick = function(){
				disableButton(this,thisForm,null);
				return false;
			}
		}
	}
}

function center() {
	if( document.getElementById("exitPop") ){
		var frameWidth;
		var frameHeight;
		if (self.innerWidth)
			{
				frameWidth = self.innerWidth;
				frameHeight = self.innerHeight;
			}
			else if (document.documentElement && document.documentElement.clientWidth)
			{
				frameWidth = document.documentElement.clientWidth;
				frameHeight = document.documentElement.clientHeight;
			}
			else if (document.body)
			{
				frameWidth = document.body.clientWidth;
				frameHeight = document.body.clientHeight;
			}

		self.moveTo((screen.width-frameWidth)/2,(screen.height-frameHeight)/2);
		};
}

addEvent(window,'load',center);
addEvent(window,'load',doPopups);
addEvent(window,'load',disableSub);

$(function(){
	if ($.browser.mozilla && navigator.userAgent.indexOf('Mac') != -1) {
		$('#subNav li a').css('letter-spacing', '0px')
	}

    var submits = 0;

   /* $('button').each(function(i){
        $(this).click(function(e){
            if (submits == 0) {
                $(this).attr('disable','disable');
                submits++;
            } else {
               return false;
            }
        });
        $(this).dblclick(function(){
            $(this).attr('disable','disable');
            submits++;
            return false
        });
    });   */

    $('#dashboard li a').hover(
		function() {
			$(this).children('span.upgrade').show();
			$(this).css('cursor','pointer');
		},
		function() {
			$(this).children('span.upgrade').hide()
		});

//		$('#myselectbox').css('border','1px solid red');

//	if( $("#branding a img").length >0 &&  $("#branding a img").attr("src").indexOf("emusic-US.gif") != -1 ){
//		$("div#brandingWrapper").css("height","82px")
//	}


});