function clearInnerHTML(obj) {
	/*
	 * Empties a DIV of all children
	 */
	try {
		if (obj == null || obj == undefined)
			return;
		while (obj.firstChild != null && obj.firstChild != undefined) {
			obj.removeChild(obj.firstChild);
		}
		obj.innerHTML = "";
		// obj.style.display='none';
	} catch (e) {
	}
}

function removeHTMLElement(obj){
	try {
		if (obj == null || obj == undefined)
			return;
		 	obj.parentNode.removeChild(obj);
	 
	} catch (e) {
	}
}
function getURLParam(url) {
	// this is used to extract param from the url
	// they are only separated by commas
	var urlquery = ((url == null || url == undefined) ? location.href
			.split("?") : url.split("?"));
	if (urlquery.length < 2)
		return null;
	var rnurlterms = urlquery[1].split("&");
	return rnurlterms;
}
function getParamFromURL(url, param) {

	var paramArray = [];
	paramArray = getURLParam(url);
	if (paramArray == null)
		return null;
	for ( var i = 0; i < paramArray.length; i++) {
		if (paramArray[i].indexOf(param) != -1) {
			var ret = paramArray[i].substr(paramArray[i].indexOf('=') + 1);
			// remove # from url content
			ret = ret.replace('#', '');
			return ret;
		}
	}
	return null;
}

// ------------------------- locale utility
// ---------------------------------------------------

function getLocale(id) {
	try {
		initLocale();// init if necessary
		var ret = null;

		try {

			if (bundle == null || bundle == undefined) {
				bundle = dojo.i18n.getLocalization("my.app", "resBundle");
			}
			var ret = eval("bundle." + id);
			if (ret == undefined)
				console.debug("locale : " + id + " not found ");
			return ret;
		} catch (e) {
		}
	} catch (e) {
		console.debug("Unable to retrive locale data - msg:" + e.message);
		return null;
	}
}

function getLocaleStr(id, defaultValue) {
	var ret = getLocale(id);
	if (ret == null || ret == undefined || ret == "") {
		return defaultValue;
	}
	return ret;
}

function initLocale() {
	// localInitialised is set to false when there is a need for a locale
	// refresh
	try {
		if (!(getCookie("localInitialised") == "true")) {

			setCookie("localInitialised", "true", null, null, null, null);

			var currentLocale = getCookie('currentLocale');
			currentLocale = currentLocale == null ? "en" : currentLocale;
			djConfig.locale = currentLocale;
			bundle = dojo.i18n.getLocalization("my.app", "resBundle");

		}
	} catch (e) {
	}
}

// --------------------------------------------------------------------------------------------

function setCookie(name, value, expires, path, domain, secure) {
	var curCookie = name + "=" + escape(value)
			+ ((expires) ? "; expires=" + expires.toGMTString() : "")
			+ ((path) ? "; path=" + path : "")
			+ ((domain) ? "; domain=" + domain : "")
			+ ((secure) ? "; secure" : "");
	document.cookie = curCookie;
}

function getCookie(name) {
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0)
			return null;
	} else
		begin += 2;
	var end = document.cookie.indexOf(";", begin);
	if (end == -1)
		end = dc.length;
	return unescape(dc.substring(begin + prefix.length, end));
}

function getMousePos(e) {
	var pos = [];
	var docX, docY;
	if (e) {
		if (typeof (e.pageX) == 'number') {
			docX = e.pageX;
			docY = e.pageY;
		} else {
			docX = e.clientX;
			docY = e.clientY;
		}
	} else {
		e = window.event;
		docX = e.clientX;
		docY = e.clientY;
		if (document.documentElement
				&& (document.documentElement.scrollTop || document.documentElement.scrollLeft)) {
			docX += document.documentElement.scrollLeft;
			docY += document.documentElement.scrollTop;
		} else if (document.body
				&& (document.body.scrollTop || document.body.scrollLeft)) {
			docX += document.body.scrollLeft;
			docY += document.body.scrollTop;
		}
	}

	pos[0] = docX;
	pos[1] = docY;

	return pos;
}

// / --------------------------------------------------------------------------
function hasSignedIn() {
	var id = getCookie('CompId');
	if (id == null || id == "" || id == undefined || id == "null") {
		verifyOpenSocialStatus();
		return false;
	} else
		return true;
}
function signout() {
	setCookie("CompId", null, null, null, null, null);
	// delete session attributes
	try {
		WebRemoting.signout( function(data) {
		});
	} catch (e) {
		dojo
				.xhrGet( {
					url :'service?action=notification&notificationType=initSession&CompId=&UserId=',
					handleAs :'xml',
					load : function(data, evt) {

					}
				});
	}
}
function signin() {

	var compId = getCookie('CompId');
	if (compId != null && compId != undefined && compId != "null")
		return;
	if(facebook){
		signinFacebookUser();
	}else{
	showDialogBox(false, 'signin.html',
			getLocaleStr('menu_signin', 'Signin ..'), 350, 180);
	}

	/*
	 * //store current page in session variable so as to able to return to the
	 * page
	 * 
	 * try{ dojo.xhrGet( {
	 * url:'service?action=notification&notificationType=initSession&NextPageUrl='+location.href,
	 * handleAs: 'xml', load: function(data, evt){ //after success
	 * alert(getLocaleStr("signin_msg","Please sign in"));
	 * location.href="showSignin.jsp"; }} ); }catch(e){}
	 */

}
function fireScriptAfterLogin() {
	var script = getCookie('scriptAfterLogin');
	if (script) {
		try {
			eval(script);
		} catch (e) {
		}
		setCookie('scriptAfterLogin', null, null, null, null, null);
	}
}

/*
 * DWR functions
 * 
 */

function forward(pageUrl, div) {
	WebRemoting.getInclude(pageUrl, function(data) {
		 dwr.util.setValue(div, data, {
			escapeHtml :false
		});
	});
}
function errh(msg) {
	/*
	 * var localeMsg = getLocale(msg); if (localeMsg == null) {
	 * tellUser(msg,true); } else { tellUser(localeMsg,true); }
	 */
}

// dwr.engine.setErrorHandler(errh);
/*
 * DOM Manipulation
 * 
 */
function createLabelElement(id, title) {
	/*
	 * Returns a label node
	 */
	var colTitleLabel = document.createElement("label");
	colTitleLabel.innerHTML = title;
	colTitleLabel.className = "label";
	colTitleLabel.id = id;
	return colTitleLabel;
}
function createInputElement(id, value, type) {
	/*
	 * Returns an input of type node
	 */
	var inp = document.createElement("input");
	inp.value = value;
	if (type == 'text')
		inp.className = "text-box textfield";
	else
		inp.className = "text-box";

	inp.type = type;
	inp.id = id;
	return inp;
}
function createSelectElement(id) {
	/*
	 * Returns an select of type node
	 */
	var inp = document.createElement("select");
	inp.className = "select-box textfield";
	inp.id = id;
	return inp;
}
function createTextareaElement(id, value) {
	/*
	 * Returns an textarea of type node
	 */
	var inp = document.createElement("textarea");
	inp.value = value;
	inp.className = "textfield";
	inp.id = id;
	return inp;
}
function $(elementId) {
	return document.getElementById(elementId);
}

function purchaseContent(contentId, callbackFunction) {
	setCookie("contentId", contentId);
	setCookie("purchaseContentCallbackFunction", callbackFunction);
	showDialogBox(false, 'content-pricing.html', getLocaleStr('buy_content',
			'Acquire Content ..'), 350, 150);
}
function showRegistration() {
	showDialogBox(false, 'register-user.html', getLocaleStr('nav_register',
			'Sign-up ..'), 550, 250);

}
var FACEBOOK_INVITATION_MSG="Checkout this Multimedia App"
function showUserInvitation() {
	if(facebook){
		facebook.sendRequestViaMultiFriendSelector(FACEBOOK_INVITATION_MSG,function(data){
			//data contains the id of the request send and the users it  was sent to
			//alert("Message was sent successfully");
		});
	}else{
	showDialogBox(true, 'invite.html', "Find your Friends ...", 450,
			250);
	}
}
function showAccessRestriction(contentId, mediaType) {
	setCookie("MediaType", mediaType);
	setCookie("contentId", contentId);
	showDialogBox(true, 'access_restriction.html', getLocaleStr('security',
			'Security ..'), 350, 300);
}
function showContentUpload() {
	setCookie("VideoUploadMode", "U", null, null, null, null);
	showDialogBox(false, "content-upload.html", getLocaleStr("upload",
			"Upload .."), 685, 300);

}
function showCollectionAssignment() {
	showDialogBox(true, 'collection_assignment.html', getLocaleStr(
			'collection_title', 'Collection ..'), 740, 550);
}

function reportUserAction(actionReferenceCode, actionData,actionData2,actionData3,actionData4) {
	try {
		WebRemoting.setUserAction(actionReferenceCode, actionData, function(
				data) {
		}); 
	} catch (e) {
	}
	
	try{if(getCookie("hasChatSessionCtl")=="true"){
		channelUserActionToChat(actionReferenceCode, actionData,actionData2,actionData3,actionData4);
		}
	} catch (e) {
	}
}

function sendEmailVerification() {
	try {
		WebRemoting.sendEmailVerification( function(data) {
		});
	} catch (e) {
	}
}
function updateIndex(contentId) {
	/*
	 * called anytime content info in database needs to be synch with lucene
	 * index
	 */
	dojo.xhrPost( {
		url :"service?action=updateIndex&contentId=" + contentId,
		load : function(data, evt) {
		},
		handleAs :"json"
	});

}
function deleteFromIndex(contentId) {
	dojo.xhrPost( {
		url :"service?action=updateIndex&delete=true&contentId=" + contentId,
		load : function(data, evt) {
		},
		handleAs :"json"
	});

}

function verifyOpenSocialStatus() {
	// load the data using open social
	if (!openSocialAuthInProgress) {
		var params = {
			"profileDetail" : [ opensocial.Person.Field.ID,
					opensocial.Person.Field.NAME,
					opensocial.Person.Field.THUMBNAIL_URL,
					opensocial.Person.Field.ABOUT_ME,
					opensocial.Person.Field.PROFILE_URL,
					opensocial.Person.Field.NAME,
					opensocial.Person.Field.EMAILS ]
		};

		var req = opensocial.newDataRequest();
		req.add(req.newFetchPersonRequest('VIEWER', params), 'viewer');

		/*
		 * req.add(req.newFetchPeopleRequest(opensocial.newIdSpec( { "userId"
		 * :"OWNER", "groupId" :"FRIENDS" }), params), "req");
		 */
		req.send(onLoadGFCCallback);
	}
}

function extractOpenSocialEmail(emails) {
	if (emails && emails.length > 0) {
		try {
			return emails[0].subStr(emails[0].indexOf(">"), emails[0].indexOf(
					"<", emails[0].indexOf(">")));
		} catch (e) {
		}
	}
	return null;
}
var openSocialAuthInProgress = false;
// called after data is loaded
function onLoadGFCCallback(data) {

	if (data.get('viewer').getData()) {
		var person = data.get('viewer').getData();
		var id = person.getField(opensocial.Person.Field.ID);
		var userId = person.getField("displayName");
		var name = person.getField(opensocial.Person.Field.NAME);
		var logoLink = person.getField(opensocial.Person.Field.THUMBNAIL_URL);
		var website = person.getField(opensocial.Person.Field.PROFILE_URL);

		var emails = person.getField(opensocial.Person.Field.EMAILS);
		var aboutMe = person.getField(opensocial.Person.Field.ABOUT_ME);

		openSocialAuthInProgress = true;
		RegisterUser.registerUser((!userId ? name : userId),
				extractOpenSocialEmail(emails), id, id, (name ? name : userId),
				aboutMe, logoLink, website, function(data) {
					openSocialAuthInProgress = false;
					signinOpenSocialUser(!userId ? name : userId, id);

				});

	} else {

	}
}
function openSocialSigninListener(securityToken){
	verifyOpenSocialStatus();
}
function signinOpenSocialUser(userId, pwd) {
	WebRemoting
			.validateUser(
					userId,
					pwd,
					function(data) {
						if (data == null) {
						} else {
							setCookie("CompId", data.compId, null, null, null,
									null);
							setCookie("UserId", data.userId, null, null, null,
									null);
							setCookie("UserType", data.userType, null, null,
									null, null);
							try {
								var welcomeLink = this.parent.document
										.getElementById("headerSection:welcome-user");
								welcomeLink.innerHTML = data.userId;
								welcomeLink.href = "profile.html?pageId="
										+ getCookie("CompId") + "&ownerId="
										+ getCookie("CompId");
								this.parent.document
										.getElementById("headerSection:welcome-user-label").innerHTML = getLocaleStr(
										"welcome", "Welcome");
								this.parent.document
										.getElementById("headerSection:sign-in").innerHTML = getLocaleStr(
										"sign-out", "Sign Off");

							} catch (e) {
							}

							try {
								this.parent.DHTML_modalMessage.prototype
										.close();
								this.parent.fireScriptAfterLogin();
							} catch (e) {
							}

							reportUserAction("signed_in::", null);
						}
					});

}
function isValidEmail(email){
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	return filter.test(email) ;
	 
}

function translateText(outputElementId, txt) {
	try{
	var curLocale=getCookie('currentLocale');
	google.language.translate(txt, "", curLocale?curLocale:"en", function(result) {
		if (!result.error) {
			var container = document.getElementById(outputElementId);
			container.innerHTML = result.translation;
		}
	});
	}catch(e){}
}

