/* KIDS namespace: shared across nick, nickr, nicktoons, etc */

if(typeof KIDS == "undefined" || !KIDS) var KIDS = {};

KIDS.IS_DEV = window.location.hostname.indexOf("localhost") >= 0 || window.location.hostname.indexOf('d.mtvi.com') > 0;
KIDS.IS_QA = window.location.hostname.indexOf('q.mtvi.com') > 0;
KIDS.IS_DEV_ENV = KIDS.IS_DEV || KIDS.IS_QA;
KIDS.IS_LIVE = !KIDS.IS_DEV_ENV;
KIDS.IS_DEBUG = KIDS.IS_DEV_ENV && window && typeof window.console != "undefined";
//KIDS.IS_DEBUG = window && typeof window.console != "undefined";

KIDS.namespace = function(nodes, root) {
	root = root == null ? KIDS : root;

    var a = nodes, o = null, i, j, d;

    d = nodes.split(".");
    o = root;

    // root is implied, so it is ignored if it is included
    for (j = (d[0] == root) ? 1 : 0; j < d.length; j++) {
        o[d[j]]=o[d[j]] || {};
        o=o[d[j]];
    }
    return o;
};

KIDS.namespace("utils", KIDS);

KIDS.utils.URL_DEV_NICK = 'www.nick-jd.mtvi.com';
KIDS.utils.URL_QA_NICK = 'www.nick-jq.mtvi.com';
KIDS.utils.URL_LIVE_NICK = 'www.nick.com';

KIDS.utils.isEmptyString = function(str) {
	//return str == null || KIDS.utils.trim(str) == "" || str === 'undefined';
	return str == null || str == undefined || str == "" || str === 'undefined';
}

KIDS.utils.trim = function(str) {
	return str == null ? "" : str.replace(/^\s+|\s+$/g, '');
}

KIDS.utils.getCookie = function(name) {
	if(KIDS.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;
}

KIDS.utils.getDomain = function() {
	return window.location.hostname;
}

KIDS.utils.getNickDomain = function() {
	if(KIDS.IS_LIVE){
		return KIDS.utils.URL_LIVE_NICK;
	} else if(KIDS.IS_QA) {
		return KIDS.utils.URL_QA_NICK;
	} else {
		return KIDS.utils.URL_DEV_NICK;
	}
}

KIDS.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;
}

/*
	Utility to submit xml into the GDC without incurring an html redirect to a "successURL"
	Shouldn't need to wrap this in xml. Inquire about a fix.
*/
KIDS.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;
}

KIDS.utils.getSwf = function(id) {
    if(navigator.appName.indexOf("Microsoft") != -1) {
        return window[id];
    } else {
    	if(document[id].length != undefined) {
			return document[id][1];
    	}
    	return document[id];
	}
}

KIDS.utils.trimArray = function(arr, toLower) {
	if(arr == null) return null;

	for(var i = 0; i < arr.length; i++) {
		arr[i] = toLower ? arr[i].toLowerCase() : arr[i];
		arr[i] = KIDS.utils.trim(arr[i]);
	}
	return arr;
}

KIDS.utils.getUrlParts = function(url) {
	var urlInfo = url.replace('//', '/').split('/');
	return urlInfo;
}

KIDS.utils.getUrlPath = function(url) {
	var urlInfo = KIDS.utils.getUrlParts(url);
	var domain;

	if(url.indexOf("http://") > -1) domain = urlInfo.splice(0, 2).join("/");

	var docInfo = urlInfo.join("/");
	//KIDS.utils.doLog("getUrlPath: "+domain+" | "+docInfo);
	return docInfo;
}

KIDS.utils.getContextPath = function(url, context, removeExtension, removeTrailingIndex) {
	var path = getUrlPath(url);
	
	// remove the file extension if a page is specified: file.jhtml
	if(removeExtension && path.lastIndexOf(".") >= 0) {
		path = path.substring(0, path.lastIndexOf("."));
	}
	
	// remove assigned context from url. context = "games" > url = /games/spongebob/game.jhtml > spongebob/game
	context = context == null || context == "" ? "" : context;
	var contextMatch = new RegExp("^"+context+"\/", "i")
	path = path.replace(contextMatch, "");;

	// remove trailing "/index" - to combine - "/some/url/index" & "/some/url/"
	if(removeTrailingIndex) path = path.replace(/\/index$/i, "");

	// remove trailing forward slash
	path = path.replace(/\/$/, "");
	
	if(path.indexOf("/") >= 0){
		path = path.replace(/\/$/, "");
	}
		
	if(path == ""){
		path = "hub";
	}
	//alert("getContextType: "+path+" | "+url);
	path = context + "_" + path;
	return path;
}

KIDS.properties = null;
KIDS.add = function(name, value) {
	if(name == null || name == '') return;
	if(KIDS.properties == null) KIDS.properties = {};

	KIDS.properties[name] = value;
};

KIDS.get = function(name) {
	if(name == null || name == '') return null;
	if(KIDS.properties == null) return null;

	return KIDS.properties[name];
};

KIDS.utils.printObj = function(obj) {
	if(!obj) KIDS.utils.doLog('>>PrintObj: invalid: '+ typeof(obj));

	KIDS.utils.doLog('>>PrintObj: type: '+ typeof(obj));
	if(typeof(obj) != 'object') return;

	for(var key in obj) {
		KIDS.utils.doLog('>>PrintObj: key: '+ key +" | "+obj[key]);
	}
}

KIDS.utils.doLog = function() {
	if (!KIDS.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);
		// IE 6 -  CompanionJS - Bug in version 0.5 - Revert to 0.4.2 - Treats window.console.debug as a string instead of a function
	} 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]);
	    }
	}
}

KIDS.utils.openBumper = function(wBumper, advertiser, onair, customBumper, customHeight, newWindow, isInHouse, customWidth) {
	KIDS.utils.doLog("openBumper: site specific override missing!");
	window.open(advertiser);
}

if(typeof NICK == "undefined" || !NICK) var NICK = {};

NICK.namespace = function(nodes) {
	KIDS.namespace(nodes, NICK);
}
NICK.namespace("utils", NICK);

/* Expose some kids functions that got moved to utils-kids */
NICK.utils.isEmptyString = KIDS.utils.isEmptyString;
NICK.utils.trim = KIDS.utils.trim;
NICK.utils.getCookie = KIDS.utils.getCookie
NICK.utils.getDomain = KIDS.utils.getDomain;
NICK.utils.printObj = KIDS.utils.printObj;
NICK.utils.getQueryString = KIDS.utils.getQueryString;
NICK.utils.getGdcXml = KIDS.utils.getGdcXml;
NICK.utils.getSwf = KIDS.utils.getSwf;
NICK.utils.trimArray = KIDS.utils.trimArray;
NICK.utils.getUrlParts = KIDS.utils.getUrlParts;
NICK.utils.getUrlPath = KIDS.utils.getUrlPath;
NICK.utils.getContextPath = KIDS.utils.getContextPath;
NICK.add = KIDS.add;
NICK.get = KIDS.get;
NICK.utils.getNickDomain = KIDS.utils.getNickDomain;
/* end: Expose */

/* legacy - just in case */
NICK.IS_DEV = KIDS.IS_DEV;
NICK.IS_QA = KIDS.IS_QA;
NICK.IS_DEV_ENV = KIDS.IS_DEV_ENV
NICK.IS_LIVE = KIDS.IS_LIVE;
NICK.IS_DEBUG = NICK.IS_DEV_ENV && window && typeof window.console != "undefined";

NICK.utils.URL_DEV_NICK = KIDS.utils.URL_DEV_NICK;
NICK.utils.URL_QA_NICK = KIDS.utils.URL_QA_NICK;
NICK.utils.URL_LIVE_NICK = KIDS.utils.URL_LIVE_NICK;

NICK.utils.URL_SPRING_NICK = 'spring.nick.com';
NICK.utils.URL_MTVN_D = "nick.mtvnimages-d.mtvi.com";
NICK.utils.URL_MTVN_Q = "nick.mtvnimages-q.mtvi.com";
NICK.utils.URL_MTVN_L = "nick.mtvnimages.com";

NICK.utils.URL_MTVN = null;

NICK.utils.initMtvnImageUrl = function() {
	var url = document.location.href;
	var urlParts = NICK.utils.getUrlParts(url);

	switch(urlParts[1]) {
		case NICK.utils.URL_LIVE_NICK : {
			NICK.utils.URL_MTVN = NICK.utils.URL_MTVN_L; 
			break;
 		} case NICK.utils.URL_SPRING_NICK : {
			NICK.utils.URL_MTVN = NICK.utils.URL_MTVN_L; 
			break;
		} case NICK.utils.URL_QA_NICK : {
			NICK.utils.URL_MTVN = NICK.utils.URL_MTVN_Q;
			break;			
		} default : {
			NICK.utils.URL_MTVN = NICK.utils.URL_MTVN_D;
		}
	}
}

NICK.utils.getImage = function(url,h,w) {
	h = h || null;
	w = w || null;
	
	return NICK.utils.getMtvnImageUrl(url,h,w);
}

NICK.utils.getMtvnImageUrl = function(image,h,w) {
		
	if(NICK.utils.isEmptyString(NICK.utils.URL_MTVN)) {
		NICK.utils.initMtvnImageUrl(); 
	}

	var path = NICK.utils.getUrlPath(image);

	path = path != null && path.indexOf("/") == 0 ? path : "/" + path;
	if(h) path+='?height='+h;
	if(w && !h) {
		path += '?'
	} else if(w) {
		path += '&';
	}

	if(w) path+='width='+w;
	
	return "http://" + NICK.utils.URL_MTVN + path;
}

NICK.utils.doLog = function(message) {
	//KIDS.utils.doLog("DOLOG: "+NICK.IS_LIVE +" | "+NICK.IS_DEBUG);
	KIDS.utils.doLog(message);
}

NICK.utils.getUsername = function() {
	return NICK.utils.getCookie("loggedInScreenName");
}
getUsername = NICK.utils.getUsername;

NICK.utils.getSessionId = function() {
	return NICK.utils.getCookie("JSESSIONID");
}
getSessionId = NICK.utils.getSessionId;


NICK.utils.hideElement = function(id) {
	if(!id || !$(id)) return;
	$(id).setStyle('visibility', 'hidden');
}

NICK.utils.showElement = function(id) {
	if(!id || !$(id)) return;
	$(id).setStyle('visibility', 'visible');

	//NICK.utils.doLog('vis: '+id+' | '+($(id).getStyle('display') == 'none'));
	if($(id).getStyle('display') == 'none') $(id).setStyle('display', 'block');
}

NICK.utils.toggleButton = function(id, toggle) {
	if(!$(id)) return;
	$(id).set("disabled", !toggle);
}

// 2008-06-27:carrillos
NICK.utils.validateDivIds = function() {
	//if(window.location.hostname.indexOf('mtvi.com') < 0) return;
	if(!NICK.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;
	}
	NICK.utils.doLog('validateDivIds: valid');
}

NICK.utils.doBookmark = function() {
	var title = 'Nick.com';
	var url = 'http://www.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,"");
}

NICK.utils.initTooltip = function(){
	
	$('.with-nick-tooltip').unbind("mouseenter")
						   .unbind("mouseleave")
	// Initial the tooltip for any items
	$('.with-nick-tooltip').tooltip({
    	contentSelector: ".tooltip-content",
		id: "nick-tooltip",
		allowAccess: false,
		followMouse: true,
		lockTo: "side",
		lockToElement: "img:first",
		offsetX: -13
	});

		
	
}

NICK.utils.addTooltip = function(){
	
}



NICK.utils.openNewBumper = function(wBumper, advertiser) {
	NICK.utils.openBumper(wBumper, advertiser, null, null, null, true);
} 

NICK.utils.openBumper = function(wBumper, advertiser, onair, customBumper, customHeight, newWindow, isInHouse, customWidth) {
	/*var bumperUrl = "/utils/bumper/frameset.html?";
	var fullPageBumperUrl = "/utils/bumper/full-page.html?";*/
	var bumperUrl = "http://www.nick.com/common/bumpers/bumperFrameset.jhtml?";
	var fullPageBumperUrl = "http://www.nick.com/common/bumpers/fullpage/nicktoons.jhtml?";
	var bumperParam = "wBumper";
	var targetUrlParameter = "advertiser";
	onair = onair != null && onair;
	isInHouse = isInHouse == undefined ? true : isInHouse;

	switch(wBumper) {
		case "external" : {
			bumperUrl = "http://www.nick.com/common/bumpers/go.jhtml?";
			bumperUrl += customBumper == null ? "" : ("bumper=" + escape(customBumper) + "&");
			bumperUrl += customHeight == null ? "" : ("bumperHeight=" + customHeight + "&");
			bumperUrl += isInHouse == undefined ? "" : ("isInHouse=" + isInHouse + "&");
			targetUrlParameter = "destination";
			break;
		} case "fullPage" : {
			bumperUrl = fullPageBumperUrl;
			targetUrlParameter = "destination";
			break;
		} case "paysite" : {
			break;
		} case "grown-ups" : {
			break;
		} case "launchpad" : {
			break;
		} case "sponsor" : {
			break;
		} case "full-redirect" : {
			bumperUrl = '/utils/bumper/half-page.html?'	
			break;
		} default : {
			wBumper = "sponsor";
			break;
		}
	}

	var bumperHref = bumperUrl +
					 bumperParam +"="+ wBumper +"&"+
					 targetUrlParameter +"="+ escape(advertiser);

	if(onair) bumperHref += "&onair_landing=true";
	if(onair && wBumper == "external") {
		bumperHref = fullPageBumperUrl + targetUrlParameter +"="+ escape(bumperHref);
	}
	if(newWindow) {
		window.open(bumperHref, 'bumper', 'status=1,scrollbars=1,location=1,resizable=1,toolbar=1,menubar=1');
	} else {
		window.location.href = bumperHref;
	}
}

NICK.utils.wrapOPABanner = function() {
/*
	if ( $("#ad-728x90Div table").width() > 728 ) {
		$("#ad-728x90Div").wrapInner("<div class=\"AdSize-OPA\"></div>");
	} else {
		$("#ad-728x90Div").wrapInner("<div class=\"AdSize-728\"></div>");
	}
*/
}

/* Utils on Document ready function*/
$(document).ready(function() {
	NICK.utils.initTooltip();
	NICK.utils.validateDivIds();
});


/* Provided for yahoo ads */
KIDS.utils.openBumper = NICK.utils.openBumper;

NICK.utils.hideSwfs = function() {
	$(".swf > *").each(function() {
		obj = $(this);
		//obj.css("display", "none");
		//obj.hide();
		obj.css('visibility', 'hidden');
	});
}

NICK.utils.showSwfs = function() {
	$(".swf > *").each(function() {
		obj = $(this);
		//obj.css("display", "block");
		//obj.show();
		obj.css('visibility', 'visible');
	});
}

NICK.utils.openOverlay = function() {
	NICK.utils.doLog("NICK.utils.openOverlay(): Deprecated. Use: NICK.overlay.open().");
}

NICK.utils.closeOverlay = function() {
	NICK.utils.doLog("NICK.utils.closeOverlay(): Deprecated. Use: NICK.overlay.close().");
}

NICK.utils.initAdFreePage = function() {
	//NICK.utils.doLog("initAdFreePage: "+KIDS.get("adfree"));
	if(KIDS.get("adfree") !== "true") return;

	$('a').bind("click", NICK.utils.doBumperOverride);
	$('.brand-mamabar-more-list .bumper').remove();
}

NICK.utils.initAdFreeLinks = function(){
	NICK.utils.initAdFreePage();

	$('#top-menu a').bind("click", NICK.utils.doBumperOverride);
	$('#page-menu a').bind("click", NICK.utils.doBumperOverride);
}

NICK.utils.doBumperOverride = function(e){
	NICK.utils.openBumper('fullPage', this.href);
	return false;
}

NICK.utils.random = function(X) {
	    return Math.floor(X * (Math.random() % 1));
}
	
NICK.utils.randomBetween = function(MinV, MaxV) {
	  return MinV + NICK.utils.random(MaxV - MinV + 1);
}

NICK.utils.getNoRepeatRandoms = function(total, cap){
	var rands = new Array();
	var total = Math.min(total, cap);
	while (rands.length < total){
		var val = NICK.utils.randomBetween(0, cap);
		var duplicate = false;
		for(var i=0; i<rands.length; i++){
			//NICK.utils.doLog(rands[i] + "could= " + val);
			if(rands[i] == val){
				duplicate = true;
			}
		}
		if(duplicate == false){
			rands.push(val);
		}
	}

	return rands;
}

NICK.utils.timezone = function() {
	var rightNow = new Date();
	var jan1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);  // jan 1st
	var june1 = new Date(rightNow.getFullYear(), 6, 1, 0, 0, 0, 0); // june 1st
	var temp = jan1.toGMTString();
	var jan2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
	temp = june1.toGMTString();
	var june2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
	var std_time_offset = (jan1 - jan2) / (1000 * 60 * 60);
	var daylight_time_offset = (june1 - june2) / (1000 * 60 * 60);
	var dst;
	if (std_time_offset == daylight_time_offset) {
		dst = "0"; // daylight savings time is NOT observed
	} else {
		// positive is southern, negative is northern hemisphere
		var hemisphere = std_time_offset - daylight_time_offset;
		if (hemisphere >= 0)
			std_time_offset = daylight_time_offset;
		dst = "1"; // daylight savings time is observed
	}
	return std_time_offset;
}

NICK.utils.getTimezone = function () {
	if (NICK.utils.timezone() == -5)
		return "east";
	else return "west";
}

if(typeof NICK == "undefined" || !NICK) var NICK = {};
NICK.namespace("config");
NICK.config.URL_COMMENT_POST = "http://"+NICK.utils.getNickDomain()+"/xml/gdc_json.jhtml?jsonCallback=?";
NICK.config.IMX_RATE = "/api/ratings/1.0/rate";
NICK.config.IMX_PUT = "/api/imx/1.0/put";
NICK.config.IMX_VIEW_COUNT = "/api/imx/1.0/report";
/**
 * @author carrillos
 * @version 1.0, 05/01/2009
 */
if(typeof NICK == "undefined" || !NICK) var NICK = {};

(function() {
	KIDS.namespace("utils", NICK);
	KIDS.namespace("request.messages", NICK);
	KIDS.namespace("request.errors", NICK);
	KIDS.namespace("response.codes", NICK);

	NICK.request.errors.SERVER = "_ERROR_SERVER";
	NICK.request.errors.REQUEST = "_ERROR_REQUEST";
	NICK.request.errors.RESPONSE = "_ERROR_RESPONSE";
	NICK.request.errors.URL = "_ERROR_URL";

	NICK.request.messages.INVALID_RESPONSE = "Invalid reponse";
	NICK.request.messages.INVALID_URL = "Invalid url requested";

	NICK.response.codes.OK = "ok";
	NICK.response.codes.ERROR = "error";

	NICK.request.doRequest = function(options) {
		var defaults = {
			type:"GET",
			url:null,
			data:null,
			dataType:"jsonp",
			onSuccess:null,
			onFail:null
		};

		var settings = $.extend({}, defaults, options);

		var doResponse = function(response) {
			if("jsonp" == settings.dataType) doResponseJson(response);
			else if("json" == settings.dataType) doResponseJson(response);
			else if("xml" == settings.dataType) doResponseXml(response);
			else if("html" == settings.dataType) doResponseHtml(response);
			else KIDS.utils.doLog(">>NICK.request: No response handler for type: "+settings.dataType);
		}

		var doResponseJson = function(response) {
		
			if(response == null) {
				onFail(getError(NICK.request.errors.RESPONSE, NICK.request.messages.INVALID_RESPONSE));
			} else if(response.code == NICK.response.codes.OK) {
				onSuccess(response);
			} else if(response.code == NICK.response.codes.ERROR) {
				onFail(response.errors);
			}else{
				onSuccess(response);
			}
		}

		var doResponseXml = function(response) {
			if(response == null) {
				onFail(getError(NICK.request.errors.RESPONSE, NICK.request.messages.INVALID_RESPONSE));
				return;
			} else if($(response).find('response').attr('status') == NICK.response.codes.OK) {
				onSuccess(response);
			} else if($(response).find('response').attr('status') == NICK.response.codes.ERROR) {
				var errors = {};

				$(response).find('error').each(function() {
					errors[$(this).attr('name')] = $(this).text();
				});

				//onFail($(response).find('errors'));
				onFail(errors);
			}
		}

		var doResponseHtml = function(response) {
			if(response == null) {
				onFail(getError(NICK.request.errors.RESPONSE, NICK.request.messages.INVALID_RESPONSE));
				return;
			} else {
				onSuccess(response);
			}
		}

		var onFail = function(error) {
			var errors = typeof error == 'string' ? { request:error } : error;

			if(settings.onFail) settings.onFail(errors); // Always want to pass errors as an Object
			else KIDS.utils.doLog("doRequest: Failed: "+ error);
		}

		var onSuccess = function(data) {
			if(settings.onSuccess) settings.onSuccess(data);
			else KIDS.utils.doLog("doRequest: OK");
		}

		var doRequestError = function(request, error, exception) {
			onFail(getError(NICK.request.errors.REQUEST, error));
		}

		var getError = function(name, message) {
			var error = new Object();
			error[name] = message;
			return error;
		}

		if(settings.url == null) {
			onFail(getError(NICK.request.errors.URL, NICK.request.messages.INVALID_URL));
			return;
		}

		try { // Catch browser security exceptions.
			$.ajax({
				type:		settings.type,
				url:		settings.url,
				data:		settings.data == null ? {} : settings.data,
				dataType:	settings.dataType,
				success:	doResponse,
				error:		doRequestError
			});
		} catch(error) {
			KIDS.utils.doLog("NickRequest: error: "+error);
			onFail({_ERROR_SERVER:error});
		}
	}

})();
/*
 * Main Authentication class. 
 * responsible for:
 *  -Login
 *  -Logout
 *  -Login status
 *  -Registration
 * 
 * written by: Blaine O'Brien
 */
$(document).ready(function () {
	    $(document).bind("authStatus", function(response){NICK.utils.doLog("authStatus: loggedIn: " + NICK.userData.loggedIn);})
	    NICK.login.doNickCheck();
});

NICK.namespace("login.forgot");

var nickLoginUrl = 'http://'+ NICK.utils.getNickDomain() +'/common/login/check.jhtml';
var nickRegUrl = 'http://'+ NICK.utils.getNickDomain() +'/common/registration/register.jhtml';
var nickAuthQuestionUrl = 'http://'+ NICK.utils.getNickDomain() +'/registration/data_files/getUserQuestion.jhtml';
var nickAuthAnswerUrl = 'http://'+ NICK.utils.getNickDomain() +'/registration/data_files/verify_answer.jhtml';
var nickPrepGamesUrl = 'http://'+ NICK.utils.getNickDomain() +'/nicktropolis/game/data/prep_games_js.jhtml';

NICK.login.doNickCheck = function() {
	if(NICK.userData == undefined){
 		var params = {
 	 			'res':'js',
 	 			'login_type':'LOGIN_CHECK'
 	 		}; 
 		NICK.request.doRequest({
 			dataType:"jsonp",
 			url: nickLoginUrl,
 			data: params,
 			onSuccess: function(response) {
 				NICK.utils.doLog("doNickCheck: onSuccess : " + response.nickName);
 				NICK.userData = response;
 				$(document).trigger("authStatus", response); 
 			},
 			onFail: function(errors) {
 				for(var error in errors) {
 					NICK.utils.doLog("doNickCheck: error: "+error+" - "+errors[error]);
 				}
 			}				
 		});
 	
	}else{
		$(document).trigger("authStatus");
	}
	

	//var nickLoginUrl = 'http://'+ NICK.utils.getNickDomain() +'/common/login/check.jhtml';
	//NICK.moojax.json.doRequest(nickLoginUrl, params, this.handleNickCheck.bind(this));
}

NICK.login.doLogIn = function(data) {
	NICK.utils.doLog("doLogIn!");

	var params = {
			'res':'js',
 			'screenName':data.username,
 			'password': data.password
 		}; 
	NICK.request.doRequest({
		dataType:"jsonp",
		url: nickLoginUrl,
		data: params,
		onSuccess: function(response) {
			NICK.utils.doLog("doLogIn: onSuccess : " + response.loggedIn);
			NICK.userData = response;
			for(var i in response){ NICK.utils.doLog('doLogIn: userData: ' + i); }

			if(response.loggedIn == "true"){
				$(document).trigger("loggedIn", response);
				NICK.login.prepGamesServer();
				NICK.overlay.close();
			}else{
				$(document).trigger("logInFail");
			}
		},
		onFail: function(errors) {
			NICK.utils.doLog("doLogIn: onFail");
			for(var error in errors) {
				NICK.utils.doLog("doLogIn: error: "+error+" - "+errors[error]);
			}
		}				
	});
}

NICK.login.doLogOut = function() {
	var params = {
			'res':'js',
	 		'forceLogout':'true'
	 		}; 
	NICK.request.doRequest({
			dataType:"jsonp",
			url: nickLoginUrl,
			data: params,
			onSuccess: function(response) {
				NICK.utils.doLog("doLogOut: onSuccess : " + response.loggedIn);
				NICK.userData = response;
				$(document).trigger("loggedOut", response); 
			},
			onFail: function(errors) {
				for(var error in errors) {
					NICK.utils.doLog("doLogOut: error: "+error+" - "+errors[error]);
				}
			}				
		});    	
}

NICK.login.doRegister = function(regdata) {
	var params = regdata; 
	params.res = 'js';
	params.trylogin = 'true';
     	
    	NICK.request.doRequest({
			dataType:"jsonp",
		url: nickRegUrl,
		data: params,
		onSuccess: function(response) {
			NICK.utils.doLog("doRegister: onSuccess : ");
			if(response.success =="true"){
				doRegSuccess(response, regdata);
			}else{
				doRegFail(response, regdata);
			}
		},
		onFail: function(errors) {
			for(var error in errors) {
				NICK.utils.doLog("doRegister: error: "+error+" - "+errors[error]);
			}
		}				
	});
}  
NICK.login.forgot.questionData = "";

NICK.login.forgot.submitAuthQuestion = function() {
	NICK.overlay.loadingToggle();
	NICK.utils.doLog("submitAuthQuestion");
	if($("#getQuestionDiv").css("display") != "none"){
		NICK.login.forgot.submitNickname();
	}else{
		NICK.login.forgot.submitAnswer();
	}
	
};

NICK.login.forgot.submitNickname = function(){
	var username = $('#usernameField').val();
	NICK.utils.doLog("submitNickName: ["+username+"]");
	if(NICK.utils.isEmptyString(username)) {
		$("#failMsg").show().html("Incorrect NickName. Try again.");
		return;
	}

	var params = {
		'username':$('#usernameField').val(),
		'showComments':'false',
		'responseType':'json'
	 }; 
    NICK.request.doRequest({
		dataType:"jsonp",
		url: nickAuthQuestionUrl,
		data: params,
		onSuccess: function(response) {
    		NICK.overlay.loadingToggle();
			NICK.utils.doLog("response question:"+ response.question);
			if(response.questionid != "null"){
				NICK.login.forgot.questionData  = response
				$("#secretQuestion").html(response.question);
				$("#getQuestionDiv").hide();
				$("#getAnswerDiv").show();
				$("#failMsg").hide();
			}else{
				//NICK.utils.doLog("bad nickname");
				$("#failMsg").show().html("Incorrect NickName. Try again.");
			}
		},
		onFail: function(errors) {
			NICK.overlay.loadingToggle();
			for(var error in errors) {
				NICK.utils.doLog("submitNickname: error: "+error+" - "+errors[error]);
			}
		}				
	});
}
NICK.login.forgot.submitAnswer = function(){
	NICK.utils.doLog("submitAnswer");
	var answer = $("#answerField").val();
	if(NICK.utils.isEmptyString(answer)) {
		$("#failMsg").show().html("Incorrect answer. Try again.");
		return;
	}

	var params = {
		'username':NICK.login.forgot.questionData.username,
		'questionid':NICK.login.forgot.questionData.questionid,
		'answer':answer,
		'responseType':'json'
	 }; 
    NICK.request.doRequest({
		dataType:"jsonp",
		url: nickAuthAnswerUrl,
		data: params,
		onSuccess: function(response) {
    		NICK.overlay.loadingToggle();
			NICK.utils.doLog("response valid:"+ response.valid);
			if(response.valid == "true"){
				$("#failMsg").hide();
				$("#getAnswerDiv").hide();
				$(".o_popup_forgot .actions").hide();
				$('#yourPassword').show().html("Your password is: "+response.password);
			}else{
				//NICK.utils.doLog("submitAnswer: incorrect answer");
				$("#failMsg").show().html("Incorrect answer. Try again.");
			}
		},
		onFail: function(errors) {
			NICK.overlay.loadingToggle();
			for(var error in errors) {
				NICK.utils.doLog("submitAnswer: error: "+error+" - "+errors[error]);
			}
		}				
	});
	
}

NICK.login.prepGamesServer = function(){
	 NICK.request.doRequest({
		dataType:"jsonp",
		url: nickPrepGamesUrl,
		onSuccess: function(response) {
    		NICK.utils.doLog("Prep game server completed.");
		},
		onFail: function(errors) {
			for(var error in errors) {
				NICK.utils.doLog("Prep Game: error: "+error+" - "+errors[error]);
			}
		}				
	});
}
if(typeof NICK == "undefined" || !NICK) var NICK = {};
NICK.namespace("sendToFriend");

// 5/12/2009 David Jordan
/* email string validation */
NICK.utils.validateEmail = function ( email ) {
	var ptrn  =  /^[a-z0-9._%-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i;
	return ptrn.test(email);
}

// Send to friend 
	NICK.sendToFriend.URL_WORD_FILTER = "http://www.nick.com/dynamo/wordfilter/index.jhtml?name=";
	NICK.sendToFriend.goodWordsCounter =0;
	NICK.sendToFriend.formSubmitting = false;

NICK.sendToFriend.formLoaded = function(){
	$('#failMsg').hide();
	$('#badwordMsg').hide();
	$('#bademailMsg').hide();
	$('#emailSentMsg').hide();
	$('#badnameMsg').hide();
	$('#sendToFriendForm').show();
	$('#send-to-a-friend div.loadingAnimation').hide();

}

NICK.sendToFriend.validate = function(){
	$('#failMsg').hide();
	$('#badwordMsg').hide();
	$('#bademailMsg').hide();
	$('#emailSentMsg').hide();
	$('#badnameMsg').hide();
	$('#send-to-a-friend div.loadingAnimation').show();
	$('#send-to-a-friend div.loadingAnimation h4').html("Validating...");
	
	if($("#yourName").attr("value") == "")
	{
		$('#failMsg').show();
		$('#badnameMsg').show();
		$('#yourName').removeClass("textboxerror");
		$('#yourName').addClass("textboxerror");
	}
	else
	{
		$('#yourName').removeClass("textboxwrapper");
		$('#yourName').addClass("textboxwrapper");
	}
		
	if($("#friendsName").attr("value") == "")
	{
		$('#failMsg').show();
		$('#badnameMsg').show();
		$('#friendsName').removeClass("textboxerror");
		$('#friendsName').addClass("textboxerror");
	}
	else
	{
		$('#friendsName').removeClass("textboxerror");
		$('#friendsName').addClass("textboxerror");
	}
		
	if ((!NICK.utils.validateEmail( $("#friendsEmail").attr("value") ))) {
		$('#failMsg').show();
		$('#bademailMsg').show();
		$('#friendsEmail').removeClass("textboxerror");
		$('#friendsEmail').addClass("textboxerror");
	}
	else {
		$('#friendsEmail').removeClass("textboxerror");
		$('#friendsEmail').addClass("textboxerror");
	}
	NICK.sendToFriend.goodWordsCounter = 0;
	NICK.sendToFriend.checkBadWord($("#yourName"));
	NICK.sendToFriend.checkBadWord($("#friendsName"));
	
}

NICK.sendToFriend.checkBadWord = function( field){
	var word = field.attr("value")
	var nick_url = NICK.utils.getNickDomain();
	var JSON_URL = "http://"+ nick_url + "/common/wordfilter/json.jhtml";
	NICK.request.doRequest({
		dataType:"jsonp",
		url: JSON_URL,
		data: {v:"1", word:word},
		onSuccess: function(response) {
			NICK.utils.doLog("Dirty Word Response:" + response.data[0].code);
			if(response.data[0].code == "bad" ){
				field.attr("value","");
				NICK.sendToFriend.goodWordsCounter = 0;
				$('#failMsg').css("display", "block");
				$('#badwordMsg').css("display", "block");
				$('#send-to-a-friend div.loadingAnimation').hide();
			}else{
				NICK.sendToFriend.goodWordsCounter++;
				//NICK.utils.doLog("goodWordsCounter:" + NICK.sendToFriend.goodWordsCounter);
				$('#send-to-a-friend div.loadingAnimation').hide();
				if(NICK.sendToFriend.goodWordsCounter == 2 && $('#failMsg').css("display") == "none"){
					NICK.sendToFriend.goodWordsCounter = 0;
					NICK.sendToFriend.formSubmitting = true;
					
					var friendsEmail = $("#friendsEmail").val();
					var yourName = $("#yourName").val();
					var friendsName = $("#friendsName").val();
					var link = window.location;
					NICK.sendToFriend.sendEmail(yourName,friendsName, friendsEmail, link);
				}
			}			
		},
		onFail: function(errors) {
			for(var error in errors) {
				NICK.utils.doLog("Dirty Word Response: Error: "+error+" - "+errors[error]);
			}
		}				
	});
}

NICK.sendToFriend.sendEmail = function(yourName,friendsName, friendsEmail, link){
	$('#failMsg').hide();
	$('#badwordMsg').hide();
	$('#bademailMsg').hide();
	$('#emailSentMsg').hide();
	$('#badnameMsg').hide();
	$('#sendToFriendForm').hide();
	$('#send-to-a-friend div.loadingAnimation').show();
	
	var nick_url = NICK.utils.getNickDomain();
	//var URL = "http://"+ nick_url + "/dynamo/email/sendToFriend.jhtml";
	var URL = "http://"+ nick_url + "/sbcom/data/sendToFriend/send_nick.jhtml";
	var encodedLink = $("<div/>").text( link.toString() ).html();
	if (NICK.sendToFriend.overrideTemplate == undefined) {
		template = NICK.get("type");
	}
	NICK.request.doRequest({
		dataType:"jsonp",
		url: URL,
		data: {email:friendsEmail, senderName:yourName, friendsName:friendsName, URLpath:encodedLink, etype:template, id: NICK.get("cmsId"), domain:window.location.hostname, section:NICK.get("type") },
		onSuccess: function(response) {
			NICK.utils.doLog("Email Send Success!");
			//tb_remove();
			$('#send-to-a-friend div.loadingAnimation').hide();
			$("#sentMessage").show().html("Congrats! This has been sent to your friend.");
		},
		onFail: function(errors) {
			$("#sentMessage").show().html("There was an error sending your message. Please try again.");
			$('#sendToFriendForm').show();
			for(var error in errors) {
				NICK.utils.doLog("Bad load: Error: "+error+" - "+errors[error]);
				alert(errors[error]);
			}
		}				
	});
}
var menuTimeout = null;

$(function() {
	// Give the requested mamabar items bumper links
	$("a.bumper").each(function() {
		$(this).click(function(e) {
			e.preventDefault();
			NICK.utils.openBumper("paysite", $(this).attr("href"));
			return false;
		});
	});

	$("#global-bar .down-arrow-extra").click(function() {
		var pos = 0, next = $(this).parent().parent().next();
		if ( next.size() > 0 ) {
			var pos = next.siblings().andSelf().index(next);
		}
		$(this).parent().parent().parent().animate({
			top: pos * -next.height()
		}, "fast");
	});

	$("#top-menu-more,#global-sites-more").hover(function() {
			$(this).addClass("hover");
		}, function() {
			$(this).removeClass("hover");
		}
	);
	
	$("#nick-arcade-bumper a").click(function() {
		 NICK.utils.openBumper('paysite', 'http://www.nick.com/common/bumpers/go.jhtml?destination=http://arcade.nick.com/nick/home.jsp?refid=4819'); 
		 return false;
	});

	if ( $("#submenu-more").size() > 0 ) {
		$("#submenu-more").mouseenter(function() {
			clearInterval(menuTimeout);
			$("#submenu-wrapper").addClass("expanded");
			$("#submenu-content").show();
		});
		
		$("#submenu-more").mouseleave(function() {
			menuTimeout = setTimeout(function() {
				$("#submenu-wrapper").removeClass("expanded");
				$("#submenu-content").hide();
			}, 150);
		});
		
		$("#submenu-content").mouseenter(function() { clearInterval(menuTimeout); });
		$("#submenu-content").mouseleave(function () {
			$("#submenu-wrapper").removeClass("expanded");
			$("#submenu-content").hide();
		});
	}

	$(".png,h1.icon").supersleight({
		shim: "/assets/transparent.gif",
		apply_positioning: false
	});

	$(document).bind("authStatus loggedIn loggedOut", function(){
		setHeaderStatus();
	});

	var setHeaderStatus = function(){
		NICK.utils.doLog("authStatus: setHeaderStatus:" + NICK.userData.loggedIn + NICK.userData.screenName);
		if(NICK.userData.loggedIn == "true"){
			$(".mynick-noauth").hide();
			$(".mynick-auth").show();
			if(NICK.userData.screenName == ''){
				var displayName = NICK.userData.nickName;
			}else{
				var displayName = NICK.userData.screenName;
			}
			$("#mynick-nav-main").html('<a href="/mynick/nickpages/index.jhtml?username=' + displayName.toLowerCase() + '">' + displayName + '</a>');
			
		} else {
			$("#mynick-nav-main").html('<a href="/mynick/">MYNICK</a>');
			$(".mynick-auth").hide();
			$(".mynick-noauth").show();	
		}
	}

	/*$("#submenu a").each(function() {
		if ( $(this).attr("href") == window.location.pathname ) {
			$(this).addClass("active");
		}
	});*/
});

function openMoreSubMenu(e) {
	var wrapper = $("#submenu-wrapper");
	var content = $("#submenu-content");
	var text    = $("#submenu-more").find("a span");

	if ( wrapper.hasClass("expanded") ) {
		//content.slideUp("fast", function() { wrapper.removeClass("expanded"); });
		content.hide();
		wrapper.removeClass("expanded");
		//text.text("More");
	} else {
		
		//content.slideDown("fast");
		content.show();
		//text.text("Close");
	}

	e.stopPropagation();
}

$(document).ready(function() {
	NICK.utils.doLog("header.js: initLogin!");
		
	$(document).bind("loggedIn", function(){
		NICK.utils.doLog("header.js: loggedIn");
	})
	$(document).bind("logInFail", function(){
		NICK.utils.doLog('header.js: logInFail');
		setErrorContent();
	});

	var setErrorContent = function(){
		$('#loginError').show();
		$('#nickLogin').show();
		$('#loginLoader').hide();
	}
});

function sendLogin(){
	var loginData = {
		username: $(".o_popup_login input[name='nickUsername']").val(),
		password: $(".o_popup_login input[name='nickPassword']").val()
	};

	NICK.login.doLogIn(loginData);
}if(typeof NICK == "undefined" || !NICK) var NICK = {};
NICK.namespace("pagination");

NICK.pagination.itemOffset = -1;

NICK.pagination.setItemOffset = function(itemOffset) {
	NICK.utils.doLog(">setItemOffSet: "+itemOffset);
	NICK.pagination.itemOffset = itemOffset;
}

NICK.pagination.getItemOffset = function() {
	return NICK.pagination.itemOffset;
}

NICK.pagination.goToPage = function(page, max, id, sort) {
	NICK.utils.doLog("Pagination!: goToPage: " + id);
	id = id == null ? '' : '' + id;

	$(document).trigger({type:"pagination_go."+id, page:page, max:max, id:id, sort:sort}); 
}

NICK.pagination.goNext = function(page, max, id, sort) {
	NICK.pagination.goToPage(page, max, id, sort);
}

NICK.pagination.goPrevious = function(page, max, id, sort) {
	NICK.pagination.goToPage(page, max, id, sort);
}

$(document).bind("pagination_go.",
	function(response) {
		NICK.utils.doLog("Pagination: event: " + response.type +" | "+ response.id);
		NICK.listings.getDataPages(response.sort, response.page, response.max);
	}
);

$(document).bind("pagination_go.game-browser-pagination",
	function(response) {
		var offset = NICK.pagination.getItemOffset();

		if(offset <= 0) {
			NICK.listings.getDataPages(response.sort, response.page, response.max);
			return;
		}

		var items = 0;

		if(response.page == 1) {
			items = 0;
		} else if(response.page <= 2) {
			items = offset;
		} else {
			items = ((response.page * response.max - response.max) - offset);
		}
		NICK.utils.doLog("Pagination: " + offset + " | "+ response.page +" | "+ response.max +" | "+ items);
		NICK.listings.getData(NICK.listings.getUriOverride(), response.sort, items, response.page);
	}
)

$(document).bind("pagination_go.collection-grid-pagination",
	function(response) {
		NICK.utils.doLog("Pagination: event: " + response.type +" | "+ response.id);
		NICK.listings.getDataPages(response.sort, response.page, response.max);
	}
)

$(document).bind("pagination_go.collection-grid-paginationfullEpisodeItem",
	function(response) {
		NICK.utils.doLog("Pagination: event: " + response.type +" | "+ response.id);
		NICK.listings.getDataPages(response.sort, response.page, response.max,{'type':'fullEpisodeItem'});
	}
)



$(document).bind("pagination_go.collection-grid-paginationvideoItem",
	function(response) {
		NICK.utils.doLog("Pagination: event: " + response.type +" | "+ response.id);
		NICK.listings.getDataPages(response.sort, response.page, response.max,{'type':'videoItem'});
	}
)

$(document).bind("pagination_go.collection-grid-paginationvideoPlaylist",
	function(response) {
		NICK.utils.doLog("Pagination: event: " + response.type +" | "+ response.id);
		NICK.listings.getDataPages(response.sort, response.page, response.max,{'type':'videoPlaylist'});
	}
)

$(document).bind("pagination_go.collection-grid-all-paginationfullEpisodeItem",
	function(response) {
		NICK.utils.doLog("Pagination: event: " + response.type +" | "+ response.id);
		NICK.listings.getDataPages(response.sort, response.page, response.max,{'type':'fullEpisodeItem', 'viewType' : 'collectionAll'});
	}
)


$(document).bind("pagination_go.collection-grid-all-pagination",
	function(response) {
		NICK.utils.doLog("Pagination: event: " + response.type +" | "+ response.id);
		NICK.listings.getDataPages(response.sort, response.page, response.max, {'viewType' : 'collectionAll'});
	}
)


$(document).bind("pagination_go.collection-grid-all-paginationvideoItem",
	function(response) {
		NICK.utils.doLog("Pagination: event: " + response.type +" | "+ response.id);
		NICK.listings.getDataPages(response.sort, response.page, response.max,{'type':'videoItem', 'viewType' : 'collectionAll'});
	}
)

$(document).bind("pagination_go.collection-grid-all-paginationvideoPlaylist",
	function(response) {
		NICK.utils.doLog("Pagination: event: " + response.type +" | "+ response.id);
		NICK.listings.getDataPages(response.sort, response.page, response.max,{'type':'videoPlaylist', 'viewType' : 'collectionAll'});
	}
)


$(document).bind("pagination_go.tag-search-pagination",
	function(response) {
		NICK.utils.doLog("Pagination: event: " + response.type +" | "+ response.id);
		l=document.location.href.split('?');
		l=l[0];
		if (response.page > 1) l+="?page="+response.page+"&start="+(response.page-1)*response.max;
		document.location.href=l;
	}
)


$(document).bind("pagination_go.search-pagination",
	function(response) {
		NICK.utils.doLog("Pagination: event: " + response.type +" | "+ response.id);
		l=document.location.href.split('?');
		
		// grab term
		t=l[1].split('&');t=t[0].split('=');t=t[1];
		
		l=l[0];
		l+='?term='+t;
		if (response.page > 1) l+="&page="+response.page+"&start="+(response.page-1)*response.max;
		document.location.href=l;
	}
)


$(document).bind("pagination_go.games-by-show-all-pagination",
	function(response) {
		NICK.utils.doLog("Pagination: event: " + response.type +" | "+ response.id +" | page: "+ response.page +" | max: "+ response.max );
		//NICK.listings.getDataPages(response.sort, response.page, response.max);
			
		var params = {
		 	'sort':'',
		 	'start': (response.page * response.max - response.max),
			'page': response.page
		 }; 
		NICK.request.doRequest({
			dataType:"html",
			url: "/ajax/listing-game/games-by-show-all.html",
			data: params,
			onSuccess: function(response) {
				$("div.filter-target").html(response);
			},
			onFail: function(errors) {
				for(var error in errors) {
					NICK.utils.doLog("Sort Response: Error: "+error+" - "+errors[error]);
				}
			}				
		});
	}
)


$(document).bind("pagination_go.shows-list-pagination",
	function(response) {
		NICK.utils.doLog("Pagination: event: " + response.type +" | "+ response.id +" | page: "+ response.page +" | max: "+ response.max );
		//NICK.listings.getDataPages(response.sort, response.page, response.max);
			
		var params = {
		 	'sort':'',
		 	'start': (response.page * response.max - response.max),
			'page': response.page
		 }; 
		NICK.request.doRequest({
			dataType:"html",
			url: "/ajax/listing-video/shows-list.html",
			data: params,
			onSuccess: function(response) {
				$("div.filter-target").html(response);
			},
			onFail: function(errors) {
				for(var error in errors) {
					NICK.utils.doLog("Sort Response: Error: "+error+" - "+errors[error]);
				}
			}				
		});	
	}
)

$(document).bind("pagination_go.comments-pagination",
	function(response) {
		NICK.utils.doLog("Pagination: Comments event: " + response.type +" | "+ response.id +" | page: "+ response.page +" | max: "+ response.max );
		NICK.comments.loadComments(response.type ,null,NICK.comments.urlAlias,(response.page * response.max - response.max),20);
	}
)
