if(typeof SBCOM == "undefined" || !SBCOM) var SBCOM = {};

SBCOM.namespace = function() {
    var a = arguments, o = null, i, j, d;
    for (i = 0; i < a.length; i++) {
        d = a[i].split(".");
        o = SBCOM;

        // SBCOM is implied, so it is ignored if it is included
        for (j = (d[0] == "SBCOM") ? 1 : 0; j < d.length; j++) {
            o[d[j]]=o[d[j]] || {};
            o=o[d[j]];
        }
    }
    return o;
};

SBCOM.namespace("utils");

SBCOM.IS_DEV_ENV = window.location.hostname.indexOf('nick.com') == -1;
SBCOM.IS_DEBUG = SBCOM.IS_DEV_ENV && window && typeof window.console != "undefined";
SBCOM.utils.URL_DEV_SPONGE = 'spongebob-nick.scenic-l.mtvi.com';
SBCOM.utils.URL_DEV_NICK = 'www.nick-d.mtvi.com';

SBCOM.utils.IMG_DEFAULT_GAMES = '/images/Common/default-game-thumb.png';
SBCOM.utils.IMG_DEFAULT_VIDEOS = '/images/Common/btn_spo_generic.jpg';
SBCOM.utils.IMG_DEFAULT_GAMES_STUDIO = '/images/characters/gamestudio/sponge_icon.jpg';

SBCOM.utils.IS_SPONGEBOB_FANS = window.location.hostname.indexOf('spongebobfans') > -1;

SBCOM.utils.getImageDefault = function(type, image) {
	if(!SBCOM.utils.isEmptyString(image)) return image;

	if(type == 'games') {
		return SBCOM.utils.IMG_DEFAULT_GAMES;
	}
	else if(type == "games_studio"){
		return SBCOM.utils.IMG_DEFAULT_GAMES_STUDIO;
	}		
	else {
		return SBCOM.utils.IMG_DEFAULT_VIDEOS; 
	}
}

SBCOM.utils.isEmptyString = function(str) {
	return str == null || SBCOM.utils.trim(str) == "" || str == 'undefined';
}

SBCOM.utils.trim = function(str) {
	return str.replace(/^\s+|\s+$/g, '');
}

SBCOM.utils.doLog = function() {
	if (!SBCOM.IS_DEBUG) return; // flag should already verify window && window.console. Fixes an odd bug

	if (typeof window.console.debug !== "undefined") {
		// firebug error console
		window.console.debug.apply(window.console, arguments);
	} else if (typeof window.console.log !== "undefined") {
		if(window.console.log.apply === "function") {
		    // safari error console
		     window.console.log.apply(window.console, arguments);
	    } else {
	    	// IE8
		    window.console.log(arguments[0]);
	    }
	}
}

SBCOM.utils.getUsername = function() {
	return SBCOM.utils.getCookie("loggedInScreenName");
}

SBCOM.utils.getCookie = function(name) {
	if(SBCOM.utils.isEmptyString(name)) return null;

	var cook = document.cookie.toString();
	if(cook.length > 0) {
		var begin = cook.indexOf(name+"=");
		if(begin != -1) {
			begin += name.length+1;
			var end = cook.indexOf(";", begin);
			if(end == -1){
			   end = cook.length;
			}
			return unescape(cook.substring(begin, end));
		}
	}
	return null;
}

SBCOM.utils.getDomain = function() {
	return window.location.hostname;
}

SBCOM.utils.getNickDomain = function() {
	var domain = window.location.hostname;
	return domain == SBCOM.utils.URL_DEV_SPONGE ? SBCOM.utils.URL_DEV_NICK : domain.replace(/spongebob-nick\.scenic|spongebob\.nick/, 'www.nick');
}

SBCOM.utils.hideElement = function(id) {
	if(!id || !$(id)) return;
	$(id).setStyle('visibility', 'hidden');
}

SBCOM.utils.showElement = function(id) {
	if(!id || !$(id)) return;
	$(id).setStyle('visibility', 'visible');

	//SBCOM.utils.doLog('vis: '+id+' | '+($(id).getStyle('display') == 'none'));
	if($(id).getStyle('display') == 'none') $(id).setStyle('display', 'block');
}

SBCOM.utils.toggleButton = function(id, toggle) {
	if(!$(id)) return;
	$(id).set("disabled", !toggle);
}

SBCOM.utils.getQueryString = function(data) {
	if(data == null) return "";
	var qs = "";
	for(var key in data) {
		if(!key || !data[key]) continue;

		if(qs != '') qs += '&';
		qs += key +"="+ escape(data[key]);
	}
	return qs;
}

/*Example: getElementsByClassName(document.getElementById(pageName), "div", "bodyContainer") */
function getElementsByClassName(oElm, strTagName, strClassName){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++){
		oElement = arrElements[i];
		if(oRegExp.test(oElement.className)){
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements)
}

SBCOM.utils.printObj = function(obj) {
	if(!obj) SBCOM.utils.doLog('>>PrintObj: invalid: '+ typeof(obj));

	SBCOM.utils.doLog('>>PrintObj: type: '+ typeof(obj));
	if(typeof(obj) != 'object') return;

	for(var key in obj) {
		SBCOM.utils.doLog('>>PrintObj: key: '+ key +" | "+obj[key]);
	}
}

SBCOM.utils.getGdcXml = function(id, obj) {
	var gdc = "<answers collectionID=\""+id+"\">";
	for(var key in obj) {
		gdc += "<answer tag=\""+ key +"\"><![CDATA["+ obj[key] +"]]></answer>";
	}
	gdc += "</answers>";
	return gdc;
}

SBCOM.utils.displayMessageUrl = '/overlay/message/?msg=';
SBCOM.utils.msg_title_default = 'window_title_info';
SBCOM.utils.msg_title_error = 'window_title_error';

SBCOM.utils.doMessage = function(message, title) {
	if(!message || !overlayObj) return;

	SBCOM.utils.doLog('doMessage: '+message);
	doRemoveLoader();
	title = title == null ? SBCOM.utils.msg_title_default : title;
	overlayObj(SBCOM.utils.displayMessageUrl + escape(message) + '&t=' + escape(title));
}

// 2008-06-27:carrillos
SBCOM.utils.validateDivIds = function() {
	//if(window.location.hostname.indexOf('mtvi.com') < 0) return;
	if(!SBCOM.IS_DEBUG) return;

	var dupes = new Object();

	// NodeList, not an array. Can't join divs and objects
	var divs = document.getElementsByTagName('div');
	for(var i = 0; i < divs.length; i++) {
		if(divs[i].id == null || divs[i].id == "" || divs[i].id == "FLASH_AD") continue;

		if(dupes[divs[i].id] != null) {
			alert("Warning: Duplicate element ID found: ["+divs[i].id+"]");
		}
		dupes[divs[i].id] = divs[i].id;
	}

	var objects = document.getElementsByTagName('object');
	for(var i = 0; i < objects.length; i++) {
		if(objects[i].id == null || objects[i].id == "" || objects[i].id == "FLASH_AD") continue;

		if(dupes[objects[i].id] != null) {
			alert("Warning: Duplicate element ID found: ["+objects[i].id+"]");
		}
		dupes[objects[i].id] = objects[i].id;
	}
	SBCOM.utils.doLog('validateDivIds: valid');
}

function bookmark() {
	var title = 'SpongeBob SquarePants';
	var url = 'http://spongebob.nick.com';
	if (document.all)
		window.external.AddFavorite(url, title);
	else if (window.sidebar)
		window.sidebar.addPanel(title, url, "")
	else if (window.sidebar&&window.sidebar.addPanel)
		window.sidebar.addPanel(title,url,"");
}

SBCOM.utils.getScenicRequestUrl = function(url, params) {
	if(url == null || params == null) return url;

	for(var key in params) {
		SBCOM.utils.doLog('URL: '+key+' | '+params[key]);
		if(key == null || params[key] == null) continue;
		url = url.replace('##'+key.toUpperCase()+'##', params[key]); 
	}
	return url;	
}

SBCOM.utils.openBumper = function(wBumper, advertiser, onair, customBumper, customHeight, newWindow, isInHouse, customWidth) {
	var bumperUrl = "/bumper/?";
	var targetUrlParameter = "destinationURL";
	var bumperHref = bumperUrl + targetUrlParameter +"="+ escape(advertiser);
	
	SBCOM.utils.doLog("openBumper: Site name =" + window.location.hostname);
	//No Bumper
	if(SBCOM.utils.IS_SPONGEBOB_FANS)
	{
		bumperHref = advertiser;
	}
	window.open(bumperHref, 'bumper', 'status=1,scrollbars=1,location=1,resizable=1,toolbar=1,menubar=1');
}

SBCOM.utils.doInitPagination = function(moduleId, moduleCount, offsetSize) {
	var slides = moduleCount;		// number of slides
	var pos = 0;		   // start position 
	var offset = offsetSize;	   // value in pixel to offset (should be a multiple of your slide width + padding and margin)
	var currentslide = 1;  // set to 1 since it is used for display also 
	var items = $(moduleId + 'browser'); // DOM id of your slide container 
	var fx = new Fx.Morph(items, {duration: 100, transition: Fx.Transitions.linear}); // not used at the moment (would  fade in/out) see mootools doc for details
	var scroll = new Fx.Scroll(moduleId + 'wrapper', {
		offset:{'x':0, 'y':0}, // sets the start x and y position
		transition: Fx.Transitions.Elastic.easeOut  // creates the bounce effect kids love (see mootools fx.transitions for details)
	});
	
	if(currentslide == slides)
	{
		$(moduleId + 'Next').swapClass('lightnext dirButton','lightnext_no dirButton');
	}

	$(moduleId + 'Previous').addEvent('click', function(event) {
		this.swapClass('lightprevious dirButton','lightprevious_on dirButton');
		event = new Event(event).stop();
		if(currentslide == 1) return;
		$(moduleId + 'slidepos').set('html', currentslide-1);	//added slide postion feedback (see mootools core for $ and .set shorthands)		
		currentslide--;														
		pos += -(offset);
		fx.start({ 
			'opacity': 1 
		}).chain(function(){
			this.start.delay(100, this, { 'opacity': 1 });
			scroll.start(pos);
			$(moduleId + 'Previous').swapClass('lightprevious_on dirButton','lightprevious dirButton');
			if(currentslide == 1) $(moduleId + 'Previous').swapClass('lightprevious_on dirButton','lightprevious_no dirButton');
			$(moduleId + 'Next').className='lightnext dirButton';
		});			
	});
			
	$(moduleId + 'Next').addEvent('click', function(event) { 
		this.swapClass('lightnext dirButton','lightnext_on dirButton');
		event = new Event(event).stop();			
		if(currentslide >= slides) return;
		$(moduleId + 'slidepos').set('html', currentslide+1);	//added slide postion feedback (see mootools core for $ and .set shorthands)
		currentslide++;
		pos += offset;
		fx.start({ 
			'opacity': 1 
		}).chain(function(){
			this.start.delay(100, this, { 'opacity': 1 });
			scroll.start(pos);
			$(moduleId + 'Next').swapClass('lightnext_on dirButton','lightnext dirButton');
			if(currentslide == slides) $(moduleId + 'Next').swapClass('lightnext_on dirButton','lightnext_no dirButton');
			$(moduleId + 'Previous').className='lightprevious dirButton';
		});
	});	
	//scroll.toLeft();
}

// Date Formatting
SBCOM.utils.dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = SBCOM.utils.dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
SBCOM.utils.dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
SBCOM.utils.dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return SBCOM.utils.dateFormat(this, mask, utc);
};

SBCOM.utils.dateRE = /^(\d{2})[\/\- ](\d{2})[\/\- ](\d{4})/;

// Date Ordering (month, day, year ascending)
SBCOM.utils.mdyOrdA = function(a, b){
	a = a.dateSort.replace(SBCOM.utils.dateRE,"$3$1$2");
	b = b.dateSort.replace(SBCOM.utils.dateRE,"$3$1$2");
	if (a>b) return 1;
	if (a <b) return -1;
	return 0; }

//Date Ordering (month, day, year descending)
SBCOM.utils.mdyOrdD = function(a, b){
	a = a.dateSort.replace(SBCOM.utils.dateRE,"$3$1$2");
	b = b.dateSort.replace(SBCOM.utils.dateRE,"$3$1$2");
	if (a>b) return -1;
	if (a <b) return 1;
return 0; }

/*
 * Added to fix banner ad alignenment issue
 */
window.addEvent('domready', function() {
	
	if ( jQuery(".banner > object").size() > 0 ) {
		jQuery(".banner > object").wrap("<div class=\"banner728\"></div>"); 
	}
});

SBCOM.utils.hideSwfs = function() {
	jQuery(".swf > *").each(function() {
		obj = $(this);
		//obj.css("display", "none");
		//obj.hide();
		obj.css('visibility', 'hidden');
	});
}

SBCOM.utils.showSwfs = function() {
	jQuery(".swf > *").each(function() {
		obj = $(this);
		//obj.css("display", "block");
		//obj.show();
		obj.css('visibility', 'visible');
	});
}


