/*
 * root.js
 *
 * Copyright (c) 2007-2010 by Zelestra, ZELESTRA.COM. All Rights Reserved.
 * Version 3.1 2010-04-29
 * Requires: prototype.js version v1.6.1
 */

var Root = {

	// Constants

	CAPTION_MARGIN: 8,
	CAPTION_MAX_HEIGHT: 140,
	CONTENT_MIN_HEIGHT: 252,
	CONTENT_MIN_WIDTH: 370,
	DEFAULT_MIX_HEIGHT: 600,
	DEFAULT_MIX_WIDTH: 740,
	FLV_CAPTION_HEIGHT: 40,
	FLV_CONTROLS_HEIGHT: 28,
	QT_CONTROLS_HEIGHT: 16,
	SCROLL_BAR_WIDTH: 20,
	WINDOW_MARGIN: 20,

	// Attributes

	bsks: {},

	// Methods

	ensureSession: function(requireAuthn) {
		if (requireAuthn)
			Root._loginCloseBoxEnabled = (requireAuthn === true);
		else {
			Root._loginCloseBoxEnabled = false;
			requireAuthn = (document.parameters["requireAuthn"] == "true");
		}
		if (document.getSessionStorageItem("userId") != null) {
			if (document.getSessionStorageItem("userCategory") == "guest" && requireAuthn) {
				document.removeSessionStorageItem("userId");
				document.removeSessionStorageItem("userCategory");
				document.removeSessionStorageItem("userName");
				document.removeSessionStorageItem("agentId");
				document.postAjaxRequest("http://" + document.identityProviderId + "/services/2001/Realm/logout",{onSuccess: Root._requireLogoutSuccess.bind(this,requireAuthn),onFail:Root._requireLogoutFail});
				return;
			}
		}
		document.removeSessionStorageItem("userId");
		document.removeSessionStorageItem("userCategory");
		document.removeSessionStorageItem("userName");
		document.removeSessionStorageItem("agentId");
		var requireAuthnStr = "";
		if (requireAuthn)
			requireAuthnStr = "&requireAuthn=true";
		document.postAjaxRequest("/services/2001/Realm/getSessionInfo?json=true"+requireAuthnStr, { onSuccess: Root._ensureSessionSuccess.bind(this,requireAuthn),onFail: Root._ensureSessionFail });
	},

	getCacheBuster: function(recalc) {
		if ((recalc == true) || (Root._cacheBuster == null)) {
			Root._cacheBuster = Math.floor(Math.random()*99999999);
			document.setSessionStorageItem("cacheBuster",Root._cacheBuster);
		}
		return Root._cacheBuster;
	},

	getIsMix: function(category) {
		if (category == "mix") return true;
		if (category == "mixClip") return true;
		return false;
	},

	loadBsks: function() {
 	 	for(var i in Root.bsks) {
			document.fire("zlst:bsksLoaded");
			return;
 	 	}
		document.postAjaxRequest("http://" + document.searchProviderId +"/select/?q=set:public&version=2.2&rows=0&facet=true&facet.field=bsk&wt=json",{onSuccess: Root._loadBsksSuccess,onFail:Root._loadBsksFail});
	},

	login: function() {
		document.postAjaxRequest("http://" + document.identityProviderId + "/services/2001/Realm/logout",{onSuccess: Root.ensureSession,onFail: Root.ensureSession});
	},

	logout: function() {
		document.fire("zlst:logout");
		document.removeSessionStorageItem("userId");
		document.removeSessionStorageItem("userCategory");
		document.removeSessionStorageItem("userName");
		document.removeSessionStorageItem("agentId");
		document.postAjaxRequest("http://" + document.identityProviderId + "/services/2001/Realm/logout",{onSuccess: Root._logoutSuccess,onFail:Root._logoutFail});
	},

	openEditor: function(uri) {
		Root.postMetadataRequest(uri,{onSuccess:Root._openEditorSuccess,onFail:Root._openEditorFail.bind(this,uri),include:["dc:title","dc:type,dctypes:Category","dc:format,dcterms:IMT","dcterms:extent,dctypes:WxH","dc:description,dctypes:Caption"]});
	},

	openInfo: function(uri) {
		var requireAuthnStr = "";
		if (document.parameters["requireAuthn"] == "true")
			requireAuthnStr = "&requireAuthn=true";
		window.openPopup("/services/getInfoHtml?uri=" + encodeURIComponent(uri) + requireAuthnStr,600,600);
	},

	openPresenter: function(uri) {
		Root.postMetadataRequest(uri,{onSuccess:Root._openPresenterSuccess,onFail:Root._openPresenterFail.bind(this,uri),include:["dc:title","dc:type,dctypes:Category","dc:format,dcterms:IMT","dcterms:extent,dctypes:WxH","dc:description,dctypes:Caption"]});
	},

	postMetadataRequest: function(uri,options) {
		var tmpOpts = {};
		if (options) {
			if (options.onSuccess)
				tmpOpts.onSuccess = Root.postMetadataSuccess.bind(this,options.onSuccess);
			if (options.onFail)
				tmpOpts.onFail = options.onFail;
			if (options.onProgress)
				tmpOpts.onProgress = options.onProgress;
			if (options.include)
				tmpOpts.include = options.include;
			if (options.include)
				tmpOpts.exclude = options.exclude;
		}
		document.postMetadataRequest(uri,tmpOpts);
	},

	postMetadataSuccess: function(fnc,metadata) {
		var width = 0;
		var height = 0;
		if (Root.getIsMix(metadata.category)) {
			width = Root.DEFAULT_MIX_WIDTH;
			height = Root.DEFAULT_MIX_HEIGHT;
		}
		if (metadata.width)
			width = metadata.width;
		if (metadata.height)
			height = metadata.height;
		if (width < Root.CONTENT_MIN_WIDTH)
			width = Root.CONTENT_MIN_WIDTH;
		if (height < Root.CONTENT_MIN_HEIGHT)
			height = Root.CONTENT_MIN_HEIGHT;
		metadata["contentWidth"] = width;
		metadata["contentHeight"] = height;
		if (metadata.caption) {
			metadata.caption = metadata.caption.replace(/<a/g,"<a target=\"_blank\"");
			if (Root._captionSizer == null) {
				var elem = document.getElementsByTagName("body")[0];
				var captionDiv = new Element("div");
				captionDiv.addClassName("captionSizer");
				elem.appendChild(captionDiv);
				Root._captionSizer = captionDiv;
			}
			width -= (Root.CAPTION_MARGIN * 2);
			Root._captionSizer.setStyle({width:(width+"px")});
			Root._captionSizer.innerHTML = metadata.caption;
			height = Root._captionSizer.getHeight();
			metadata["captionWidth"] = width;
			metadata["captionHeight"] = height;
		} else {
			metadata["captionWidth"] = 0;
			metadata["captionHeight"] = 0;
		}
		fnc(metadata);
	},

	requireLogin: function() {
		document.removeSessionStorageItem("userId");
		document.removeSessionStorageItem("userCategory");
		document.removeSessionStorageItem("userName");
		document.removeSessionStorageItem("agentId");
		document.postAjaxRequest("http://" + document.identityProviderId + "/services/2001/Realm/logout",{onSuccess: Root.ensureSession.bind(this,true),onFail:Root.ensureSession.bind(this,true)});
	},

	// Private

	// attributes
	_cacheBuster: null,
	_captionSizer: null,
	_loginCloseBoxEnabled: false,
	_loginLoaderTimer: null,
	_presenterSizer: null,

	_calcWindowDims: function(metadata) {
		var width = metadata.contentWidth + (Root.WINDOW_MARGIN * 2);
		var height = metadata.contentHeight + (Root.WINDOW_MARGIN * 2);
		if (metadata.category == "quicktime")
			height += Root.QT_CONTROLS_HEIGHT;
		else if (metadata.category == "flashVideo")
			height += Root.FLV_CONTROLS_HEIGHT;
		else if (metadata.category == "biography") {
			height = 640;
			width = 780;
		}
		var cHeight = 0;
		if (metadata.captionHeight) {
			if (cHeight < metadata.captionHeight)
				cHeight = metadata.captionHeight;
			if ((metadata.category == "flashVideo") && (cHeight < Root.FLV_CAPTION_HEIGHT))
				cHeight = Root.FLV_CAPTION_HEIGHT;
			if (cHeight > Root.CAPTION_MAX_HEIGHT) {
				cHeight = Root.CAPTION_MAX_HEIGHT;
				width += Root.SCROLL_BAR_WIDTH;
			}
		} else if (metadata.category == "flashVideo")
			cHeight = Root.FLV_CAPTION_HEIGHT;
		height += cHeight + Root.CAPTION_MARGIN;
		return {width:width,height:height};
	},

	_ensureSessionSuccess: function(requireAuthn,data) {
		var info = data.evalJSON();
		if (info.user && (info.user.length > 0)) {
			if (requireAuthn && (info.userCategory == "guest")) {
				document.removeSessionStorageItem("userId");
				document.removeSessionStorageItem("userCategory");
				document.removeSessionStorageItem("userName");
				document.removeSessionStorageItem("agentId");
				document.postAjaxRequest("http://" + document.identityProviderId + "/services/2001/Realm/logout",{onSuccess: Root._requireLogoutSuccess.bind(this,requireAuthn),onFail:Root._requireLogoutFail});
				return;
			}
			document.setSessionStorageItem("userId",info.user);
			if (!info.userCategory)
				info.userCategory = "";
			document.setSessionStorageItem("userCategory",info.userCategory);
			if (!info.userName)
				info.userName = info.user;
			document.setSessionStorageItem("userName",info.userName);
			if (!info.agent)
				info.agent = "";
			document.setSessionStorageItem("agentId",info.agent);
			if (!info.virtualSpace)
				info.virtualSpace = "";
			document.setSessionStorageItem("virtualSpaceId",info.virtualSpace);
			_gaq.push(["_setCustomVar",1,"username",info.user.basename(),2]);
			document.fire("zlst:login");
		} else
			Root._ensureSessionFail();
	},

	_ensureSessionFail: function() {

		var loginOverlay = new Element("div",{id:"loginOverlay",'class':"loginOverlay"});
		var box = new Element("div",{'class':"loginBox"});

		if (Root._loginCloseBoxEnabled) {
			var closeBox = new Element("div",{id:"loginCloseBox",'class':"loginCloseBox"});
			box.appendChild(closeBox);
		}

		var logo = new Element("div",{id:"loginLogo",'class':"loginLogo"});
		box.appendChild(logo);

		var loader = new Element("div",{id:"loginLoader",'class':"loginLoader"});
		box.appendChild(loader);

		var userIdLabel = new Element("p",{'class':"loginUserIdLabel"});
		userIdLabel.innerHTML = "email or user ID:";
		box.appendChild(userIdLabel);

		var username = new Element("input",{id:"loginUsername",'class':"loginUsername",type:"text"});
		box.appendChild(username);

		var passwordLabel = new Element("p",{'class':"loginPasswordLabel"});
		passwordLabel.innerHTML="password (case sensitive):";
		box.appendChild(passwordLabel);

		var password = new Element("input",{id:"loginPassword",'class':"loginPassword",type:"password"});
		box.appendChild(password);

		var loginInvalid = new Element("p",{id:"loginInvalid",'class':"loginInvalid"});
		loginInvalid.innerHTML="Invalid Sign In!";
		box.appendChild(loginInvalid);

		var loginButton = new Element("div",{id:"loginButton",'class':"loginButton"});
		box.appendChild(loginButton);

		var forgotLink = new Element("a",{id:"loginForgotLink",'class':"loginForgotLink"});
		forgotLink.innerHTML="Forgot your password?";
		box.appendChild(forgotLink);

		var registerButton = new Element("div",{id:"loginRegisterButton",'class':"loginRegisterButton"});
		box.appendChild(registerButton);

		loginOverlay.appendChild(box);
		document.body.appendChild(new Element("div",{id:"lightBox",'class':"lightBox"}));
		document.fire("zlst:lightBoxOpen");
		document.body.appendChild(loginOverlay);
    	if (Root._loginCloseBoxEnabled)
    		$("loginCloseBox").setSimpleLink(Root._loginClose).setEnabled(true);
		$("loginLogo").setSimpleLink("/").setEnabled(true);
    	Event.observe($("loginUsername"),"keydown",Root._loginKeyUsername);
    	Event.observe($("loginPassword"),"keydown",Root._loginKeyPassword);
    	$("loginButton").setSimpleLink(Root._loginSubmit).setEnabled(true);
  		$("loginUsername").setEnabled(true).focus();
    	$("loginPassword").setEnabled(true);
		$("loginForgotLink").setSimpleLink(Root._loginForgotSubmit).setEnabled(true);
    	$("loginRegisterButton").setSimpleLink(Root._loginRegisterSubmit).setEnabled(true);
	},

	_loadBsksSuccess: function(data) {
		var response = data.evalJSON();
		try {

			var tmpCodes = response.facet_counts.facet_fields.bsk;
			for(var i=0;i<tmpCodes.length;i+=2) {
				Root.bsks[tmpCodes[i]] = tmpCodes[i+1];
			}
		} catch(error) {
			Root.bsks = {};
			Root._loadBsksFail(0,"Results not parsable.");
		}
		document.fire("zlst:bsksLoaded");
	},

	_loginForgotSubmit: function() {
		window.open("/newPassReq.html");
	},

	_loginClose: function() {
		document.body.removeChild($("loginOverlay"));
		document.fire("zlst:lightBoxClose");
		document.body.removeChild($("lightBox"));
		document.fire("zlst:cancelLogin");
	},

	_loginSubmit: function() {
		$("loginUsername").setEnabled(false);
		$("loginPassword").setEnabled(false);
		$("loginButton").setEnabled(false);
		$("loginForgotLink").setEnabled(false);
		$("loginRegisterButton").setEnabled(false);
		var username = $("loginUsername").value;
		var password = $("loginPassword").value;
		var variables = "username=" + username + "&password=" + password;
		Root._setLoginLoaderEnabled(true);
		document.postAjaxRequest("https://" + document.identityProviderId + "/services/2001/Realm/login",{method:"POST",data:variables,onSuccess:Root._loginSuccess,onFail:Root._loginFail});
	},

	_loginKeyUsername: function(event) {
		$("loginInvalid").setEnabled(false);
		if ((event.which && event.which == 13) ||
			(event.keyCode && event.keyCode == 13)) {
			$("loginUserId").focus();
   			$("loginPassword").select();
			return true;
		}
		return true;
	},

	_loginKeyPassword: function(event) {
		$("loginInvalid").setEnabled(false);
		if ((event.which && event.which == 13) ||
			(event.keyCode && event.keyCode == 13)) {
			Root._loginSubmit();
			return true;
		}
		return true;
	},

	_setLoginLoaderEnabled: function(enabled) {
		if (enabled) {
			if (Root._loginLoaderTimer == null)
				Root._loginLoaderTimer = window.setTimeout($("loginLoader").setEnabled.bind($("loginLoader"),true),500);
			return;
		}
		if (Root._loginLoaderTimer != null) {
			window.clearTimeout(Root._loginLoaderTimer);
			Root._loginLoaderTimer = null;
		}
		$("loginLoader").setEnabled(false);
	},

	_loginRegisterSubmit: function() {
		window.open("/newUserReq.html");
	},

	_loginSuccess: function() {
		Root._setLoginLoaderEnabled(false);
		document.body.removeChild($("loginOverlay"));
		document.fire("zlst:lightBoxClose");
		document.body.removeChild($("lightBox"));
		Root.ensureSession();
	},

	_loginFail: function(statusCode,message) {
		Root._setLoginLoaderEnabled(false);
		$("loginRegisterButton").setEnabled(true);
		$("loginForgotLink").setEnabled(true);
		$("loginButton").setEnabled(true);
		$("loginUsername").setEnabled(true);
		$("loginPassword").value = "";
		$("loginPassword").setEnabled(true);
		$("loginPassword").focus();
		$("loginInvalid").setEnabled(true);
	},

	_logoutSuccess: function() {
		window.location.href="/";
	},

	_logoutFail: function() {
		window.location.href="/";
	},

	_onLoad: function() {
		if($("closeWindowLink") && window.opener)
			$("closeWindowLink").setEnabled(true);
		Root._cacheBuster = document.getSessionStorageItem("cacheBuster");
	},

	_openEditorFail: function(uri) {
		window.open("/services/getEditorHtml?uri=" + encodeURIComponent(uri) + "&requireAuthn=true");
	},

	_openEditorSuccess: function(metadata) {
		if (((metadata.category != "web") && (metadata["dc:format"]) && (metadata["dc:format"]["dcterms:IMT"] == "text/html")) ||
			((metadata.category == "web") && !metadata.width && !metadata.height)) {
			window.open(metadata.uri);
			return;
		}
		var dims = Root._calcWindowDims(metadata);
		var requireAuthnStr = "";
		if (document.parameters["requireAuthn"] == "true")
			requireAuthnStr = "&requireAuthn=true";
		window.openPopup("/services/getEditorHtml?uri=" + encodeURIComponent(metadata.uri) + requireAuthnStr,dims.width,dims.height);
	},

	_openPresenterFail: function(uri) {
		window.open("/services/getPresenterHtml?uri=" + encodeURIComponent(uri) + "&requireAuthn=true");
	},

	_openPresenterSuccess: function(metadata) {
		if (((metadata.category != "web") && (metadata["dc:format"]) && (metadata["dc:format"]["dcterms:IMT"] == "text/html")) ||
			((metadata.category == "web") && !metadata.width && !metadata.height)) {
			window.open(metadata.uri);
			return;
		}
		var dims = Root._calcWindowDims(metadata);
		var requireAuthnStr = "";
		if (document.parameters["requireAuthn"] == "true")
			requireAuthnStr = "&requireAuthn=true";
		window.openPopup("/services/getPresenterHtml?uri=" + encodeURIComponent(metadata.uri) + requireAuthnStr,dims.width,dims.height);
	},

	_requireLogoutSuccess: function(requireAuthn) {
		var requireAuthnStr = "";
		if (requireAuthn)
			requireAuthnStr = "&requireAuthn=true";
		document.postAjaxRequest("http://" + document.identityProviderId + "/services/2001/Realm/getSessionInfo?json=true"+requireAuthnStr, { onSuccess: Root._ensureSessionSuccess.bind(this,requireAuthn),onFail: Root._ensureSessionFail});
	},

	_requireLogoutFail: function() {
		window.location.href="/";
	}

};

Element.addMethods( {
	setEditorLink: function(elem,uri) {
		return elem.setSimpleLink(Root.openEditor.bind(window,uri));
	},
	setInfoLink: function(elem,uri) {
		return elem.setSimpleLink(Root.openInfo.bind(window,uri));
	},
	setPresenterLink: function(elem,uri) {
		return elem.setSimpleLink(Root.openPresenter.bind(window,uri));
	}
});

document.serviceProviderId = "as1.contentclips.com";
document.searchProviderId = "as2.contentclips.com";
Event.observe(window, "load", function() {
	Root._onLoad();
});

var _gaq = _gaq || [];
if (document.localProviderId == "www.contentclips.com")
	_gaq.push(["_setAccount","UA-5355870-6"]);
else
	_gaq.push(["_setAccount","UA-5355870-15"]);
if (document.parameters["whence"] && (document.getSessionStorageItem("whence")== null)) {
	var whence = document.parameters["whence"];
	if (whence > 31)
		whence = whence.substring(0,31);
	document.setSessionStorageItem("whence",whence);
	_gaq.push(["_setCustomVar",2,"whence",whence,2]);
}

