
var emailPat=new RegExp(/^([\w\-\.]+)@((\[([0-9]{1,3}\.){3}[0-9]{1,3}\])|(([\w\-]+\.)+)([a-zA-Z]{2,4}))$/);var urlPat=new RegExp(/^((http(s?))\:\/\/)?([0-9a-zA-Z\-]+\.)+[a-zA-Z]{2,6}(\:[0-9]+)?(\/\S*)?$/);var datePat=new RegExp(/^(?=\d)^(?:(?!(?:10\D(?:0?[5-9]|1[0-4])\D(?:1582))|(?:0?9\D(?:0?[3-9]|1[0-3])\D(?:1752)))((?:0?[13578]|1[02])|(?:0?[469]|11)(?!\/31)(?!-31)(?!\.31)|(?:0?2(?=.?(?:(?:29.(?!000[04]|(?:(?:1[^0-6]|[2468][^048]|[3579][^26])00))(?:(?:(?:\d\d)(?:[02468][048]|[13579][26])(?!\x20BC))|(?:00(?:42|3[0369]|2[147]|1[258]|09)\x20BC))))))|(?:0?2(?=.(?:(?:\d\D)|(?:[01]\d)|(?:2[0-8])))))([-.\/])(0?[1-9]|[12]\d|3[01])\2(?!0000)((?=(?:00(?:4[0-5]|[0-3]?\d)\x20BC)|(?:\d{4}(?!\x20BC)))\d{4}(?:\x20BC)?)(?:$|(?=\x20\d)\x20))?((?:(?:0?[1-9]|1[012])(?::[0-5]\d){0,2}(?:\x20[aApP][mM]))|(?:[01]\d|2[0-3])(?::[0-5]\d){1,2})?$/);var detect=navigator.userAgent.toLowerCase();var ECHO_DEBUG=true;var moment=new Date();var moment1=new Date(moment.getUTCFullYear()+1,moment.getUTCMonth(),moment.getUTCDate());var moment0=new Date(moment.getUTCFullYear()-1,moment.getUTCMonth(),moment.getUTCDate());var sceneForDeletion=0;var previewedScene=0;var ECHO_DEBUG=true;var contentHolder,contentHeight,contentWidth;var topWin=top;var arrayNavImgs=["my_voki","voki_apps","voki_blog","account_info","partners"];var arrayProtectedPages=['account_info','mywebsite','to_me','to_others','about_me'];
//base_global.js
var emailPat 	= new RegExp(/^([\w\-\.]+)@((\[([0-9]{1,3}\.){3}[0-9]{1,3}\])|(([\w\-]+\.)+)([a-zA-Z]{2,4}))$/);

var urlPat	 	= new RegExp(/^((http(s?))\:\/\/)?([0-9a-zA-Z\-]+\.)+[a-zA-Z]{2,6}(\:[0-9]+)?(\/\S*)?$/);

var datePat 	= new RegExp(/^(?=\d)^(?:(?!(?:10\D(?:0?[5-9]|1[0-4])\D(?:1582))|(?:0?9\D(?:0?[3-9]|1[0-3])\D(?:1752)))((?:0?[13578]|1[02])|(?:0?[469]|11)(?!\/31)(?!-31)(?!\.31)|(?:0?2(?=.?(?:(?:29.(?!000[04]|(?:(?:1[^0-6]|[2468][^048]|[3579][^26])00))(?:(?:(?:\d\d)(?:[02468][048]|[13579][26])(?!\x20BC))|(?:00(?:42|3[0369]|2[147]|1[258]|09)\x20BC))))))|(?:0?2(?=.(?:(?:\d\D)|(?:[01]\d)|(?:2[0-8])))))([-.\/])(0?[1-9]|[12]\d|3[01])\2(?!0000)((?=(?:00(?:4[0-5]|[0-3]?\d)\x20BC)|(?:\d{4}(?!\x20BC)))\d{4}(?:\x20BC)?)(?:$|(?=\x20\d)\x20))?((?:(?:0?[1-9]|1[012])(?::[0-5]\d){0,2}(?:\x20[aApP][mM]))|(?:[01]\d|2[0-3])(?::[0-5]\d){1,2})?$/);

var detect = navigator.userAgent.toLowerCase();
var ECHO_DEBUG	= true;
var moment	= new Date();
var moment1 = new Date(moment.getUTCFullYear() + 1, moment.getUTCMonth(), moment.getUTCDate() );
var moment0 = new Date(moment.getUTCFullYear() - 1, moment.getUTCMonth(), moment.getUTCDate() );

var sceneForDeletion 	= 0;
var previewedScene		= 0;
var ECHO_DEBUG			= true;
var contentHolder, contentHeight, contentWidth;

var topWin 				= top;
var arrayNavImgs 		= ["my_voki", "voki_apps", "voki_blog", "account_info", "partners"];

var arrayProtectedPages = ['account_info', 'mywebsite', 'to_me', 'to_others', 'about_me'];
//base_utils.js
// *********************
//  UTILITY FUNCTIONS
// *********************


function debug(str, level){
	var level = level || 1
	var dontdebug		= document.dontdebug || false;

	if (this.dontdebug == true || (location.host.indexOf('-vd') < 0 && location.host.indexOf('-vs') < 0 ))
		return true;	

	candebug		= false;
	consoledebug	= false;
	warndebug		= false;
	forceOutput		= document.forceOutput || false;
	
	if ($('#debug'))
		this.candebug	= true;	
	
	if (window.console)	{
		if (window.console.log){
			this.consoledebug	= true;
			this.candebug		= true;	
		}
		
		if (window.console.warn){
			this.warndebug	= true;
		}
	}
	
	if (level == 1 && consoledebug) {		
		console.log(str);
	}
	if (level == 2 && warndebug) {		
		console.warn(str);
	}
	return true;
};

function hideProc(){ 
	topWin.$('TACoverlay').hide();
	topWin.$('Processing').hide();
}

function showDimensions() {
	var selected = document.formEmbedOptions.size.selectedIndex;
	if (document.formEmbedOptions.size.options[selected].value.indexOf("custom") != -1) {
		$("widthHeight").style.display = "block";
	} else {
		$("widthHeight").style.display = "none";
		if (document.formEmbedOptions.size.options[selected].value.indexOf("300") != -1) {
			document.formEmbedOptions.customWidth.value = 300;
			document.formEmbedOptions.customHeight.value = 400;
		} else {
			document.formEmbedOptions.customWidth.value = 200;
			document.formEmbedOptions.customHeight.value = 267;
		}
	}
}

function debugNoFB(str){
	var dbem = $('debugDiv');
	if (!dbem){	
		dbem	= document.createElement('DIV');
        dbem.style.display = "block";    
        dbem.id = "debugDiv";    
        dbem.style.zIndex = "2147483647";
        dbem.style.position = "absolute";
        dbem.style.background = "#FFFFFF";
        dbem.style.color = "#000000";
        dbem.style.width = "100%";
        dbem.style.left = "0";
        dbem.style.overflow = "auto";
        dbem.style.bottom = "0";
        dbem.style.height = "200px";
        document.body.appendChild(dbem);
	}	
	
	dbem.innerHTML	+= str + '<br>';
}

function grabQueryValue(qName){
	try{
		var q = location.search;
		
		if (q.indexOf(qName + '=') == -1)
			return false;
	
		q = q.substring(q.indexOf(qName) + (qName.length + 1));
	
		q = q.split('&')[0];
	} catch (e){alert(e);}

	return q;
}


function spaceTrim(text) {

	while (text.charAt(0) == " ") {
		text = text.substring(1);
	}

	while (text.charAt(text.length-1) == " ") {
		text = text.substring(0,text.length-1);
	}

	return text;
}

/** Depecarte this later.  **/
function truncate(text,chars) {
	if (text.length <= chars) {
		return text;
	} else {
		var newText = text.substring(0,chars);
		var breakSpot = /[ \.\?\!\;\,\:]/;
		// make sure there is at least one breakspot, if not return as is plus elipses
		if (newText.match(breakSpot) == null) {
			document.write(newText += "&#0133;");
		}
		// find the first break character from the end
		while (newText.charAt(newText.length-1).match(breakSpot) == null) {
			newText = newText.substring(0,newText.length-1);
		}
		// find the first real character from the new end
		while (newText.charAt(newText.length-1).match(breakSpot) != null) {
			newText = newText.substring(0,newText.length-1);
		}
		return newText += "&#0133;";
	}
}


function validateEmail(email)
{
	var addressPattern = /^(.+)@(.+)\.(.+)$/;

	if (addressPattern.test(email))
		return true;
	else
		return false;
}

// ***********************
//  MISC FUNCTIONS
// ***********************

function VHSS_DoFSCommand() {}


function updateViewOption(newTarget)
{
	if (document.getElementById('divMyVokis_viewoptions'))
	{
		var optionLinks = document.getElementsByTagName('a');

		for (a=0; a < optionLinks.length; a++)
		{
			optionLinks[a].className = '';
		}
	}

	newTarget.className = 'viewOptions_selected';
	newTarget.blur();
}


function populateSelect(source,sTarget)
{
	//if (!document.getElementById(source) || !document.getElementById(sTarget)) return;
	var t = document.getElementById(sTarget);
	for(j=0; j < document.setAccountInfo.elements.length; j++) {
		var elem = document.setAccountInfo.elements[j];
		if (elem.type == "hidden" && elem.name == source) {
			var theValue = elem.value;
			break;
		}
	}
	for (p=0; p < t.options.length; p++) {
		if (t.options[p].value == theValue) {
			t.selectedIndex = p;
			return;
		}
	}
}


function howLongAgo(dateStr, level){
	if (!level)
		level	= 2;
		
	var dateArray 	= dateStr.split(' ');
	var dayArr 		= dateArray[0].split('-');
	var year 		= parseInt(dayArr[0]);
	var month 		= parseInt(dayArr[1].replace('0','')) - 1;
	var day 		= parseInt(dayArr[2]);
	var hourArr 	= dateArray[1].split(':');
	var hour 		= parseInt(hourArr[0]);
	var minute 		= parseInt(hourArr[1]);
	var sec 		= parseInt(hourArr[2]);
	var created 	= new Date(year,month,day,hour,minute,sec);
	var rightNow 	= new Date();
	var dateDiff 	= new Date(parseInt(rightNow.getTime()) - parseInt(created.getTime()));
	var years		= dateDiff.getYear();
	var months 		= dateDiff.getMonth();
	var days 		= dateDiff.getDate();
	var hours 		= dateDiff.getHours();
	var mins 		= dateDiff.getMinutes();
	var ret			= '';
	var curLvl		= 0;
	var years		= 0;
	//years
	if (years = 1){
		ret		= years + ' Year ';
		curLvl++;
	}
	
	if (years > 1){
		ret		= years + ' Year(s) ';
		curLvl++;
	}
	
	if (curLvl	== level){
		return ret;
	}
	//months
	if (months == 1){
		ret		+=  months + ' Month ';
		curLvl++;
	}
	
	if (months > 1){
		ret		+=  months + ' Months ';
		curLvl++;
	}
	
	if (curLvl	== level){
		return ret;
	}
	//days
	if (days == 1){
		ret		+=  days + ' Day ';
		curLvl++;
	}
	
	if (days > 1){
		ret		+=  days + ' Days ';
		curLvl++;
	}
	if (curLvl	== level){
		return ret;
	}
	
	//hours
	if (hours == 1){
		ret		+=  hours + ' Hour ';
		curLvl++;
	}
	
	if (hours > 1){
		ret		+=  hours + ' Hours ';
		curLvl++;
	}
	if (curLvl	== level){
		return ret;
	}
	
	//mins
	if (mins == 1){
		ret		+=  mins + ' Min ';
	}
	
	if (mins > 1){
		ret		+=  mins + ' Mins ';
	}
	
	return ret;
}

function getPageSize(parent){
	parent = parent || document.body;              
	var windowWidth, windowHeight;
	var pageHeight, pageWidth;
	
	if (parent != document.body) {
		windowWidth = parent.getWidth();
		windowHeight = parent.getHeight();                                
		pageWidth = parent.scrollWidth;
		pageHeight = parent.scrollHeight;                                
	} else {
		var xScroll, yScroll;
		
		if (window.innerHeight && window.scrollMaxY) {  
			xScroll = document.body.scrollWidth;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
	
		if (self.innerHeight) {  // all except Explorer
			windowWidth = self.innerWidth;
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}  
		
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}
	
	// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){  
			pageWidth = windowWidth;
		} else {
			pageWidth = xScroll;
		}
	}  
	           
	return {pageWidth: pageWidth ,pageHeight: pageHeight , windowWidth: windowWidth, windowHeight: windowHeight};
};


function hideProcessLogin(){
	//very triky thing should be remebered
	top.frames['frmLogin'].document.getElementById('Processing').style.display = 'none';
	parent.closeModal();	
};
//base_modal.js
// ********************************
// MODAL WINDOW CONTROLS
// modalSizes also controls Iframe scrollbars display 
// ********************************
if (!topWin){
	alert("topWin is not set.  You must set topWin in order to use this library");
}

var modalSizes	= $H({
	regWindow:		{width: 560, height: 475}, 	//REGISTRATION WINDOW
  regWindowVC:  {width: 720, height: 480},	// REGISTRATION CLASSROOM
  regWindowCalledBack: {width: 720, height: 480}, //back button from multipaypal
	tagWindow:		{width: 500, height: 220}, //
	blocked:			{width: 400, height: 200},
	loginWin:			{width: 400, height: 140},
	thanksWin:		{width: 400, height: 125}, // Scene Saved Window
	embedCode:		{width: 370, height: 330},
	regThank:			{width: 550, height: 125},
	createVoki:		{width: 400, height: 260},
	publish:			{width: 410, height: 520}, // EMBED CODE
	sceneSet:			{width: 375, height: 200},
	editorWin:		{width: 570, height: 436},
	changePass:		{width: 300, height: 200},
	forgotPass:		{width: 400, height: 250},
	STAF:					{width: 350, height: 425},
	partTNC:			{width: 500, height: 360},
	partThanks:		{width: 500, height: 260},
	TACWindow:		{width: 418, height: 500}		// TERMS OF SERVICE WINDOW	
});

function getContentProperties() {
	if ($('tblFrame'))
		contentHolder = $('tblFrame');
	else
		contentHolder = document.body;
		contentHeight = contentHolder.offsetHeight;
		contentWidth 	= contentHolder.offsetWidth;
}

function detectTopScroll() {
	var scroll_Y;
	if (document.documentElement) {scroll_Y = document.documentElement.scrollTop + document.body.scrollTop;}
	if (window.scrollY) {scroll_Y = window.scrollY;}
	return scroll_Y;
}

function openModalIframe(frameSrc, modalWidth, modalHeight, modalTitle){
	var modalWin	= topWin.Windows.getWindow('modal_window');	
	if (modalWin){		
		resizeModal(modalWidth, modalHeight, modalTitle);
		modalWin.setURL(frameSrc);
		modalWin.setTitle(modalTitle);
		return;
	}

	var win = new Window('modal_window', {
			className:	 		"modalVoki",
			url: 						frameSrc,
			width: 					modalWidth,
			height: 				modalHeight,
			zIndex: 				1000,
			opacity: 				100,
			title:					modalTitle,
			recenterAuto:		true,
			destroyOnClose:	true,
			resizable: 			false,
			maximizable: 		false,
			minimizable: 		false
		}
	);
	
	win.showCenter();
	win.setDestroyOnClose();
	win.show(true);
	$('modal_window_content').allowTransparency = false;
}

function openScrollerIframe(frameSrc, modalWidth, modalHeight, closeCB){
	if (topWin.Windows.getWindow('vk_scroller')){
		topWin.Windows.getWindow('vk_scroller').setURL(frameSrc);
		resizeModal(modalWidth, modalHeight);
		return;
	}

	pageSize	= getPageSize();
	left = Math.floor((pageSize.windowWidth - modalWidth) / 2);
	
	var scroll = new Window('vk_scroller', {
			className:	 		"scroll",
			url: 						frameSrc,
			width: 					modalWidth,
			height: 				modalHeight,
			zIndex: 				1000,
			opacity: 				100,
			bottom:					10,
			left:						left,			
			title:					'My Voki Characters',
			recenterAuto:		false,
			destroyOnClose:	true,
			resizable: 			true,
			maximizable: 		false,
			minimizable: 		false
			}
		);
	
	if (closeCB){
		scroll.setCloseCallback(closeCB);
	}

	scroll.setDestroyOnClose();
	scroll.show(true);
}

function resizeScroller(modalWidth, modalHeight, modalTitle){
	scrollWin	= topWin.Windows.getWindow('vk_scroller');	
	if (!scrollWin){
		return false;
	}
	
	scrollWin.setSize(modalWidth, modalHeight);
	
	if (modalTitle){
		scrollWin.setTitle(modalTitle);
	}		
}

function resizeModal(modalWidth, modalHeight, modalTitle){
	modalWin	= topWin.Windows.getWindow('modal_window');	
	if (!modalWin){
		return false;
	}
	
	modalWin.setSize(modalWidth, modalHeight);
	modalWin.showCenter();
	
	if (modalTitle){
		modalWin.setTitle(modalTitle);
	}		
}

function getModalDem(){
	modalWin	= topWin.Windows.getWindow('modal_window');	
	if (!modalWin){
		return false;
	}

	return modalWin.getSize();	
}

function openModalContent(content, modalWidth, modalHeight, modalTitle){
	modalWin	= topWin.Windows.getWindow('modal_window');
	if (modalWin){
		topWin.Windows.closeAll();
	}

	var win = new Window('modal_window', {
		className:	 		"modalVoki",		
		width: 					modalWidth,
		height: 				modalHeight,
		zIndex: 				1000,
		opacity: 				100,
		title:					modalTitle,
		recenterAuto:		true,
		destroyOnClose:	true,
		resizable: 			false,
		maximizable: 		false,
		minimizable: 		false});
	
	win.getContent().innerHTML 	= content;
	win.getContent().align 		= 'center';
	
	win.showCenter();
	win.setDestroyOnClose();
	win.show(true);
}

function closeModal(){ 
	if (topWin.Windows.getWindow('modal_window') || topWin.Windows.getWindow('vk_scroller')){
		topWin.Windows.closeAll();
	}
}

function cancelFriend(){
	window.location = 'create.php';
}
//base_login.js
// *********************
//  LOGIN FUNCTIONS
// *********************
(function() { 
	document.observe("dom:loaded", function (){
		debug('DOM Loaded: base_login');
		var err = grabQueryValue('err');
		if (err != false){
			displayErr(unescape(err));	
		}
		
		if (!checkLogin()){
			for (n=0; n < arrayProtectedPages.length; n++){
				if (location.pathname.indexOf(arrayProtectedPages[n]) != -1){		
					topWin.location.href = 'login_force.php?destination=' + escape(location.pathname);
				}
			}
		}
	})	
})();


//checks if the user is logged in or not
function checkLogin(){
	var cookie 	= readCookie('vdata' + vokiEnv); 
	//no cookie set not logged in
	if (!cookie){
		return false;
	}

	//read Chip
	var	accChip	= parseInt(readChip(cookie, 'acc'));

	//chip is not in the cookie not logged in
	if (isNaN(accChip)){
		return false;
	}

	//read the env chip to make sure that both match up
	var envChk 	= readChip(cookie, 'env');
	envChk 		= envChk.toString();

	if (envChk != vokiEnv){
		return false;
	}

	return true;
}

function logoutUser(){
	location = dynamicDomain + 'login_status.php?logout=1';
	return true;
}

function submitLoginForm(){	
	dest			= grabQueryValue('destination');
	
	if (dest.toString() == 'false')
		 dest	= 'mywebsite.php';
   
	var display  = grabQueryValue('useLong');
	display    	= parseInt(display);
   
	
	email		  = $('email').value;
	pass		  = $('password').value;
	remember	= $('rememberMe').value;
  upgrade	  = $('upgrade').value;
  
  if(upgrade == 1)
    dest	  = 'classroom/paypal/startPaypal.php';

    err		  = $('loginError');

	errorStr	= '';

	//check the fields to avoid submitting to the page all the time
	formOk	= true;	
	if(email.indexOf(":") > -1) {
		//This may be student login.
		errorStr 		= "You did not enter a valid email address.\n";
	} else if (!emailPat.test(email)) {
		errorStr = "You did not enter a valid email address.\n";
		formOk = false;
	} else if (pass == "") {
		errorStr = "You did not enter your password.\n";
		formOk = false;
	}

	if (!formOk){
		if (err) {
			displayErr(errorStr);
		} else {			
			topWin.openLogin(dest, errorStr);			
		}
		return false;
	}
	
	var url = 'login_action.php';
	
	debug(url);
	var	pars = '?email=' + escape(email) + '&password=' + escape(pass) + '&rememberMe=' + escape(remember) + '&upgrade='+upgrade;
	pars 	+='&rand=' + Math.floor(Math.random() * 1000000000);	
	
	new Ajax.Request(url, {
		parameters:   	pars,
		asynchronous: 	true,
		crossDomain:	true,
		onSuccess:		processLoginResponse,
		onFailure:		processLoginFail,
		onCreate:		function () {$('Processing').show(); debug('processing PROCESSING!!');}
	});
	
	return false;
}

function displayErr(msg){
	$('Processing').hide();
	$('loginDiv').hide();
	$('loginError').show();	
	$('errMsg').innerHTML	= unescape(msg);	
}

function hideErr(){
	$('loginError').hide();
	$('loginDiv').style.display ='block';	
	$('errMsg').innerHTML	= '';	
}

function processLoginResponse(aResp){
	debug('processLoginResponse' + aResp);
	
	dest		= grabQueryValue('destination');
	
	if (dest.toString() == 'false')
		 dest	= 'mywebsite.php';
	
	
	response	= aResp.responseText.split("||");
	code		= parseInt(response[0]);
	action		= response[1];
	
	var errMsg		= '';	
	var resOk		= true;
	
	if (isNaN(code)){
		errorStr 	= 'We Apologize, But there was an internal Error. Please Try again later.';
		resOk	= false;
	}else{
		switch (code){
			//params where not submitted properly
			case 7:
				errorStr 		= 'Please check your login information and try again.';
				resOk			= false;
				break;
			//login succeeds but more steps are required (DEPECRATING)
			case 6:
				top.openModalIframe(action, 350, 400);
				return false;
				break;
			//"error" with logging in from the php script
			case 5:
				topWin.resetPass(response[2],response[1], dest);
				return false;
				break;
			case 4:
				errorStr		= response[1];
				resOk			= false;
				break;
			case 8:
				errorStr		= 'Wrong username or password';
				resOk			= false;				
				break;
			//no problems
			case 0:
				
				if (top.location.pathname == '/vokiCommentEditor.php'){					
					top.location.reload();
				}else{
					var upgarde = grabQueryValue('upgrade');
					
					if(upgrade == 1) {
						dest	  = 'classroom/paypal/startPaypal.php';
						topWin.RegisterClassroom();
					} else {
							top.location	=  cachedDomain + dest;
						}
					}
					
				return false;
				break;
			//we should never get a default.  There might be something wrong
			default:
				errorStr 	= 'We Apologize, But there was an internal Error. Please Try again later.';
				resOk		= false;
		}
	}
	
	//properly display the error message if applies
	if (!resOk){
		if (err) {
			displayErr(errorStr);
		} else {
			$('Processing').hide();
			topWin.openLogin(dest, errorStr);
			if(parseInt(code) == 8) {
				errorStr		= '<BR><font style="font-size: 12px;color: red;">This login ['+response[1]+'] is valid for Voki Classroom only. Please <a href="#" onclick="javascript:top.location=\'https://'+vokiHttps+'/classroom/\';"><b>click here</b></a> to log in to Voki Classroom and view your assignments.</font>';
				modalWin	= topWin.Windows.getWindow('modal_window').setHTMLContent(errorStr);
				resizeModal(400, 80);
			}
		}
		return false;
	}
}

//if the ajax call fails, display an error
function processLoginFail(aResp){
	debug('processLoginFail');
	$('Processing').hide();
	displayErr('We Apologize, But there was an internal Error. Please Try again later.');
}

function accessMyVoki(url){
	if (readChip(readCookie('vdata' + vokiEnv), 'acc'))
		location.href = url;
	else
		Login(url);
		//alert ('hello');
		//$('shortLoginForm').style.display = 'block';

}

function checkResetForm(){
	uPswd 			= $("new_password");
	uPswdConfirm 	= $("new_password");
	if ($("old_password")){
		uOldPass		= $("old_password");
	}
	
	
	formOk			= true;	
	if (uPswd.value.length < 6) {
		errorStr 	= "Your New password must be at least 6 characters.<br />";
		formOk		= false;
	} else {
		if (uPswdConfirm.value != uPswd.value) {
			errorStr 	= "Your New passwords did not match.<br />";
			formOk		= false;
		} 
	}
	if (!formOk){
		$('loginError').innerHTML = errorStr;
		$('loginError').style.display='block';
		return false;
	}
	return true;
}
//base_voki.js
//base_voki.js
//base_voki.js
// ********************
// PREVIEW FUNCTIONS
// ********************

function previewMyVoki(checksum, sceneID, sceneName, tblItem, editable)
{ 
// no Vokis to preview, or dummy About Me placeholder
  if (checksum == null || sceneID == null)
  {
    if (sceneID == '')
    {
      top.document.getElementById('pMyVoki_preview').innerHTML = '<img src="/images/preview_empty.gif">';
      top.document.getElementById('spanMyVoki_name').innerHTML = "<i>No Voki Created</i>";
    }
    else
    {
      top.document.getElementById('pMyVoki_preview').innerHTML = '<img src="/images/preview_empty.gif">';
      top.document.getElementById('spanMyVoki_name').innerHTML = "<i>No Voki Created</i>";
    }
    top.document.getElementById('previewVokiFullName').value = '';
    if (top.document.getElementById('btnRename'))
    top.document.getElementById('btnRename').style.display = "none";
    top.document.getElementById('tblEmbedOptions').style.display = "none";
    top.document.getElementById('previewVokiID').value = '';
    top.document.getElementById('previewTblItem').value = '';
    return;
  }

// preview the Voki! *************************************
  var embedWidth = 200;
  var embedHeight = 267;
  if (tblItem == "sentMessage" || top.location.href.indexOf('browse') != -1 || top.location.pathname == "/") 
  {
    embedWidth = 300;
    embedHeight = 400;
  }

  var isTransparent = 1;
  if (checkIt('mac') && checkIt('firefox')) {isTransparent = 0;}document.getElementById('pMyVoki_preview').innerHTML = AC_Voki_Embed(embedWidth, embedHeight, checksum, sceneID, isTransparent, 'FFFFFF', 1);
  if (document.getElementById('spanMyVoki_name')) document.getElementById('spanMyVoki_name').innerHTML = sceneName.truncate(20,'&#133;'); 
  if (document.getElementById('previewVokiFullName')) document.getElementById('previewVokiFullName').value = sceneName;
  if (document.getElementById('btnRename')) document.getElementById('btnRename').style.display = "inline";
  if (document.getElementById('tblEmbedOptions')) document.getElementById('tblEmbedOptions').style.display = "block";
  if (document.getElementById('previewVokiID')) document.getElementById('previewVokiID').value = sceneID;
  if (document.getElementById('previewVokiChecksum')) document.getElementById('previewVokiChecksum').value = checksum;
  if (document.getElementById('previewTblItem')) document.getElementById('previewTblItem').value = tblItem;

  previewedScene = parseInt(sceneID);

// if they were in the middle of renaming the last previewed Voki, cancel it
  if (top.document.getElementById('btnRename')) renameCancel();
  if (top.document.getElementById('ediBtn') && top.document.getElementById('btnRename') && top.document.getElementById('SceneSettings'))
  {
    if (editable == 0 )
    {
      top.document.getElementById('ediBtn').disabled = true;
      top.document.getElementById('btnRename').style.display = 'none';
      top.document.getElementById('SceneSettings').style.display = 'none';
    }
    else
    {
      top.document.getElementById('ediBtn').disabled = false;
      top.document.getElementById('btnRename').style.display = 'inline';
      top.document.getElementById('SceneSettings').style.display = "block";
    }
  }
}

function linkVokiModal(accountID, sceneID)
{
  var width = 300;
  var height = 300;
  sceneID = document.getElementById('previewVokiID').value;
  if(top.location.href.indexOf('browse') != -1 || top.location.pathname == "/") {width=400;height=420;}
  top.openModalIframe('linkVoki.php?sceneID=' + sceneID, width, height);
}           

// ********************
// COMMENTS FUNCTIONS
// ********************
function enableEditComments(numComments)
{
  if (!document.getElementById('btnEditComments')) return false;
  var b = document.getElementById('btnEditComments');
  if (numComments == 0)
  {
    b.disabled = true;
    b.className = "btn_100 disabled";
  }
  else
  {
    b.disabled = false;
    b.className = "btn_100";
  }
}

function populateMsgDetails(msgDetails)
{
  if (msgDetails != null)
  {
    if ($('previewSenderEmail')) $('previewSenderEmail').value = msgDetails.split('||')[0];
    if ($('tdVokiText'))
    {
      var msgText = msgDetails.split('||')[1];
      var breaksArray = ['\r\n', '\n', '\r'];
      for (i=0;i<breaksArray.length;i++)
      {
        msgText = msgText.gsub(breaksArray[i],'<br>');
      }
      $('tdVokiText').innerHTML = msgText;
    }
  }
}

// ********************
// EMBED FUNCTIONS
// ********************
function updateEmbedOptions()
{
  var f = document.forms['formEmbedOptions'];
  if (f.embedIn.options[f.embedIn.selectedIndex].text.toLowerCase() == "myspace")
  document.getElementById('btnEmbedOptions_Publish').style.display = "none";
  else document.getElementById('btnEmbedOptions_Publish').style.display = "none";
}

//////////////////////////////////////////
// function showCreateOptions2 () {} is DUPLICATE OF function showCreateOptions () FROM func_create.js
// MODIFIED on 01/10/11 by Will Lainez
function showCreateOptions2(sceneID,checksum)
{
  //document.getElementById('partnernames').value='test';
  //document.getElementById('vokiSize2').selectedIndex = 0;
  createShowDimensions();
}

//////////////////////////////////////////
// function createShowDimensions() {} HAS BEEN MIGRATED FROM func_create.js
// MODIFIED on 01/10/11 by Will Lainez
function createShowDimensions()
{
  
  createURLPickup();
  
  var size=document.getElementById('vokiSize').value;
	
  if (size == '')
  {
    var size = document.getElementsByID('myspaceCode').value;
    return;
  }
  
  var sceneID = $('vokiID').value;
  var checksum = $('vokiCS').value;
  if (size == '300')
  {
    var width = 300;
    var height = 400;
  }
  else if (size == '200')
  {
    var width = 200;
    var height = 267;
  }
  else
  {
    var width = 100;
    var height = 133;
  }
  if (location.hostname.indexOf('-vd') != -1)
  {
    var server = 'vhost-vd.oddcast.com';
    var serverVoki = 'www-vd.voki.com';
  }
  else if (location.hostname.indexOf('-vs') != -1)
  {
    var server = 'vhost-vs.oddcast.com';
    var serverVoki = 'www-vs.voki.com';
  }	
  else
  {
    var server = 'vhss-d.oddcast.com';
    var serverVoki = 'www.voki.com';
  }
  
  var pconf =
  {
    CID : '000 - Voki Widget',
    defaultBookmarkURL: 'http://'+serverVoki+'/pickup.php?scid='+sceneID+'&height='+height+'&width='+width,
    lang: 'en',
    useFacebookMystuff: 'false',
    widgetDescription: 'Come and create your very own Voki widget!',
    widgetTitle: 'I just made a new Voki. See it here:',
    facebookPreviewURL: 'http://www.voki.com/images/voki_fb2.jpg',
    defaultPreviewURL: 'http://www.voki.com/images/voki_fb2.jpg',
    defaultContent: 'gigyaEmbedText',
    UIConfig: '<config><display showEmail="false" useTransitions="true" showBookmark="true" codeBoxHeight="auto" showCloseButton="false" networksWithCodeBox=""></display><body corner-roundness="8;8;8;8"><background frame-thickness="3" gradient-color-begin="#d8e4f4" corner-roundness="6;6;6;6"></background><controls frame-thickness="1" frame-color="#8DD1FF" bold="true"><snbuttons iconsOnly="true" type="textUnder" background-color="#FFFFFF" over-background-color="#FFFFFF" color="#376DDA" corner-roundness="0;10;0;10" bold="false" over-color="#0D1B6D"></snbuttons><textboxes><codeboxes color="#6A6A6A" frame-color="#1B366D" background-color="#F4F4F4"></codeboxes></textboxes><buttons gradient-color-begin="#0099FF" gradient-color-end="#223276" color="#FFFFFF" corner-roundness="0;8;0;8" bold="true" over-gradient-color-begin="#0099FF" over-gradient-color-end="#0099FF"></buttons><servicemarker gradient-color-begin="#F4F4F4" gradient-color-end="#F4F4F4"></servicemarker></controls><texts color="#FFFFFF" bold="true"><privacy color="#AAAAAA"></privacy><labels color="#1B366D"></labels><messages color="#F4F4F4" background-color="#1B366D"></messages><links color="#376DDA" underline="false" over-color="#1B366D"></links></texts></body></config>'
  };
  //Wildfire.initPost('975072', 'divWildfirePost', 338, 250, pconf); //<<<<<<ALTERED LINE OF CODE
  
                
  var embed = '<script language="JavaScript" type="text/javascript" src="' + location.protocol + '//' + server
  + '/voki_embed_functions.php"></scr' + 'ipt>'
  + '<script language="JavaScript" type="text/javascript">AC_Voki_Embed(' + width + ',' + height + ',"' + checksum + '",' + sceneID + ', 1, "", 0);</scr'
  + 'ipt><BR><a href="http://www.voki.com/"><b>Get a Voki now!</b></a><BR><BR>';

 var myspaceEmbed = '<object height="'+height+'" width="'+width+'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' +
  'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0" id="widget_name">' +
  '<param name="movie" value="http://'+ server +'/vhss_editors/voki_player.swf?doc=http://'+server+'/php/vhss_editors/getvoki/chsm='+checksum+'%26sc='+sceneID+'" />'+
  '<param name="quality" value="high" />' +
  '<param name="allowScriptAccess" value="always" />' +
  '<param name="width" value="'+ width+'" />' +
  '<param name="height" value="'+ height + '" />' +
  '<param name="allowNetworking" value="all"/>' +
  '<param name="wmode" value="transparent" />'+
  '<param name="allowFullScreen" value="true" />' +
   '<embed height="'+height+'" width="'+width+'" src="http://'+server+'/vhss_editors/voki_player.swf?doc=http%3A%2F%2F'+server+'%2Fphp%2Fvhss_editors%2Fgetvoki%2Fchsm='+checksum+'%26sc='+sceneID+'"'+
    ' quality="high"' +
    ' allowScriptAccess="always"' +
    ' allowNetworking="all"'+
    ' wmode="transparent"'+
    ' allowFullScreen="true"'+
    ' pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" name="widget_name">'+
  '</object>';
  $('gigyaEmbedText').value = myspaceEmbed;
  
//  document.getElementById('TEXTAREA_dBlock').value = myspaceEmbed;
  try	{
    Wildfire.initPost('975072', 'divWildfirePost', 338, 250, pconf);
    //Wildfire.initPost('divWildfirePost', 338, 250, pconf);
  }
	catch(err)  {
    document.getElementById('TEXTAREA_div').style.display="block";
    document.getElementById('TEXTAREA_dBlock').style.display="block";
    document.getElementById('TEXTAREA_dBlock').value = myspaceEmbed;
	}
  
}

//////////////////////////////////////////
// function createURLPickup () HAS BEEN MIGRATED FROM func_create.js
// MODIFIED on 01/10/11 by Will Lainez
function createURLPickup ()
{
  var size=document.getElementById('vokiSize').value;
  var sceneID = $('vokiID').value;
  var checksum = $('vokiCS').value;
	
  if (size == '300')
  {
    var width = 300;
    var height = 400;
  }
	else if (size == '200')
  {
    var width = 200;
    var height = 267;
  }
  else
  {
    var width = 100;
    var height = 133;
  }

  var partnerName = document.getElementById('vokiSize2').value;
  if (partnerName == '')
  {
    return;
  }
    if (location.hostname.indexOf('-vd') != -1)
  {
    var server = 'www-vd.voki.com';
  }
  else
  {
    var server = 'www.voki.com';
  }
	
  var pickUpURLEmbed = 'http://'+server+'/pickup.php?scid='+sceneID+'&height='+height+'&width='+width;
	if (partnerName =='0')
	{
		var pickUpURLEmbed = 'Please select your newly created URL'
	}
  if (partnerName == '1')
  {
    var pickUpURLEmbed = 'http://'+server+'/pickup.php?scid='+sceneID+'&height='+height+'&width='+width;
  }
  else if (partnerName == '2')
  {
    var pickUpURLEmbed =  'http://'+server+'/pickup.php?partnerID=symbaloo&scid='+sceneID+'&height='+height+'&width='+width;
  }
  
  document.getElementById('urlHolder').innerHTML=pickUpURLEmbed;
}

	//function change()
	//					{
	//						 switch (document.getElementById("vokiSize2").value)
	//						 {
	//								case "1":
	//								document.getElementById("urlHolder").innerHTML = 'standard URL'
	//								break;
	//								case "2":
	//								document.getElementById("urlHolder").innerHTML = 'client 1'
	//								break;
	//								case "3":
	//								document.getElementById("urlHolder").innerHTML = 'client 2'
	//								break;
	//								case "4":
	//								document.getElementById("urlHolder").innerHTML = 'client 3'
	//								break;
	//						 }
	//					}					


//voki player functions
function playVoki(audio)
{
  var v = document.VoKi;
  v.vokiStop();
  v.vokiSayAudio(audio);
}

// ********************
// RENAME FUNCTIONS
// ********************
function renamePrompt()
{
  dispName = document.getElementById('previewVokiFullName').value.unescapeHTML();
  document.getElementById('newSceneName').value = dispName;
  document.getElementById('divMyVoki_name').style.display = "none";
  document.getElementById('divMyVoki_rename').style.display = "block";
}

function renameSubmit()
{
  var newName = spaceTrim(document.getElementById('newSceneName').value);
  var sceneID = document.getElementById('previewVokiID').value;
  if (newName == "")
  {
    top.Dialog.alert("Names cannot be blank or composed only of spaces.",
                     {
                      windowParameters: {width:325, height:100, className: "dialog"}, okLabel: "OK", 
                      ok:function(win) { return true }
                      }
                    );
    document.getElementById('newSceneName').value = document.getElementById('spanMyVoki_name').innerHTML;
    return;
  }
  else
  {
    var url = 'renameScene.php';
    var pars = 'sceneID=' + sceneID + '&sceneName=' + escape(newName);
    var ajaxRequest = new Ajax.Request(url,
                                       {
                                        parameters: pars,
                                        asynchronous: true,
                                        onComplete: parseRenameMessages
                                        }
                                      );
  }           
}

function parseRenameMessages(oReq)
{
  response  = oReq.responseText.split("||");
  if(response[0] == 1)
  {
// Scene found and renamed successfully
//when the user submits the new name, ' is replace with &rsquo; we need to replace with '
    newDispName = truncate(response[1], 20);
    document.getElementById('spanMyVoki_name').innerHTML = response[1].truncate(20, '&#133;');
    document.formEmbedOptions.previewVokiFullName.value = response[1];
    document.getElementById('divMyVoki_rename').style.display = "none";
    document.getElementById('divMyVoki_name').style.display = "block";
    window.frameMyVokis_content.document.getElementById('name_' + document.getElementById('previewVokiID').value).innerHTML = response[1].truncate(15, '&#133;');
    window.frameMyVokis_content.document.getElementById('fullName_' + document.getElementById('previewVokiID').value).innerHTML = response[1];
  }
}

function renameCancel()
{
  document.getElementById('divMyVoki_rename').style.display = "none";
  document.getElementById('divMyVoki_name').style.display = "block";
}

//base_mngVoki.js
// *************************
// CREATE & EDIT FUNCTIONS
// *************************

function vokiEditorCancel(){
	////debug('vokiEditorCancel');
	if ($('modal_window')) {
		topWin.closeModal();
	} else {
		if ($('create_page_div')) {
			topWin.location		= cachedDomain;
		}else{
			topWin.location.reload();
		}
	}
}

function uncacheVoki(vokiID){
	var uncacheValues = readCookie('uncached');
	
	if (uncacheValues)	{
		var uncacheArray = uncacheValues.split("||");
		
		for (n=0; n < uncacheArray.length; n++)		{
			if (uncacheArray[n] == vokiID) return;
		}
		
		uncacheArray[uncacheArray.length] = vokiID;
		
		setCookie('uncached', uncacheArray.join('||'), null, null, 'voki.com');
	}else{
		setCookie('uncached', vokiID, null, null, 'voki.com');
	}	
}

function checkUncachedVoki(vokiID){	
	if (readCookie('uncached'))	{		
		var uncacheArray = readCookie('uncached').split("||");
		
		for (n=0; n < uncacheArray.length; n++)		{
			if (uncacheArray[n] == vokiID) return true;
		}		
	}
	
	return false;
}

function vokiEditorSaveDone(vokiID, gMode, action, chsm, sceneName, accountId){
	gMode	= parseInt(gMode);
	
	//if the user is not logged in, set the unregisterdCreation cookie
	if (!checkLogin())
		setCookie('unregisteredCreation', vokiID, null, null, cookieDomain);

	// set uncached player array
	if (gMode == 3 || gMode == 4)	uncacheVoki(vokiID);
	
	//debug('gMode: ' + gMode);
	// handle submission
	switch (gMode){
		// Demo mode
		case 1:
			if (action == 'save')
				window.setTimeout('Login()', 500);
				
			if (action == 'send') 
				window.setTimeout('Login()', 500);
			return true;
			break;
		// Comment
		case 2:
			//check to see if we are in a window or not and take the approiate action 
			if(window.opener.location.href.indexOf('voki') != -1) {		
				var newWin 	= window.open('','editorComment','');
				newWin.close();
			} else {		
				window.location.href 	= cachedDomain;
				window.opener.focus();
			}
			return true;
			break;
		// Message Creation
		case 4:			
			window.setTimeout('topWin.SendToFriend(' + vokiID + ')', 500);
			return true;
			break;
		default:			
			//handeled below
	}
	
	// Registered User on Homepage (redirect to My Voki) (Will depecrate with feature releases, vokis are not created on home page any more)
	if (location.pathname == "/" && gMode == 3){
		location.href = '/mywebsite.php';
		return true;
	}

	//refersh the voki content page to make sure that we have the fresh one
	if (window.frameMyVokis_content){
		var w 			= window.frameMyVokis_content;
		w.location.href	= w.location.protocol + "//" + w.location.hostname + w.location.pathname + ("?updatedVoki=" + vokiID) + ("#voki_" + vokiID);
	}
	
	//user is on the about_me page 
	if (window.frameMyVokis_aboutContent){
		window.frameMyVokis_aboutContent.location.reload();
	}
	
	// since we just edited the previewed Voki, refresh the preview		
	if (top.document.getElementById('previewVokiID') && top.document.getElementById('previewVokiID').value == vokiID){
		previewMyVoki(topWin.$('previewVokiChecksum').value, topWin.$('previewVokiID').value, topWin.$('previewVokiFullName').value, topWin.$('previewTblItem').value);			
	}
	
	//user is on the create page 
	if ($('create_page_div')) {
		//chage the create global vars 
		createGblChsm		= chsm;
		createGblSID		= vokiID;
		createGblAID		= accountId;
		$('vokiID').value 	= createGblSID;
		
		if (!checkLogin() && !readCookie('vokiBlockedReg') && !readCookie('vokiNoThanks')){
			loginTag();
		}else{
			thankSave();
		}
		
		window.setTimeout('showCreateOptions(' + vokiID + ',"' + createGblChsm + '")', 500);
		return true;
	}

	window.setTimeout('topWin.closeModal()', 500);
	
}

// ********************
// SAVE VOKI MESSAGES 
// ********************

function saveVokiScene(sceneID){
	//debug('saveVokiScene');
	
	var save_status = 1;
	var url = 'saveScene.php';
	var pars = 'sceneID=' + sceneID + '&status=' + save_status;
	var ajaxRequest = new Ajax.Request(url, {
	    parameters:   pars, 
	    asynchronous: true,
	    onComplete:   parseSaveMessages
	});
}

function saveVokiScene_M(sceneID, same){
	//debug('saveVokiScene_M');
	
	var save_status = 1;
	var url = 'saveScene.php';
	var pars = 'sceneID=' + sceneID + '&status=' + save_status + '&same=' + same;
	var ajaxRequest = new Ajax.Request(url, {
	    parameters:   pars, 
	    asynchronous: true,
	    onComplete:   parseSaveMessages
	});
}

function processSavedScene(sceneID){
	//debug('processSavedScene');
	
	if (window.frameMyVokis_content && window.frameMyVokis_content.document.getElementById('save_' + sceneID))	{
		var a = window.frameMyVokis_content.document.getElementById('save_' + sceneID);
		a.onclick = "";
		a.setAttribute('href', '#');
		a.style.cursor = 'default';
		a.getElementsByTagName('img')[0].src = "images/buttons/myvoki_icon_save_disabled.gif";
		a.blur();
	}
}

function parseSaveMessages(oReq){
	//debug('parseSaveMessages');
	response  = oReq.responseText.split("||");
	//alert(oReq.responseText);
	if(response[0] == 1){
		// Scene found and saved successfully
		processSavedScene(response[1]);	
	}
}

// ********************
// DELETE VOKI FUNCTIONS
// ********************
function confirmDeleteVoki(vokiID, deleteID, vokiName){
	//debug('confirmDeleteVoki');
	topWin.Dialog.confirm("Are you sure you want to delete <b>" + vokiName + "</b>?", 
		{windowParameters: {width:300, height:100, className: "dialog"}, okLabel: "Delete", cancelLabel: "Cancel", 
			cancel:function(win) { return false },
			ok:function(win) { 
				//its not the perfect solution but its working
				deleteVoki(vokiID, deleteID); 			
				var w 			= window.frameMyVokis_content;
				w.location.href	= w.location.protocol + "//" + w.location.hostname + w.location.pathname;
				//w.location.href	= w.location.protocol + "//" + w.location.hostname + w.location.pathname;				
			 return true }
		});
}

function confirmDeleteVoki_A(vokiID, deleteID, vokiName) {
	//debug('confirmDeleteVoki_A');
	topWin.Dialog.confirm("Are you sure you want to delete <b>" + vokiName + "</b>?", 
		{windowParameters: {width:300, height:100, className: "dialog"}, okLabel: "Delete", cancelLabel: "Cancel", 
			cancel:function(win) { return false },
			ok:function(win) { deleteVoki_A(vokiID, deleteID); return true }
		});
}
function confirmDeleteVoki_iframe(vokiID, deleteID, vokiName) {
	//debug('confirmDeleteVoki_iframe');
	topWin.Dialog.confirm("Are you sure you want to delete <b>" + vokiName + "</b>?", 
		{windowParameters: {width:300, height:100, className: "dialog"}, okLabel: "Delete", cancelLabel: "Cancel", 
			cancel:function(win) { return false },
			ok:function(win) { deleteVoki_iframe(vokiID, deleteID); return true }
		});
}

function deleteVoki(vokiID, deleteID){
	//debug('deleteVoki');
	topWin.sceneForDeletion = parseInt(deleteID);
	
	var url = 'deleteScene.php';
	var pars = 'deleteID=' + deleteID + '&vokiID=' + vokiID;
	var ajaxRequest = new Ajax.Request(url, {
		    parameters:   pars, 
		    asynchronous: true,
		    onComplete:   parseDeleteMessages
		});
}

function deleteVoki_A(vokiID, deleteID){
	//debug('deleteVoki_A');
	topWin.sceneForDeletion = parseInt(deleteID);
	
	var url = 'deleteAboutScene.php';
	var pars = 'deleteID=' + deleteID + '&vokiID=' + vokiID;
	var ajaxRequest = new Ajax.Request(url, {
		    parameters:   pars, 
		    asynchronous: true,
		    onComplete:   parseDeleteMessages
		});
}

function deleteVoki_iframe(vokiID, deleteID){
	//debug('deleteVoki_iframe');
	topWin.sceneForDeletion = parseInt(deleteID);
	
	var url = topWin.dynamicDomain + 'deleteScene.php';
	var pars = 'deleteID=' + deleteID + '&vokiID=' + vokiID;
	var ajaxRequest = new Ajax.Request(url, {
		    parameters:   pars, 
		    asynchronous: true,
		    onComplete:   parseDeleteMessages
		});
}

function confirmDeleteVoki_M(vokiID, deleteID, vokiName, same) {
	//debug('confirmDeleteVoki_M');
	topWin.Dialog.confirm("Are you sure you want to delete <b>" + vokiName + "</b>?", 
		{windowParameters: {width:300, height:100, className: "dialog"}, okLabel: "Delete", cancelLabel: "Cancel", 
			cancel:function(win) { return false },
			ok:function(win) { deleteVoki_M(vokiID, deleteID, same); return true }
		});
}

function deleteVoki_M(vokiID, deleteID, same){
	//debug('deleteVoki_M');
	topWin.sceneForDeletion = parseInt(deleteID);
	
	var url = 'deleteScene.php';
	var pars = 'deleteID=' + deleteID + '&vokiID=' + vokiID + '&same=' + same;
	var ajaxRequest = new Ajax.Request(url, {
		    parameters:   pars, 
		    asynchronous: true,
		    onComplete:   parseDeleteMessages
		});
}


function parseDeleteMessages(req) {
	//debug('parseDeleteMessages');
	
	response  = req.responseText.split(",");
		
	if (response[0] == 1)
	{
		if (window.frameMyVokis_aboutContent)
		{
			window.frameMyVokis_aboutContent.location.reload();
			return;
		}
		
		// Scene found and deleted successfully
		if ($(response[1]))
			$(response[1]).style.display = 'none';
		else if (window.frameMyVokis_content.$(response[1]))
			window.frameMyVokis_content.$(response[1]).style.display = 'none';
		
		if (top.sceneForDeletion == top.previewedScene){
			previewMyVoki(null, null);
		}
	}
}

// *************************
// orginally in vokiJs.php
// *************************
function editVokiScene(sceneId, playerAccId, target, mode, editorAccId, useAs){	
	if(!target){
		target = "modal"; // default is modal window
	}
	
	if(useAs == undefined || useAs){
		useAs = 1;
	}else{
		useAs = 0;
	}
			
	if(mode == undefined)
		mode = 1; // default is demo mode
		
	//debug('mode is: ' + mode);
	
	if(editorAccId == undefined)
		editorAccId = defaultVokiAccId;
		
	setTimeout("editVokiSceneDo("+sceneId+",'"+playerAccId+"','"+target+"',"+mode+","+editorAccId+","+useAs+")",500);
	return false;
}

function editVokiSceneDo(sceneId, playerAccId, target, mode, editorAccId, useAs){

	partnerId = readCookie('pId');

	if(partnerId == undefined || partnerId==0)
		partnerId = defaultVokiPartnerId;

	tmpEditorAccId = readChip(readCookie('vdata' + vokiEnv),'acc');
	
	loggedIn = false;
	
	if(!isNaN(parseInt(tmpEditorAccId))) editorAccId = tmpEditorAccId;
	
	if(editorAccId == defaultVokiAccId){
		loggedIn = false;
	}else{
		loggedIn = true;
		if(mode==1)	mode = 3;
	}
	
	EditorMode		= mode;
	PartnerID		= partnerId;
	AccountId		= editorAccId;
	PlayerAccId		= playerAccId;
	PlayerSceneId	= sceneId;
	
	if(mode==2){
		var tmp 	= document.location.href.split("?");
		var obj 	= new Object();
		obj.commentSceneId	= 0;
		
		SceneId			= sceneId;
		
		if(tmp.length >= 2){
			var url = tmp[1].split('&');
			for( var i = 0 ;i < url.length ; i++ ) {
				var param = url[i].split('=');
				if( param[0] == 'sc')	obj.commentSceneId = param[1];
			}
			
			if(obj.commentSceneId>0){
				SceneId = obj.commentSceneId;
			}
		}
		
	
	}else if((mode == 5 || mode == 3) && useAs == 0){
		SceneId			= sceneId;
	}else{
		SceneId			= 0;
	}
	
	curSesId = readChip(readCookie('vdata' + vokiEnv),'sid');

	if(curSesId)	ExtraQueryStr += '&PHPSESSID=' + curSesId;
	
	if(loggedIn)	ExtraQueryStr += '&loggedIn=1';

	if (target == "modal")	params['wmode']		= null;
	
	FlashToDisplay 	= createFlashObj('edit');
	
	ExtraQueryStr 	= '';
	var editorName	= '';
	switch (mode){
		case 3:
			if (useAs)
				editorName	= 'Create a Voki';
			else
				editorName	= 'Edit Your Voki';
			break;
		case 4:
			modalWin	= topWin.Windows.getWindow('modal_window');
			editorName	= modalWin.getTitle();
			break;
		case 2:
			editorName	= 'Use a voki to comment';
			break;
	}
	if (target == "modal"){
		// open in modal window
		openModalContent(FlashToDisplay, modalSizes.get('editorWin').width, modalSizes.get('editorWin').height,editorName);
	}else{
		if ($(target))
			$(target).innerHTML = FlashToDisplay;
			
		if ($("tip") && $("bushContainer")){showTip();}
	}
}

function setSessionCookie(sesVal, cookieName){
	if(cookieName == undefined)
		cookieName = 'vdata' + vokiEnv;
		
	curSesId = readChip(readCookie(cookieName),'sid');
	if(!curSesId || curSesId==''){
		curCookieValue = readCookie(cookieName);
		sesVal = (curCookieValue?curCookieValue+'|':'')+'js=1|sid='+sesVal;
		setCookie(cookieName, sesVal,null,null,cookieDomain);
	}
}

function getSessionCookie(cookieName){
	
	if(cookieName == undefined)
		cookieName = 'PHPSESSID';
		
	var cookieValue = readCookie(cookieName);
	if(!cookieValue){
		return '';
	}else{
		return cookieValue;
	}
}

function showWizard(target, gMode){
	if(gMode == undefined)
		gMode = 1; // Demo mode of editor
		
	EditorMode		= gMode;
	
	loggedIn = false;
	
	tmpEditorAccId = readChip(readCookie('vdata' + vokiEnv),'acc');

	if(isNaN(parseInt(tmpEditorAccId)) || tmpEditorAccId==defaultVokiAccId){
		loggedIn = false;
	}else{
		loggedIn = true;
	}
	if(loggedIn)	ExtraQueryStr += '&loggedIn=1';

	if (target == "modal")	params['wmode']		= null;
		
	FlashToDisplay = createFlashObj('wiz');

	ExtraQueryStr = '';
	
	if ($(target))
		$(target).innerHTML = FlashToDisplay;
	else
		openModalContent('<span id="vokiEditorBlock">' + FlashToDisplay + '</span>', 570, 450);
}
//base_cookie.js
// *******************************************
// COOKIE READING/SETTING AND REDIRECTION
// *******************************************

function readCookie(cookieName) {

	if (document.cookie) {

		var whichChip = new RegExp("\\b" + cookieName + "=", "i");
		var index = document.cookie.search(whichChip);

		if (index != -1) {

			// Find the start 
			cookieStart = index + cookieName.length + 1;

			// Find the end 
			cookieStop = document.cookie.indexOf(";", index);
			if (cookieStop == -1) { cookieStop = document.cookie.length }

			// with the start and the end... now you've got the whole thing 
			return document.cookie.substring(cookieStart, cookieStop)
		}
		
		else return false;
		
	}
	return false;
}


function readChip(cookieValue, chipName) {

	if (!cookieValue) return false;
	
	cookieValue = unescape(cookieValue);
	var chips = cookieValue.split("|");
	
	for (c=0; c < chips.length; c++) {
	
		if (chips[c].indexOf(chipName) == 0) {
		
			var chipValue = chips[c].substring(chipName.length + 1);
			return chipValue;
		}
	}
	
	return false;
}

function setCookie (name,value,expires,path,domain,secure) 
{
   document.cookie = name + "=" + value +
   ((expires)	? ";expires=" + expires.toUTCString() : "") +
   ((path)		? ";path=" + path : "") +
   ((domain)	? ";domain=" + domain : "") +
   ((secure)	? ";secure" : "");
   //alert("setting cookie \nName:" + name + "\nValue:" + value + "\n" );
}

function deleteCookie(name, path, domain) {
	if (readCookie(name)) {
		document.cookie = name + '=' + 
		(( path ) ? ';path=' + path : '') + 
		(( domain ) ? ';domain=' + domain : '') + 
		';expires=Thu, 01-Jan-1970 00:00:01 GMT';
	}
}
//base_nav.js
// *******************************************
// PRELOAD NAV ROLLOVERS
// *******************************************

function clickButton(buttonID, action, code, target) {
	setCookie('vokiButtonClicked', buttonID, '','/','voki.com');
	if (action == 'link') {
		if(target) {
			window.open(code, target);
		} else {
			window.location = code;
		}
	} else {
		eval(code);
	}
}
 
function changePass(){
	if (!checkLogin())
		return false;
		
	var email	= readChip(readCookie('vdata' + vokiEnv), 'em');
	topWin.openModalIframe(cachedDomain + 'changePass.php', 340, 250, 'Change Your Password');
}

function Register(){
	if (readCookie('vokiBlockedReg')) {
		topWin.openBlocked();
	}
	else{
		topWin.openModalIframe(topWin.cachedDomain + 'modal_register.php', topWin.modalSizes.get('regWindow').width, topWin.modalSizes.get('regWindow').height);
		topWin.Windows.getWindow('modal_window')//.setTitle('Create your Voki Account'+'<div class="subheader">Fill out the information below to create your account.</div>')
		;
	}
}

function RegisterClassroom(){
  var cookie 	= readCookie('vdata' + vokiEnv);  
  var	accChip	= parseInt(readChip(cookie, 'acc')) || 0;

  /* IF USER IS LOGGED IN */
  if (accChip > 0){
    topWin.openModalIframe('classroom/paypal/startPaypal.php', topWin.modalSizes.get('regWindowVC').width, topWin.modalSizes.get('regWindowVC').height);
    
    // topWin.Windows.getWindow('modal_window').setTitle('<div id="headerHolder"><div class="lg_vokiClassroom"></div><div class="headerTxtHolder">Choose your <span class="orange">Voki Classroom</span> Plan'+'<div class="subheaderSmaller">Select the plan that is right for you.<br />A 2-year plan will save you <span class="orange">25% </span>per month.<br />Multiple accounts will save you an additional <span class="orange">10-15%</span>.</div></div><div class="clearboth"></div></div>');
    }

  else {
		topWin.openModalIframe(topWin.cachedDomain + 'modal_register.php?upgrade=1', topWin.modalSizes.get('regWindow').width, topWin.modalSizes.get('regWindow').height);
		topWin.Windows.getWindow('modal_window')//.setTitle('Voki Classroom Registration'+'<div class="subheader">Fill out the form below to create your Voki account.</div>')
		;
		// $('showloginOrRegister').observe('click', function (e) {
		// 	showloginOrRegister('voki');
		// });	
	}
}

function startMultipaypalFunc(){	
	topWin.openModalIframe(topWin.cachedDomain + 'classroom/paypal/startMultiPaypal.php',670,637);
}

function callbackPaypal(){
	topWin.openModalIframe('classroom/paypal/startPaypal.php', topWin.modalSizes.get('regWindowVC').width, topWin.modalSizes.get('regWindowVC').height);
    // topWin.Windows.getWindow('modal_window').setTitle('<div id="headerHolder"><div class="lg_vokiClassroom"></div><div class="headerTxtHolder">Choose your <span class="orange">Voki Classroom</span> Plan'+'<div class="subheaderSmaller">Select the plan that is right for you.<br />A 2-year plan will save you <span class="orange">25% </span>per month.<br />Multiple accounts will save you an additional <span class="orange">10-15%</span>.</div></div><div class="clearboth"></div></div>');
  }

function openPartReg(){
	topWin.openModalIframe(topWin.cachedDomain   + 'modal_register.php', topWin.modalSizes.get('partReg').width, topWin.modalSizes.get('partReg').height, 'Become A Voki Partner');
}

function loginTag(){
	if (readCookie("vokiNoThanks")){
		thankSave();
	}else{
		topWin.openModalIframe(topWin.cachedDomain  + 'modal_login_tag.php', topWin.modalSizes.get('tagWindow').width, topWin.modalSizes.get('tagWindow').height, 'You just Created a Voki Character!');		
	}
}

function openLogin(dest, err){
	//debug(err);
	if (!err)
		err	= '';
	
	if (!dest)
		dest	= 'mywebsite.php';
		
	topWin.openModalIframe('login.php?destination=' + escape(dest) + '&err=' + escape(err), topWin.modalSizes.get('loginWin').width, topWin.modalSizes.get('loginWin').height);				
}

function thankSave(){
	//if (!oTitle)
		//oTitle	= '';
	//oTitle	= '<div align="center">' + oTitle + '</div>';
	topWin.openModalIframe(topWin.cachedDomain  + 'modal_saveVoki.php',topWin.modalSizes.get('thanksWin').width, topWin.modalSizes.get('thanksWin').height);
}

function forgotPass(){
	topWin.openModalIframe(topWin.cachedDomain  + 'modal_lost_password.php', topWin.modalSizes.get('forgotPass').width, topWin.modalSizes.get('forgotPass').height);
}

function resetPass(email, tmpP, dest){
	topWin.openModalIframe(topWin.cachedDomain  + 'resetpassform.php?email=' + email + '&tmpP=' + tmpP + '&dest=' + dest, topWin.modalSizes.get('changePass').width, topWin.modalSizes.get('changePass').height, 'Reset Your Password');
}

function openModalVoki(accountID, sceneID){
	////debug('openModalVoki');
	var width	= 300;
	var height	= 300;
	
	if(topWin.location.href.indexOf('browse') != -1 || topWin.location.pathname == "/") {
			width	= 400;
			height	= 420;
	}
	
	topWin.openModalIframe(topWin.cachedDomain + 'modal_vokiPlayer.php?accountID=' + accountID + "&sceneID=" + sceneID, width, height);
}

function viewComments(vokiID, vokiName){
	////debug('viewComments');
	topWin.openModalIframe(topWin.dynamicDomain + 'getComments.php?vokiID=' + vokiID + '&vokiName=' + vokiName, 500, 400);
}

function createVoki(gMode, extra){
	if (!extra)
		extra = '';
	
	topWin.openModalIframe(topWin.cachedDomain + 'createScene.php?gMode=' + gMode + extra, topWin.modalSizes.get('createVoki').width, topWin.modalSizes.get('createVoki').height,'You have selected to create a new Voki');
}

function openGetCode(parameters){
	topWin.openModalIframe(topWin.dynamicDomain + "modal_getCode.php" + parameters,  topWin.modalSizes.get('embedCode').width, topWin.modalSizes.get('embedCode').height, 'Embed this Voki on your webpage');
}

// ALTERNATE SCRIPT
function openPublish(sceneID,checksum){
	if (location.toString().match("-vd") != null)
		
	{
	  var apiBase		= 'http://www-vd.voki.com/gigyawin.php?sceneID=';
	}
		else if(location.toString().match("-vs") != null)
	{
	  var apiBase		= 'http://www-vs.voki.com/gigyawin.php?sceneID=';
	}
		else
	{
	  var apiBase		= 'http://l-www.voki.com/gigyawin.php?sceneID=';
	}
	topWin.openModalIframe(apiBase + sceneID +"&checksum="+checksum, 400, 520, 'Publish this Voki directly to your site');

}
// END ALTERNATE SCRIPT
function openBlocked(){
	topWin.openModalIframe(topWin.cachedDomain + 'blocked.php', topWin.modalSizes.get('blocked').width, topWin.modalSizes.get('blocked').height, '&nbsp;');	
}

function openSceneSettings(sceneId){
	openModalIframe(topWin.cachedDomain + 'modal_settings_options.php?sceneID=' + sceneId, topWin.modalSizes.get('sceneSet').width, topWin.modalSizes.get('sceneSet').height,'Scene Settings');
}

function Login(url){	
	if (!url){
		url		= grabQueryValue('destination');
		if (url.toString() == 'false')
			 url	= 'mywebsite.php';
	}
	openModalIframe('login.php?destination=' + escape(url), topWin.modalSizes.get('loginWin').width, topWin.modalSizes.get('loginWin').height, 'Please login to access your account');	
}

function closeNoThanks(){
	//find out if the users created a voki then display the approiate page
	setCookie(topWin.cachedDomain + "vokiNoThanks",true,"","/",cookieDomain,"");
		
	if (readCookie('unregisteredCreation')) {	
		thankSave();
	}
}

function partnerTNC(){
	debug('partnerTNC');
	
	topWin.openModalIframe(topWin.cachedDomain  + 'modal_partnerTNC.php', topWin.modalSizes.get('partTNC').width, topWin.modalSizes.get('partTNC').height, '<div class="comNPub">For <strong>Communities</strong> and <strong>Publishers</strong> Only</div>Please Agree to the Partner Terms and Conditions');
}

function partThank(){
	debug('partThank');
	topWin.openModalIframe(topWin.cachedDomain  + 'modal_partnerThank.php', topWin.modalSizes.get('partThanks').width, topWin.modalSizes.get('partThanks').height, '<div class="comNPub">For <strong>Communities</strong> and <strong>Publishers</strong> Only</div>Thank you for signing up as a Voki Partner');
	modalWin	= topWin.Windows.getWindow('modal_window');	
	modalWin.setCloseCallback(function (){topWin.location = topWin.cachedDomain});
}

// ***************************
//  SEND-TO-FRIEND FUNCTIONS
// ***************************

function vokiReply(email){
	debug('vokiReply');
	createVoki(4, '&email=' + email);
	setCookie('reply',email);
	topWin.Windows.getWindow('modal_window').setTitle('Reply to your friend');
	//openModalIframe(topWin.cachedDomain + 'modal_emailSession.php?reply=yes&email=' + email, 380, 425, 'Reply to your friend');
}

function vokiForward(vokiID){
	debug('vokiForward');
	SendToFriend(vokiID);
	topWin.Windows.getWindow('modal_window').setTitle('Forward Your Voki');
	//openModalIframe(topWin.cachedDomain + 'modal_emailSession.php?reply=forward&sceneID=' + vokiID, 380, 425, 'Foward Your Voki');
}

function newMessage(){
	createVoki(4);	
	topWin.Windows.getWindow('modal_window').setTitle('New Voki Message');		
	//openModalIframe(topWin.cachedDomain + 'modal_emailSession.php', 400, 300, );
}

function SendToFriend(vokiID){
	debug('STAF Scene: ' + vokiID);
	openModalIframe(topWin.cachedDomain + 'sendToFriend.php?sceneID=' + vokiID, topWin.modalSizes.get('STAF').width, topWin.modalSizes.get('STAF').height, 'Send To A Friend');
}

function sendVokiToPhone(accId, scId, chsm, pid){
	sendToMobileComment = window.open( "http://" + VHOST_HTTP_SERVER + "/vhss_editors/sendVokiToPhone.php?acc="+accId+'&sc='+scId+'&chsm='+chsm+'&pid='+pid,"sendToMobileComment","width=730,height=625,toolbar=no,resizable=yes,scrollbars=yes");
	sendToMobileComment.focus();
}



//function openPublish(sceneID,checksum){	
//	topWin.openModalIframe("http://l-www.voki.com/gigyawin.php?sceneID="  + sceneID +"&checksum="+checksum, 400, 520, 'Publish this Voki directly to your site');
//}
//base_cookie.js
// *******************************************
// COOKIE READING/SETTING AND REDIRECTION
// *******************************************

function readCookie(cookieName) {

	if (document.cookie) {

		var whichChip = new RegExp("\\b" + cookieName + "=", "i");
		var index = document.cookie.search(whichChip);

		if (index != -1) {

			// Find the start 
			cookieStart = index + cookieName.length + 1;

			// Find the end 
			cookieStop = document.cookie.indexOf(";", index);
			if (cookieStop == -1) { cookieStop = document.cookie.length }

			// with the start and the end... now you've got the whole thing 
			return document.cookie.substring(cookieStart, cookieStop)
		}
		
		else return false;
		
	}
	return false;
}


function readChip(cookieValue, chipName) {

	if (!cookieValue) return false;
	
	cookieValue = unescape(cookieValue);
	var chips = cookieValue.split("|");
	
	for (c=0; c < chips.length; c++) {
	
		if (chips[c].indexOf(chipName) == 0) {
		
			var chipValue = chips[c].substring(chipName.length + 1);
			return chipValue;
		}
	}
	
	return false;
}

function setCookie (name,value,expires,path,domain,secure) 
{
   document.cookie = name + "=" + value +
   ((expires)	? ";expires=" + expires.toUTCString() : "") +
   ((path)		? ";path=" + path : "") +
   ((domain)	? ";domain=" + domain : "") +
   ((secure)	? ";secure" : "");
   //alert("setting cookie \nName:" + name + "\nValue:" + value + "\n" );
}

function deleteCookie(name, path, domain) {
	if (readCookie(name)) {
		document.cookie = name + '=' + 
		(( path ) ? ';path=' + path : '') + 
		(( domain ) ? ';domain=' + domain : '') + 
		';expires=Thu, 01-Jan-1970 00:00:01 GMT';
	}
}
//base_browser.js
// ********************************
// QUICK AND DIRTY BROWSER DETECT
// ********************************
var detect = navigator.userAgent.toLowerCase();
function checkIt(str) {
	var place = detect.indexOf(str) + 1;
	return place;
}

// ********************************
// DETECT FLASH OBJECTS
// ********************************
function isFlash(element) {
	if (element.classid) {
		if (element.classid.toLowerCase() == "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000") {return true;}
	}
	if (element.type) {
		if (element.type.toLowerCase() == "application/x-shockwave-flash") {return true;}
	}
	return false;
}

// ********************************
// SHOW OR HIDE FLASH OBJECTS IN SAFARI
// ********************************
function hideFlash() {
	var objects = document.getElementsByTagName("object");
	for (i=0;i<objects.length;i++) {
		if(isFlash(objects[i])) {
			objects[i].style.visibility = "hidden";
		}
	}
	var embeds = document.getElementsByTagName("embed");
	for (i=0;i<embeds.length;i++) {
		if(isFlash(embeds[i])) {
			embeds[i].style.visibility = "hidden";
		}
	}
}

function showFlash() {
	var objects = document.getElementsByTagName("object");
	for (i=0;i<objects.length;i++) {
		if(isFlash(objects[i])) {
			objects[i].style.visibility = "visible";
		}
	}
	var embeds = document.getElementsByTagName("embed");
	for (i=0;i<embeds.length;i++) {
		if(isFlash(embeds[i])) {
			embeds[i].style.visibility = "visible";
		}
	}
	top.Windows.getWindow('modal_window').hide();
}
//base_flash.js
// last updated 9/5/06
function displayFlash(params){
	var FlashDisplay = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"' + 
					(params['codebase'] ? ' codebase="' + params['codebase'] + '"' : '') + 
					(params['width'] ? ' width="' + params['width'] + '"' : '') + 
					(params['height'] ? ' height="' + params['height'] + '"' : '') + 
					(params['id'] ? ' id="' + params['id'] + '"' : '') + 
					'>';
	
	FlashDisplay += '<param name="movie" value="' + params['swf'] + '">';
	
	if (params['FlashVars']) FlashDisplay += '<param name="FlashVars" value="' + params['FlashVars'] + '">';
	if (params['allowScriptAccess']) FlashDisplay += '<param name="allowScriptAccess" value="' + params['allowScriptAccess'] + '">';
	if (params['base']) FlashDisplay += '<param name="base" value="' + params['base'] + '">';
	if (params['scale']) FlashDisplay += '<param name="scale" value="' + params['scale'] + '">';
	if (params['bgcolor']) FlashDisplay += '<param name="bgcolor" value="' + params['bgcolor'] + '">';
	if (params['quality']) FlashDisplay += '<param name="quality" value="' + params['quality'] + '">';
	if (params['wmode']) FlashDisplay += '<param name="wmode" value="' + params['wmode'] + '">';
	if (params['align']) FlashDisplay += '<param name="align" value="' + params['align'] + '">';
	if (params['salign']) FlashDisplay += '<param name="salign" value="' + params['salign'] + '">';
	FlashDisplay += '<param name="rand" value="' + Math.floor(Math.random() * 1000000000) + '">';
	FlashDisplay += '<embed src="' + params['swf'] + '" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" swliveconnect="true"' + 
		(params['allowScriptAccess'] ? ' allowScriptAccess="' +	params['allowScriptAccess'] +	'"' : '') + 
		(params['bgcolor'] ? ' bgcolor="' +	params['bgcolor'] +		'"' : '') + 
		(params['width'] ? ' width="' + params['width'] +		'"' : '') + 
		(params['height']	? ' height="' + params['height'] +		'"' : '') + 
		(params['id'] ? ' name="' + params['id'] +			'"' : '') + 
		(params['base'] ? ' base="' + params['base'] +		'"' : '') + 
		(params['scale'] ? ' scale="' + params['scale'] +		'"' : '') + 
		(params['FlashVars'] ? ' FlashVars="' +	params['FlashVars'] +	'"' : '') + 
		(params['wmode'] ? ' wmode="' + params['wmode'] + 		'"' : '') + 
		(params['quality'] ? ' quality="' +	params['quality'] + 	'"' : '') + 
		(params['align'] ? ' align="' + params['align'] + 		'"' : '') + 
		(params['salign'] ? ' salign="' + params['salign'] + 		'"' : '') + 
		'rand=' + Math.floor(Math.random() * 1000000000)+'>';
	
	FlashDisplay += '</object>';
	
	document.write(FlashDisplay);
}
//func_home.js
//begin dont change 
var topImgs = new Array();
var topLinks = new Array();
var holidayImgs = new Array();
var holidayLinks = new Array();
var playImgs = new Array();
var playLinks = new Array();

var randomHolder = new Array();
//end dont change 

//top pos list
topImgs[0] = 'images/promo/msft_idol_promo.gif';
topLinks[0] = 'http://www.theultimatesteal.com/sweepstakes/idol/';

topImgs[1] = 'images/promo/msft_allnighter_promo.gif';
topLinks[1] = 'http://www.theultimatesteal.com/sweepstakes/allnighter/';

//2nd pos list
holidayImgs[0] = 'images/promo/jaduka_homebanner.jpg'
holidayLinks[0] = 'http://www.duhbate08.com'

//3 and 4 pos list
playImgs[0] = 'images/promo/bush_impression.gif'
playLinks[0] = 'http://apps.voki.com/internal_playgrounds/bush'

playImgs[1] = 'images/promo/gossip_girl_promo.gif'
playLinks[1] = 'http://apps.voki.com/gossipgirl/gossipgirl'

playImgs[2] = 'images/promo/ak1.gif'
playLinks[2] = 'http://apps.voki.com/alicia_keys/as_i_am'

playImgs[3] = 'images/promo/ak2.gif'
playLinks[3] = 'http://apps.voki.com/alicia_keys/no_one'


// do not edit
function generateRandom() {
	var playgroundDiv = $('playgroundDiv');
	var numTop = 1;
	var numHoliday = 1;
	var numPlay = 2;
	var randomCount = 0;
	
	while (randomCount < numTop) {
		var rand = Math.floor(Math.random() * topImgs.length);
		if (!randomHolder[rand]) {
			var topAd = document.createElement('div');
			topAd.className = 'playgroundLink';
			topAd.innerHTML = '<a href="' + topLinks[rand] + '" target="_blank"><img src="' + topImgs[rand] + '" /></a>';
			playgroundDiv.appendChild(topAd);
			randomCount++;
			randomHolder[rand] = 1;
		}
	}

	randomCount = 0;
	randomHolder.length = 0;

	while (randomCount < numHoliday) {
		var rand = Math.floor(Math.random() * holidayImgs.length);
		if (!randomHolder[rand]) {
			var holidayAd = document.createElement('div');
			holidayAd.className = 'playgroundLink';
			holidayAd.innerHTML = '<a href="' + holidayLinks[rand] + '" target="_blank"><img src="' + holidayImgs[rand] + '" /></a>';
			playgroundDiv.appendChild(holidayAd);
			randomCount++;
			randomHolder[rand] = 1;
		}
	}

	randomCount = 0;
	randomHolder.length = 0;

	while (randomCount < numPlay) {
		var rand = Math.floor(Math.random() * playImgs.length);
		if (!randomHolder[rand]) {
			var playAd = document.createElement('div');
			playAd.className = 'playgroundLink';
			playAd.innerHTML = '<a href="' + playLinks[rand] + '" target="_blank"><img src="' + playImgs[rand] + '" /></a>';
			playgroundDiv.appendChild(playAd);
			randomCount++;
			randomHolder[rand] = 1;
		}
	}
}

var embedCode = '<scr' + 'ipt language="JavaScript" type="text/javascript" src="http://vhss-d.oddcast.com/voki_embed_functions.php"></scr' + 'ipt>'
			  + '<scr' + 'ipt language="JavaScript" type="text/javascript">AC_Voki_Embed(300,400,"46bf404dde12aa69b1f069e797534ada", 162141, 1, "", 0);</scr' + 'ipt>'
			  + '<BR><a href="http://www.voki.com/"><b>Get a Voki now!</b></a><BR><BR>';

var myspaceEmbed = '<PARAM NAME="movie" VALUE="http://vhss-a.oddcast.com/vhss_editors/voki_player.swf?doc=http%3A%2F%2Fvhss-d.oddcast.com%2Fphp%2Fvhss_editors%2Fgetvoki%2Fchsm%3D46bf404dde12aa69b1f069e797534ada%26sc%3D162141"><PARAM NAME="BASE" VALUE="http://vhss-a.oddcast.com/vhss_editors/"><PARAM NAME=quality VALUE=high><PARAM NAME=scale VALUE=noborder><PARAM NAME=bgcolor VALUE="transparent"><PARAM NAME="wmode" VALUE="transparent"><EMBED allowScriptAccess="never" allownetworking="internal" src="http://vhss-a.oddcast.com/vhss_editors/voki_player.swf?doc=http%3A%2F%2Fvhss-d.oddcast.com%2Fphp%2Fvhss_editors%2Fgetvoki%2Fchsm%3D46bf404dde12aa69b1f069e797534ada%26sc%3D162141" swLiveConnect=true NAME="voki" quality=high base="http://vhss-a.oddcast.com/vhss_editors/" scale=noborder wmode="transparent" WIDTH=300 HEIGHT=400 TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash%5c"></EMBED><BR><a href="http://www.voki.com/vokiCommentEditor.php?sc=162141" target=_blank>Click here to comment on this Voki.</a><BR><a href="http://www.voki.com/"><b>Get a Voki now!</b></a><BR><BR>';

//func_create.js
function showCreateOptions(sceneID,checksum) {
	
	writeFlashHeadPublish();
	$('divBody_ColumnLeft').style.display = 'none';
	$('divBody_ColumnRight').style.display = 'none';
	$('vokiHolder').innerHTML = AC_Voki_Embed(200,267, checksum , sceneID, 1, '', 1);
	$('vokiHolder').style.display = 'block';
	$('createOptions').style.display = 'block';
	$('vokiID').value = sceneID;
	$('vokiCS').value = checksum;
	$('sendSceneId').value = sceneID;
	
	createShowDimensions();
}

//function embedGigyaToModal (sceneID) {
//  $('vokiID').value = sceneID;
//  $('deliverSceneID').value = sceneID;
//}

var createDivsArray = ['addToSiteTab','sendToFriend','sendToFriendThanks','sendToMobile','moreVokiFun'];

function showCreateOption(id) {
	//unInitialize()	
	for (i=0;i<createDivsArray.length;i++) {
		$(createDivsArray[i]).style.display = 'none';
	}
	$(id).style.display = 'block';
	/*if (id == 'sendToFriend'){
		initialize();
	}*/
}

function createSend(){
	
	var formOk = validateSendToFriend;
	if (!formOk){
		return false;
	}
	
	url		= location.protocol + '//' + location.host + '/sendMessage.php';
	pars	= $('formSend').serialize();
				
	var ajaxRequest = new Ajax.Request(url, {
	    parameters:   pars, 
	    asynchronous: true,
	    onComplete:   displaySendOk
	});
	
	return false;
}

function displaySendOk(){
	
	showCreateOption('sendToFriendThanks');
	$('fromName').value = '';
	$('fromEmail').value = '';
	$('toEmail').value = '';
	$('message').value = '';
}

//////////////////////////////////////////
// function createShowDimensions() HAS BEEN MIGRATED TO base_Voki.js
// MODIFIED on 01/10/11 by Will Lainez

//////////////////////////////////////////
// function createURLPickup () HAS BEEN MIGRATED TO base_Voki.js
// MODIFIED on 01/10/11 by Will Lainez


function writeFlashHead() {
	//return;
	document.write('<object id="create_header" width="860" height="92" codebase="/getFlash.php?u=codebase" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000">'
	+ '<param value="/swf/create_header.swf" name="movie"/>'
	+ '<param value="always" name="allowScriptAccess"/>'
	+ '<param value="transparent" name="wmode"/>'
	+ '<embed width="860" height="92" wmode="transparent" name="create_header" allowscriptaccess="always" swliveconnect="true" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" src="/swf/create_header.swf"/>'
	+ '</object>');
 }
 
function writeFlashHeadPublish() {
	//return;
	$('create_header').innerHTML = '<object id="create_header" width="860" height="92" codebase="/getFlash.php?u=codebase" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000">'
	+ '<param value="/swf/create_header2.swf" name="movie"/>'
	+ '<param value="always" name="allowScriptAccess"/>'
	+ '<param value="transparent" name="wmode"/>'
	+ '<embed width="860" height="92" wmode="transparent" name="create_header" allowscriptaccess="always" swliveconnect="true" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" src="/swf/create_header2.swf"/>'
	+ '</object>'
}


//func_email.js
(function() { 
	document.observe("dom:loaded", function (){
		//debug('DOM Loaded: func_email');
		charCount();
		initialize();
	})
	
})();

var sentAlready		= false;
var msgLimit 		= 250;
var conEmls 		= $H({});
var emailList		= $H({});
var nameList		= $H({});
var allowedEmls		= 5;
var logosVisible 	= false;
var mailArray 		= ['Yahoo','Hotmail','Gmail','AOl'];
var logoEventsSet 	= false;
var popConTpl		= new Template('<tr class="emailRow" id="contactEmail_#{row}">' +
						'<td class="addCheck"><input type="checkbox" id="Con_check|#{email}|#{name}"></td>' +
						//'<td class="addressRow" id="Con_add|#{email}|#{name}">#{eml}</td>' + 
						'<td class="nameRow" id="Con_name|#{email}|#{name}">#{nam}</td></tr>');
						
var recipTpl		= new Template('<tr class="row#{classRow}">' + 
					'<td><input type="hidden" name="emailList[]" value="#{email}">#{eml}</td>' +
					//'<td><input type="hidden" name="nameList[]" value="#{name}">#{nam}</td>' +
					'<td id="dl_#{email}">remove</td></tr>');	
					
var loginClick		= false;
										
function updateEmailCount(){ 
	if ((allowedEmls < 1)){
		return true;
	}

	var totEmls	= emailList.values();
	totEmls		= totEmls.length;
	
	$('emailTally').innerHTML = (allowedEmls - totEmls) + '&nbsp;';

}

function initialize()
{	
	if (checkLogin())
	{
		var vdata	= readCookie('vdata' + vokiEnv);
		var name	= readChip(vdata, 'fn') + ' ' + readChip(vdata,'ln');
		var email	= readChip(vdata, 'em');
		
		$('yourEmail').value = email;
		$('yourName').value	= name;
	}
	
	var rEmail	= readCookie('reply');
	//debug('here chuck ' + rEmail);
	if (rEmail){
		//debug(rEmail);	
		addEmailAddy(rEmail, '', true);
		deleteCookie('reply');
	}
	
	updateEmailCount();
	
	$('manEmail').observe('keyup', function(e) {
			var el = Event.element(e);
			if (Event.KEY_RETURN == (e.keyCode || e.which))
			{
				addEmailAddy($('manEmail').value, '', true);
			}
		}
	)

	$('manEmail').observe('blur', function(e) {
		addEmailAddy($('manEmail').value, '', true);
		}
	)

	$('subBut').observe('click', function (){
			validateSendToFriend();
		});
	
	$('subButAgain').observe('click', function (){
		SendToFriendAgain();
	});
	
	$('message').observe('change', charCount);
	$('message').observe('keypress', charCount);	
	//$('selectMail').observe('click', showLogos);
	$('sendSceneId').value	= grabQueryValue('sceneID');
	
}

function unInitialize(){	
	$('manEmail').stopObserving ('keyup', function(e) {
			var el = Event.element(e);
			if (Event.KEY_RETURN == (e.keyCode || e.which)) {
				addEmailAddy($('manEmail').value, '', true);
			}
		}
	)

	$('manEmail').stopObserving ('blur', function(e) {
		addEmailAddy($('manEmail').value, '', true);
		}
	)

	$('subBut').stopObserving ('click', validateSendToFriend);
	$('subButAgain').stopObserving ('click', SendToFriendAgain);
	$('message').stopObserving ('change', charCount);
	$('message').stopObserving ('keypress', charCount);
	$('selectMail').stopObserving ('click', showLogos);
}

//count the number of charaters in the message field 
function charCount(){
	var txt				= $('message').value;	
	var currentCount 	= txt.length;
	
	if (currentCount > msgLimit)
		txt		= txt.substring(0,msgLimit);
	
	$('charTally').innerHTML = msgLimit - txt.length;
}

function showLogos() {
	//debug('ShowLogos');
	if (logosVisible) {
		$('menuDisplay').style.display	= 'block';
		$('email_logos').style.display	= 'none';
		logosVisible = false;
	} else {
		
		$('menuDisplay').style.display	= 'none';
		$('email_logos').style.display	= 'block';
		logosVisible = true;
		
		if(!logoEventsSet) {
			watchLogos();
			logoEventsSet = true;
		}
	}
}

function watchLogos(){	
	$$('[id^="LogoImg"]').each(function (e){
		var id 	= e.id;	
			
		$(id).observe('mouseover', function (event){
			var eid			= Event.element(event).id;			
			var logoName	= id.substr(id.indexOf('_') + 1);		
			$(eid).src	= '/images/email/mail_logo_' + logoName + '_over.gif';
		});	
			
		$(id).observe('mouseout', function (event){
			var eid			= Event.element(event).id;			
			var logoName	= id.substr(id.indexOf('_') + 1);		
			$(eid).src	= '/images/email/mail_logo_' + logoName + '.gif';
		});	
		
		$(id).observe('click', function (event){
			var eid			= Event.element(event).id;			
			var logoName	= id.substr(id.indexOf('_') + 1);	
			loginClick		= false;	
			selectPopApi(logoName);
		});	
	});	
}


//select which api to use will display the login form 
function selectPopApi(mailType){
	//debug('selectPopApi');
	
	logosVisible = false;
	showLogos();
	
	$('menuDisplay').style.innerHTML	= '<img src="/images/email/mail_logo_' + mailType + '.gif" />';

	$('importFrom').value 	= mailType;
	var apiSel 	= $('importFrom').value;

	if (apiSel == ''){
		$('popLogin').style.display		= 'none';
		$('popContacts').style.display	= 'none';
		$('popSpace').style.display		= 'none';	
		return true;
	}
	
	$('messageSpace').style.display	= 'none';
	$('sendCancel').style.display	= 'none';
	$('popContacts').style.display 	= 'none';
	
	$('cancelDone').style.display	= 'block';
	$('popSpace').style.display		= 'block';
	$('popSpace').style.background	= '#E1E9F5';
	$('popLogin').style.display		= 'block';
	$('popLabel').style.display 	= 'block';
	
	$('popLabel').innerHTML			= 'Please enter your Email and password for '+ mailType;
	
	$('popLoginbut').observe('click', loginToPop);
	$('buttonDone').observe('click', showMessage);
	$('popPass').observe('keypress',function (e){
		if (Event.KEY_RETURN == (e.keyCode || e.which)) {
			loginToPop();
		}
	});
}

function loginToPop(){
	if (loginClick){
		//debug('loginClick true');
		return true;
	}
	loginClick	= false;
	//check for the values 1st 
	var user	= $('popUser').value;
	var pass	= $('popPass').value;
	
	if (user == '' || pass == ''){
		usingPop					= false;
		$('popAlert').innerHTML 	= 'Please enter your email address and password and try again';
		return false;
	}
	
	$('popAlert').innerHTML 	= 'Please Wait while we try to log you in.';
	
	//now login the user and get back the stuff 
	var url 	= location.protocol + '//' + location.host + '/pop_action.php';
	var pars 	= $('formSend').serialize();	
	
	new Ajax.Request(url, {
		parameters:   	pars,
		asynchronous: 	true,
		onSuccess:		grabContacts
	});
}

//parse the response back and fill in the information 
function grabContacts(aResp){	
	$('popAlert').innerHTML 	= '';
	
	response	= aResp.responseText.split("||");
	
	code		= parseInt(response[0]);
	data		= response[1];
	
	switch(code){
		case 105: case 106:
			$('popAlert').innerHTML 	= 'Unable to log you in.  Please check your email and try again';
			break;
		case 1000:
			$('popAlert').innerHTML 	= 'We\'er sorry but we are unable to contact ' +  $('importFrom').value + '.  Please try again later';
			break;
		case 2000:
			$('popAlert').innerHTML 	= 'Please check that your user name and password are correct.';
			break;
		case 3000:
			$('popAlert').innerHTML 	= 'We were able to contact ' +  $('importFrom').value + ', however they were unable to provide us your contacts.  Please try again later';
			break;
		case 0:
			//nothing wrong
			break;
		case 1: case 2: case 3: case 4: case 5: case 6:
		case 101: case 102: case 103:
		case 9000:
		default:
			if (isNaN(code)){
				code	= -1;
				data	= 'Unkonwn Response from ' + $('importFrom').value;
			}
			$('popAlert').innerHTML 	= 'We\'er sorry but an error occured: <br>' + code + ':' + data;
			return;
			break;
	}
	
	$('popLogin').style.display		= 'none';
	
	contacts	= data.evalJSON(true);
	displayContacts();
}

//list the contacts so that the user can choose which emails to add 
function displayContacts(){
	//debug('func_email_displayContacts');
	$('popContacts').style.display 		= 'block';
	$('popSpace').style.background		= '#FFFFFF';
	$('popLogin').style.display 		= 'none';
	
	
	$('popLabel').style.display 		= 'block';
	$('popLabel').innerHTML 			= '<b>Your Contacts:</b> (Click name to add)';
	
	$('popContacts').innerHTML	 		= '';
	var row 		= 0;
	var observList	= $H({});
	conStr		= '<table border="0" cellpadding="0" cellspacing="0">'+
							'<tr class="header">' + 
							'<td class="headerShort">Add:</td>' + 
							'<td class="headerLong">Email:</td>' + 
							'<td class="headerLong">Name</td></tr>';
	contacts.each(function(contact){
		conStr		+= popConTpl.evaluate({email: contact.email, name: contact.name, nam: contact.name.truncate(20,'&#133;'), eml: contact.email.truncate(20,'&#133;')});
	});
	
	conStr						 		+= '</table>';
	$('popContacts').innerHTML	 		= conStr;
	
	$$('[id^="Con_"]').each(function (e){
		var id 	= e.id;	

		$(id).observe('click', function (event){
			var id 		= event.element().id;
			var parts	= id.split('|');
			
			checkEmailCheck(parts[1],parts[2], parts[0]);
		});	
	});	

}

function checkEmailCheck(tmpEml,tmpNam, id) {
	//debug('func_email_checkEmailCheck');
	var elemId	= 'Con_check|' + tmpEml + '|' + tmpNam;
	
	if ($(elemId).checked) {
		debug('check');
		if (id != 'Con_check'){
			$(elemId).checked = false;
		}
		addEmailAddy(tmpEml,tmpNam,false);
		
	} else {
		if (id != 'Con_check'){
			$(elemId).checked = true;
		}
		removeEmailAddy(tmpEml);
	}
}

function addEmailAddy(tmpEml, tmpNam, resetManForm){
	//debug('func_email_addEmailAddy');
	//debug('addEmailAddy') ;
	var totEmls	= emailList.values();
	totEmls		= totEmls.length;
	
	if ((allowedEmls > 0) && ((totEmls + 1) > allowedEmls)){
		$('divAlert').innerHTML = 'You are only allowed to send to a maximum of ' + allowedEmls + ' people.';
		return false;
	}
	
	//debug('adding: ' + tmpEml) ;
	//clear out the alert box 
	$('divAlert').innerHTML = '';
	
	//remove the white space and dont add if its blank 
	tmpEml	= tmpEml.strip();
	
	if (tmpEml == '')
		return true;
	
	if (validateEmail(tmpEml)){
		emailList.set(tmpEml, tmpEml);
		nameList.set(tmpEml, tmpNam);
	}else{
		$('divAlert').innerHTML = 'Invalid Email Address ';	
		return false;		
	}
	//debug(emailList);
	//update the list 
	updateEmailList();
	updateEmailCount();
	
	//if we want to reset form field blank it out
	if (resetManForm){
		$('manEmail').value	= '';
		$('manEmail').focus();
	}
	
	
}

function removeEmailAddy(email){ 
	//debug('func_email_removeEmailAddy');
	var checkBox	= 'Con_check|' + emailList.get(email) + '|' + nameList.get(email);
	
	if ($(checkBox)){
		$(checkBox).checked = false;	
	}
	
	emailList.unset(email);
	nameList.unset(email);
	updateEmailList();
	updateEmailCount();
}

//pop's the divs list to allow the user to go and see who they are sending too
function updateEmailList(){
	//debug('func_email_updateEmailList');
	//remove the default
	//$('emailList').innerHTML	= '';

	var row			= 0;
	var observList	= $H({});
	recipStr		= '<table border="0" cellpadding="0" cellspacing="0" width="100%">'+
							'<tr class="header">' + 
							'<td style="width:250px;">Email:</td>' + 
							//'<td class="headerLong">Name:</td>' + 
							'<td class="headerShort">Edit</td></tr>';
	emailList.each(function(pair) {  		
		classRow	= (row % 2) + 1 ;

		email 		= pair.value;
		name		= nameList.get(email);
	
		recipStr		+= recipTpl.evaluate({classRow: classRow, email: email, name: name, nam: name.truncate(47,'&#133;'), eml: email.truncate(47,'&#133;')});
		
		row++;
	});
	//
	$('emailList').innerHTML	= recipStr + "</table>";
	
	$$('[id^="dl_"]').each(function (e){
		var id 	= e.id;	
		//debug(id + ' watching remove');
		$(id).observe('click', function(e){
			//debug('remove click');
			var id 			= e.element().id;
			var email		= id.substr((id.indexOf('_') + 1));
			
			//debug('removing: ' + email);
			
			//debug(emailList.get(email));
			removeEmailAddy(email);
		});
	});	
	
	if (row == 0) $('emailList').innerHTML	= 'Enter/Select emails above...';
	$('manEmail').value='';
}

function showMessage() {
	//debug('func_email_showMessage');
	$('popSpace').style.display = 'none';
	$('messageSpace').style.display = 'block';
	$('sendCancel').style.display = 'block';
	$('cancelDone').style.display = 'none';
	$('menuDisplay').style.display = 'block';
}

//validate the whole form and post 
function validateSendToFriend(validateOnly){
	debug('func_email_in validateSendToFriend');
	
	if(sentAlready){
		debug('func_email_in validateSendToFriend exit');
		return;
	}
			
	$('divAlert').innerHTML 	= "&nbsp;";
	
	var message		= $('message').value;
		
	if($('yourName')) {
		var fromName	= $('yourName').value;
		fromName		= fromName.strip();
		if (fromName 	== '') {
			$('divAlert').innerHTML 	= "You must enter your name.";
			
			return false;
		}
	}
	
	if($('yourEmail')) {
		var fromEmail	= $('yourEmail').value;
		fromEmail		= fromEmail.strip();
		if (fromEmail 	== '') {
			$('divAlert').innerHTML 	= "You must enter your email address.";
			return false;
		}else{
			if (!validateEmail(fromEmail)){
				$('divAlert').innerHTML 	= "Please enter your email address correctly.";
				return false;
			}
		}
	}
	
	var totEmls	= emailList.values();
	totEmls		= totEmls.length;
	
	if (totEmls < 1){
		$('divAlert').innerHTML 	= "You need at least 1 email to send to.";
		return false;
	}
	
	if($('subject')) {
		var subject	= $('subject').value;
		subject		= subject.strip();
		if (subject 	== '') {
			$('divAlert').innerHTML 	= "You must enter a Voki Subject.";
			return false;
		}
	}
		
	if (validateOnly){
		//debug('validating only')
		return true;
	}
	
	url		= location.protocol + '//' + location.host + '/sendMessage.php';
	pars	= $('formSend').serialize();
	
	$('divAlert').innerHTML = 'Sending...';	
	new Ajax.Request(url, {
		parameters:   	pars,
		asynchronous: 	true,
		onSuccess:		checkMessageSent,
		onFailure:		badMessageSent
	});
	
}

function checkMessageSent(aResp) {
	if(!sentAlready) sentAlready = true;
	//debug('func_email_checkMessageSent');
	$('formSend').style.display 	= 'none';
	$('msgSent').style.display  	= 'block';
}

function SendToFriendAgain() {
	if(sentAlready) sentAlready = false;
	//debug('func_email_checkMessageSent');
	$('formSend').style.display 	= 'block';
	$('msgSent').style.display  	= 'none';
	$('divAlert').innerHTML = '';
}

function badMessageSent(){
	//debug('func_email_badMessageSent');
	$('divAlert').innerHTML = 'We\'re sorry, an error has occured.  Please try again later';	
}

//function charCount(){
//	//debug('func_email_charCount');
//	var txt = document.formSend.message;
//	
//	var currentCount = (txt.value.length+1);
//	
//	if (currentCount > msgLimit)
//		txt.value = txt.value.substring(0,msgLimit);
//	else
//		$('charTally').innerHTML = (msgLimit-1) - currentCount;
//}


function textCounter(field) {
	if (field.value.length > msgLimit) // if too long...trim it!
		field.value = field.value.substring(0, msgLimit);
	// otherwise, update 'characters left' counter
	else
		$('charTally').innerHTML = msgLimit - field.value.length;
}
var defaultVokiAccId 		= 37533;
var defaultVokiPartnerId 	= 16;
var AccountId		= 37533;
var PlayerAccId		= '';
var SceneId 		= 0;
var PlayerSceneId	= 0;
var EditorMode		= 1;
var PartnerID		= 16;
var PartnerConfigID	= 6;
var PartnerAppID	= 0;
var ExtraQueryStr	= '';
var VHOST_HTTP_SERVER	= 'vhss.oddcast.com';

var params  		= new Array(0);
params['swf']		= '//vhss-d.oddcast.com/vhss_editors/voki_editor.swf?acc=37533&sc=0&doc=http%3A%2F%2Fvhss.oddcast.com%2Fvoki%2FgetvokiLive.xml&gMode=1&partnerId=16&cid=6';
params['id']		= "voki_edt";
params['width']		= 552;
params['height']	= 436;
params['wmode']		= "transparent";
params['codebase']	= '/getFlash.php?u=codebase';
params['base']		= '//vhss-d.oddcast.com/vhss_editors/';
params['allowScriptAccess']	= 'always';

function cUrl(){		
	if(PlayerAccId == 0 || PlayerSceneId == 0){		
		
		newDocURL = escape('http://vhss-d.oddcast.com/php/vhss_editors/getrandomvoki/partnerId='+PartnerID+'&configId='+PartnerConfigID+(PartnerAppID>0?'&vokiapps=1':'')+(EditorMode==2?'&cmnt=1':'')+'&rnd='+(Math.max(1,parseInt(Math.random()*100)%30)));
	}else{
		newDocURL = escape('http://vhss.oddcast.com/php/vhss_editors/getvoki/chsm='+PlayerAccId+'&sc='+PlayerSceneId+'&editor=1?r='+parseInt(Math.random()*10000000));	
	}
	
	return newDocURL;
};

function createEditURL(mode){
	if(mode=='edit'){		
		params['swf'] = '//vhss-d.oddcast.com/vhss_editors/voki_editor.swf';
		params['swf'] += '?acc='+AccountId;
		params['swf'] += '&sc='+SceneId;
		params['swf'] += '&doc='+cUrl();
		params['swf'] += '&gMode='+EditorMode;
		params['swf'] += '&partnerId='+PartnerID;
		params['swf'] += '&cid='+PartnerConfigID;
		params['swf'] += ExtraQueryStr;
		return true;
	}
	
	
	params['swf'] 	= params['base']+'voki_homeModule.swf?gMode='+EditorMode+'&loadUrl=media%2Fdemomovie.swf';
	params['swf'] 	+= ExtraQueryStr;
	params['id']	= "voki_edt";
}

function createFlashObj(mode){
	createEditURL(mode);
	
	var FlashDisplay = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"' + 
						(params['codebase'] ? ' codebase="' + params['codebase'] + '"' : '') + 
						(params['width'] ? ' width="' + params['width'] + '"' : '') + 
						(params['height'] ? ' height="' + params['height'] + '"' : '') + 
						(params['id'] ? ' id="' + params['id'] + '"' : '') + 
						'>';
	
	FlashDisplay += '<param name="movie" value="' + params['swf'] + '">';
	
	if (params['FlashVars'])			FlashDisplay += '<param name="FlashVars" value="' + params['FlashVars'] + '">';
	if (params['allowScriptAccess'])	FlashDisplay += '<param name="allowScriptAccess" value="' + params['allowScriptAccess'] + '">';
	if (params['base'])					FlashDisplay += '<param name="base" value="' + params['base'] + '">';
	if (params['scale'])				FlashDisplay += '<param name="scale" value="' + params['scale'] + '">';
	if (params['bgcolor'])				FlashDisplay += '<param name="bgcolor" value="' + params['bgcolor'] + '">';
	if (params['quality'])				FlashDisplay += '<param name="quality" value="' + params['quality'] + '">';
	if (params['wmode'])				FlashDisplay += '<param name="wmode" value="' + params['wmode'] + '">';
	if (params['align'])				FlashDisplay += '<param name="align" value="' + params['align'] + '">';
	if (params['salign'])				FlashDisplay += '<param name="salign" value="' + params['salign'] + '">';
	
	FlashDisplay += '<embed src="' + params['swf'] + '" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" swliveconnect="true"' + 
		(params['allowScriptAccess']	? ' allowScriptAccess="' +	params['allowScriptAccess'] +	'"' : '') + 
		(params['bgcolor']				? ' bgcolor="' +	params['bgcolor'] +		'"' : '') + 
		(params['width']				? ' width="' +		params['width'] +		'"' : '') + 
		(params['height']				? ' height="' +		params['height'] +		'"' : '') + 
		(params['id']					? ' name="' +		params['id'] +			'"' : '') + 
		(params['base']					? ' base="' +		params['base'] +		'"' : '') + 
		(params['scale']				? ' scale="' +		params['scale'] +		'"' : '') + 
		(params['FlashVars']			? ' FlashVars="' +	params['FlashVars'] +	'"' : '') + 
		(params['wmode']				? ' wmode="' +		params['wmode'] + 		'"' : '') + 
		(params['quality']				? ' quality="' +	params['quality'] + 	'"' : '') + 
		(params['align']				? ' align="' +		params['align'] + 		'"' : '') + 
		(params['salign']				? ' salign="' +		params['salign'] + 		'"' : '') + 
		'>';
	
	FlashDisplay += '</object>';
	
	return FlashDisplay;
}
