function stdzSlashes(dm) {
	var len = dm.elements.length;
	var i = 0;
	for(i = 0; i < len; i++) {
		if( dm.elements[i].value ) {
			dm.elements[i].value = dm.elements[i].value.replace(RegExp("\'{1}" , "g"), "\\\'");
		}
	}
	return true;
}


function addSlashes( sText ) {
	if( sText) {
		return sText.replace(RegExp("\'{1}" , "g"), "\\\'");
	} else
		return sText;
}

function isNaturalNumber( sText ) {
    var re = /^[\d]+$/;
	return re.test( sText );
}

function isIntNumber( sText ) {
    if( sText.toString( ) == '-0' ) return false;
	
	var re = /^\-?[\d]+$/;
	return re.test( sText );
	
}
 
function isFloatNumber( sText ) {
	if( sText.toString( ) == '-0' ) return false;
	
	var re = /^\-?[\d]+$/;
	if( re.test( sText ) ) return true;
	re = /^\-?[\d]+\.[\d]+$/;
	return re.test( sText );
} 

function isEmpty( sText ) {
	if( !sText ) return false;
    
	return true;
}

function validateMail(email) {
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	if(reg.test(email) == false) {
	  return false;
	}
	return true;
}

function isNumberFormat( sText, sFormat ) {
	var specCharPattern = /[\D]/;
	var specChar = sFormat.match( specCharPattern );
	var aNum = sFormat.split( specChar );
	
	var sCmd = "var re = /^";
	for( var iC = 0; iC < aNum.length; iC++ ) {
		if( iC != 0 )
			sCmd += "\\" + specChar; 
		sCmd += "[0-9]{" + aNum[iC] + "}";
	}
	sCmd += "$/;";
	eval( sCmd );
	return re.test( sText );
}


// validates that the entry is formatted as an email address
function isEmail( sText ) {
    var str = sText;
	if(str == "") {
        //alert("Verify the email address format.");
        return false;
    }
    var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
    if (!str.match(re)) {
        //alert("Verify the email address format.");
        return false;
    } else {
        return true;
    }
}


function isValidInput( ) {
	var sText = "";
	var bEmptyAllowed = true;
	var bSpaceAllowed = true;
	
	switch( arguments.length ) {
		case 1:
			sText = arguments[0];
			break;
		case 2:
			sText = arguments[0];
			bEmptyAllowed = arguments[1];
			break;
		case 3:
			sText = arguments[0];
			bEmptyAllowed = arguments[1];
			bSpaceAllowed = arguments[2];
			break;
	}
	
	if( bEmptyAllowed ) {
		if( bSpaceAllowed )
			var re = /^[a-zA-Z0-9_\-\s]*$/;
		else 
			var re = /^[a-zA-Z0-9_\-]*/;
	}
	else {
		if( bSpaceAllowed )
			var re = /^[a-zA-Z0-9_\-\s]+$/;
		else 
			var re = /^[a-zA-Z0-9_\-]+$/; 
	}
	
	return re.test( sText );
			
}


function printPage() { print(document); }

function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function getInput( p_sFormId, p_sInputName ) {
	var oForm = document.getElementById( p_sFormId );
	eval( "var vInputVal = oForm." + p_sInputName + ".value;" );
	return vInputVal;
}


function getCheckBox( p_sFormId, p_sCheckBoxName ) {
	var oForm = document.getElementById( p_sFormId );
	eval( "var aChkBox = oForm." + p_sCheckBoxName + ";" );
	if( aChkBox.checked ) return aChkBox.value;
	else return "";
}


function getRadio( p_sFormId, p_sRadioName ) {
	var oForm = document.getElementById( p_sFormId );
	
	var checkedVal;
	eval( "var aRadio = oForm." + p_sRadioName + ";" );
	if( aRadio.length ) {
		for( var iC = 0; iC < aRadio.length; iC++ ) {
			if( aRadio[iC].checked ) {
				checkedVal = aRadio[iC].value;
				break;
			}
		}
	} else {
		if( aRadio.checked ) {
			checkedVal = aRadio.value;
		}
	}
	
	return checkedVal;
}


/*
 *	Param:
 *		p_sGName: multiple select box name(not including '[]')
 *	Return:
 *		option array (option within the multiple select box)
 *		checked option number
 *		unchecked option number
 *		checked values array
 */
function getOptionGroup( p_sGName ) {
	var oSelect = document.getElementById( p_sGName + '[]' );
	var aInput = oSelect.getElementsByTagName( "option" );
	var aCheckOption = new Array( );
	var aCheckedValue = new Array( );
	var aTemp = p_sGName.split( "[]" );
	var sGName = aTemp[0];
	
	var iNum = 0;
	var iCheckedNum = 0;
	var iUncheckedNum = 0;
	for( var iC = 0; iC < aInput.length; iC++ ) {
		aCheckOption[iNum++] = aInput[iC];
		if( aInput[iC].selected == true ) {
			aCheckedValue[iCheckedNum] = aInput[iC].value;
			iCheckedNum ++;
		}
		else
			iUncheckedNum++;
	}
	
	return Array( aCheckOption, iCheckedNum, iUncheckedNum, aCheckedValue );
}


//-- Functions set controls checkbox groups interaction
/*
 *	Call on 'checkall' checkbox
 *	Param:
 *		p_sGName: checkbox group name(including '[]')
 */
function checkAll( p_sGName ) {
	var aTemp2 = p_sGName.split( "[]" );
	var sGName = aTemp2[0];
	var oCheckAll = document.getElementById( sGName + "All" );
	
	var aTemp = getCheckGroup( p_sGName );
	var aCheckbox = aTemp[0];
	var iCheckedNum = aTemp[1];
	
	for( var iC = 0; iC < aCheckbox.length; iC++ ) {
		aCheckbox[iC].checked = oCheckAll.checked;
	}
	
}


/*
 *	Call on each checkbox in group
 *	Param:
 *		p_sGName: checkbox group name(including '[]')
 *		p_vValue: checkbox value
 */
function checkOne( p_sGName, p_vValue ) {
	var aTemp2 = p_sGName.split( "[]" );
	var sGName = aTemp2[0];
	var oCheckAll = document.getElementById( sGName + "All" );
	
	var aTemp = getCheckGroup( p_sGName );
	var aCheckbox = aTemp[0];
	var iCheckedNum = aTemp[1];
	
	if( iCheckedNum == aCheckbox.length )
		oCheckAll.checked = true;
	else
		oCheckAll.checked = false;
}


/*
 *	Param:
 *		p_sGName: checkbox group name(not including '[]')
 *	Return:
 *		checkbox array(checkboxes in the group)
 *		checked checkbox number
 *		unchecked checkbox number
 *		checked values array
 */
function getCheckGroup( p_sGName ) {
	var aInput = document.getElementsByTagName( "input" );
	var aCheckbox = new Array( );
	var aCheckedValue = new Array( );
	var aTemp = p_sGName.split( "[]" );
	var sGName = aTemp[0];
	
	var iNum = 0;
	var iCheckedNum = 0;
	var iUncheckedNum = 0;
	for( var iC = 0; iC < aInput.length; iC++ ) {
		if( aInput[iC].type == "checkbox" && aInput[iC].name == (sGName + "[]") ) {
			aCheckbox[iNum++] = aInput[iC];
			if( aInput[iC].checked == true ) {
				aCheckedValue[iCheckedNum] = aInput[iC].value;
				iCheckedNum ++;
			}
			else
				iUncheckedNum++;
		}
	}

	return Array( aCheckbox, iCheckedNum, iUncheckedNum, aCheckedValue );
}
//-- End
var timed_retrive_password	= 3;
function doGetPassword() {
	var email		= $('input[name=email]').val();
	var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
	if ( email == '' ) {
		$('div#get_pw_msg').html("Please enter your e-mail address!");
		$('input[name=email]').focus();
		return;
	} else if ( !emailFilter.test( email ) ) {
		$('div#get_pw_msg').html("Please enter a valid e-mail address!");
		$('input[name=email]').focus();
		return;
	} else {
		var oParam		= new Object();
		oParam.email	= email;
		oRootEngine.setParam( oParam );
		$('div#get_pw_msg').html("Loading...");
		oRootEngine.doAsyncTaskImp( 'user', '', 'retrive_password', 
			function ( rs ) {
				$('div#TB_ajaxContent').height(230);
				$('div#get_pw_msg').html(rs);
			}
		);
	}
}

function doLogin() {
	var rememberme	= 0;
	var username	= $("input[name='email']", $('#loginForm') ).val();
	var password	= $("input[name='password']", $('#loginForm') ).val();
	var id			= document.getElementById('loginForm');
	var redir		= document.getElementById('redir');
	$(':input[name=remember]').each(function(){
		if ( this.checked == true ) {
			rememberme	= this.value;
		}
	});
	
	if ( username == '' ){
		alert("Username is Empty!");
		$("input[name='email']", $('#loginForm') ).focus();
		return false;
	} else if ( password == '' ){
		alert("Password is Empty!");
		$("input[name='password']", $('#loginForm') ).focus();
		return false;
	} else {
		var oParam		= new Object();
		oParam.username	= username;
		oParam.password	= password;
		oParam.redir	= redir.value;
		oParam.rememberme	= rememberme;
		oRootEngine.setParam( oParam );
		oRootEngine.doAsyncTaskImp( 'user','','dologin',
			function ( result ) {
				var aTemp 	    = JSON.parse( result );
				var type 	    = parseInt( aTemp[0] );
				var msg 	    = aTemp[1];
				var lnkRedirect = aTemp[2];
				switch (type) {
				  case 1: //valid login
					    tb_remove();
						if (lnkRedirect) {
							window.location = lnkRedirect;
						} else {
							enableBtn();
							loadAjaxArea();
							$('#control_box').slideUp('slow');
							$('#control_box').slideDown('slow');
						};
				    break;
				  case 2: //re-activate
				    	var answer = confirm ( msg );
						if (answer){
							_doReactivate( oParam );
						};
				    break;
				  default: //invalid login
				  		$('div._messageLoginPwd').html(msg);
				  	break;
				} 
				
				loadCompJS( oRootEngine );
			}
		);
	}
}

function _doReactivate( oParam )
{
	oParam.reactivate = true;
	oRootEngine.setParam( oParam );
	oRootEngine.doAsyncTaskImp( 'user','','reactivate',
	function ( result ) {
		if ( JSON.parse( result )[0] == 1 ) {
			$('#invalid').addClass('hidden');
			location.reload();
		}
	});
}

function doGetPasswordPrehome() {
	var email		= $('#forgot_email').val();
	var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
	if ( email == '' ) {
		$('#invalid_forgot').html("Please enter your e-mail address!<br><br>").removeClass('hidden');
		$('#forgot_email').focus();
		return;
	} else if ( !emailFilter.test( email ) ) {
		$('#invalid_forgot').html("Please enter a valid e-mail address!<br><br>").removeClass('hidden');
		$('#forgot_email').focus();
		return;
	} else {
		var oParam		= new Object();
		oParam.email	= email;
		oRootEngine.setParam( oParam );
		oRootEngine.doAsyncTaskImp( 'user', '', 'retrive_password', 
			function ( rs ) {
				$('#invalid_forgot').html(rs + '<br><br>').removeClass('hidden');
			}
		);
	}
}

function doRequestInvite() {
	var em_txt		= $('#invite_email');
	var email		= em_txt.val();
	var name_txt	= $('#invite_name');
	var name		= name_txt.val();
	var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
	if ( email == '' ) {
		$('#invalid_invite').html("Please enter your e-mail address!<br><br>").removeClass('hidden');
		em_txt.focus();
		return;
	} else if ( !emailFilter.test( email ) ) {
		$('#invalid_invite').html("Please enter a valid e-mail address!<br><br>").removeClass('hidden');
		em_txt.focus();
		return;
	} else {
		var oParam		= new Object();
		oParam.email	= email;
		oParam.name		= name;
		oRootEngine.setParam( oParam );
		oRootEngine.doAsyncTaskImp( 'user', '', 'get_beta_invite',
			function ( rs ) {
				rs = eval( rs );
				$('#invalid_invite').html(rs[1] + '<br><br>').removeClass('hidden');
				if (rs[0]) {
					$('#reqInviteEmailArea').fadeOut('slow');
				}
			}
		);
	}
}
/**
 *	Load all available area after Login successful
 */
function enableBtn() {
	$('ul.main-nav li[title=submit]').html('<a href="'+ABS_PATH+'?sys_sOption=flip&amp;sys_sTask=submit" title="Submit A Flip" class="submit">SUBMIT A FLIP</a>');
	$('ul.main-nav li[title=stack]').html('<a href="'+ABS_PATH+'stack" title="Flip Stack" class="stack">FLIP STACK</a>');
//	$('ul.main-nav li[title=stack]').html('<a href="'+ABS_PATH+'?sys_sOption=stack&amp;sys_sTask=view" title="Flip Stack" class="stack">FLIP STACK</a>');
	$('ul.main-nav li[title=my]').html('<a href="'+ABS_PATH+'?sys_sOption=user&amp;sys_sTask=view" title="My Flipshake" class="my last">MY FLIPSHAKE</a>');
}

function loadAjaxArea(facebook) {
//	console.log( document.getElementById('mod_defaultHeaderDiv') );
//	console.log( parent.$("#mod_defaultHeaderDiv", '*').is("div") );
	if ( document.getElementById('control_box') ) {
		loadHTMLById( 'control_box', "Loading..." );
		var oParam		= new Object();
		oParam.uid		= document.getElementById('mainForm').user_id.value;
		oRootEngine.setParam( oParam );
		oRootEngine.doAsyncTaskImp( 'user', '', 'show_control_box',
			function ( result ) {
				$('#control_box').html( result );
			}
		);
	}
	
	if ( document.getElementById('mod_defaultHeaderDiv') ) {
//	if ( $("#mod_defaultHeaderDiv", parent).is("div") ) {
		var oParam	= new Object();
		oRootEngine.doAsyncTaskImp( 'user','','user_tabs_process',
			function ( result ) {
				var _self = $('*').index( $('#flipshake_nav_button_bar li.current') );
				$( '#mod_defaultHeaderDiv').html( result );
				menuHovers();
				$("#flipshake_nav_button_bar ul li").removeClass('current');
				$("#flipshake_nav_button_bar ul li").removeClass('active');
				$('*').eq(_self).addClass('current active');
				$("#flipshake_nav_button_bar li.current img.arrow").attr('src', ABS_PATH +'layouts/default/images/arrow_current.gif');
			}
		);
	}
		
	if ( document.getElementById('mod_userAreaDiv') ) {
		oRootEngine.doAsyncTaskImp( 'user','','user_bar_process',
			function ( result ) {
				loadHTMLById( 'mod_userAreaDiv', result );
				tb_init('a#searchLink');
			}
		);
	}
	
	if ( document.getElementById('userInfoBox') ) {
		loadHTMLById( 'userInfoBox', "Loading..." );
		oRootEngine.doAsyncTaskImp( 'user','','user_info_box_process',
			function ( result ) {
				loadHTMLById( 'userInfoBox', result );
			}
		);
	}
	
	if ( document.getElementById('leaderBoard') ) {
		loadHTMLById( 'leaderBoard', "Loading..." );
		oRootEngine.doAsyncTaskImp( 'user','','leaderboard_process',
			function ( result ) {
				loadHTMLById( 'leaderBoard', result );
			}
		);
	}
	
	if ( document.getElementById('flip-interactive-btn') ) {
		loadHTMLById( 'flip-interactive-btn', "Loading..." );
		var oParam			= new Object();
		oParam.flip_id		= document.getElementById('mainForm').flip_id.value;
		oRootEngine.setParam( oParam );
		oRootEngine.doAsyncTaskImp( 'user','','user_flip_interactive_btn',
			function ( result ) {
				loadHTMLById( 'flip-interactive-btn', result );
			}
		);
	}
	
	if ( document.getElementById('post-comment-area') ) {
		location.reload();
//		loadHTMLById( 'post-comment-area', "Loading..." );
//		hidMaker = document.getElementsByName('maker_id');
//		var oParam		= new Object();
//		oParam.maker_id  = hidMaker[0].value;
//		oRootEngine.setParam( oParam );
//		oRootEngine.doAsyncTaskImp( 'flip', '','user_post_comment_area',
//			function ( result ) {
//				$('#post-comment-area').html(result);
//				$.getScript("/extensions/tiny_mce/tiny_mce.js");
////				loadCompJS( oRootEngine );
//			}
//		);
	}
	
	if ( document.getElementById('post-comment-area-user') ) {
		location.reload();
//		loadHTMLById( 'post-comment-area-user', "Loading..." );
//		oRootEngine.doAsyncTaskImp( 'user', '', 'user_post_comment_area',
//			function ( result ) {
//				$('#post-comment-area-user').html(result);
//				$.getScript("/extensions/tiny_mce/tiny_mce.js");
//				loadCompJS( oRootEngine );
//			}
//		);
	}
	
	if ( document.getElementById('btnLogin2Collect') ) {
		var _view = $(':input[name=x_view]').val();
		var _task = $(':input[name=sys_sTask]').val();
		var _option = $(':input[name=sys_sOption]').val();
		if(_view == 'detail' && _task == 'gallery' && _option == 'flip') {
			var page 	= $('div._up div.pagers ul li.active').children().text();
			var oForm	= document.getElementById('mainForm');
			viewFlipGallery( oForm.x_view.value, page );
		}
		if(_task == 'view' && _option == 'flip') {
			location.reload();
		}
	}
	
	if ( document.getElementById('divForums49c7a7b25789c'))
	{
		location.reload();
	}
	
	if ( $(':input[name=_LoginInShareMyEmail]').length == 1 )
	{
		doShareMyMail(true);
		location.reload();
	}
	
	if(facebook) { location.reload(); }
}

function doSignup( beta ) {
	var username	= document.getElementById('username');
	var password	= document.getElementById('password');
	var r_password	= document.getElementById('r_password');
	var email		= document.getElementById('email');
	var r_email		= document.getElementById('r_email');
	var accept		= document.getElementById('accept');
	var code		= document.getElementById('signup_code');
//	for ( var i=0; i<genderGroup.length; i++ ) {
//		if (genderGroup[i].checked) {
//			gender	= genderGroup[i].value;
//		}
//	}
	var usrnamePat	= /\W/;
	var emailPat	= /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if ( username.value == '' ){
		alert("Username is Empty!");
		username.focus();
		return false;
	} else if ( usrnamePat.test( username.value ) ){
		alert("Username contains illegal characters!");
		username.focus();
		return false;
	} else if ( email.value == '' ){
		alert("Email is Empty!");
		email.focus();
		return false;
	} else if ( !emailPat.test( email.value ) ){
		alert("Invalid Email Address!");
		email.focus();
		return false;
	} else if ( password.value == '' ){
		alert("Password is Empty!");
		password.focus();
		return false;
	} else if ( (password.value.length < 6) || (password.value.length > 20) ){
		alert("Password must have 6-20 charaters!");
		password.focus();
		return false;
	} else if ( password.value != r_password.value ){
		alert("Passwords don't match!");
		r_password.focus();
		return false;
	} else if ( accept.checked == false ){
		alert("You don't accept our Terms.");
		return false;
	} else {
		var oParam			= new Object();
		oParam.username		= username.value;
		oParam.password		= password.value;
		oParam.email		= email.value;
		oParam.code			= code ? code.value : 0;
		oParam.beta			= beta ? 1 : 0;
		oRootEngine.setParam( oParam );
		oRootEngine.doAsyncTaskImp( 'user','','dosignup',
			function ( result ) {
				var aTemp 	= JSON.parse( result );
				var type 	= aTemp[0];
				var msg 	= aTemp[1];
				$('div#signupMsg').html(msg);
				if (type) {
//					$('[name=signupRest]').fadeOut('slow');
					$('div.FS-divOnLogin]').fadeOut('slow');
					if (beta) {
						setTimeout("window.location = '"+ABS_PATH+"?sys_sOption=content&sys_sTask=welcome';", 2000);
					}
					else{
						$('div#signupMsg').height(270);
						$('div#TB_ajaxContent').height(580);
					}
				}
				loadCompJS( oRootEngine );
			}
		);
	}
}

function sendReportAbuse() {
	var oParam		= new Object();
	oParam.subject	= $('#subjectAbuse option:selected').text();
	oParam.message	= $("textarea[name='messageAbuse']").val().replace(/\n/g, '<br />');
	oParam.user		= $("input[name='hLoggedUser']").val();
	oParam.url		= window.location.href;
	$("div.message").html("Please wait a minute.<br/>Sending report....<br/><br/>")
	oRootEngine.setParam( oParam );
	oRootEngine.doAsyncTaskImp( 'default', '', 'send_reportabuse',
		function ( result ) {
			if( result == '_nologued' ) {
				alert ('Permission Denied. Please Login to Continue!');
			}
			else if( result == '_yes') {
				alert ('The report has been sent.');
				$("#TB_closeWindowButton").click();
			}
		}
	);
}
function sendFeedback() {
	var oParam		= new Object();
	oParam.subject	= $('#subjectFeedback option:selected').text();
	oParam.message	= $('#messageFeedback').val().replace(/\n/g, '<br />');
	oParam.email	= $("input[name=emailFeedback]").val();
	oParam.user		= $("input[name=hLoggedUser]").val();
	
	oParam.url		= window.location.href;
	oParam.browser 	= navigator.appCodeName +' '+ navigator.appName +' ' + navigator.appVersion;
	oParam.res 		= window.screen.availWidth + ' x ' + window.screen.availHeight;
	oParam.platform = navigator.platform;
	
	$("div.message").html("Please wait a minute.<br/>Sending Feedback....<br/><br/>")
	oRootEngine.setParam( oParam );
	oRootEngine.doAsyncTaskImp( 'default', '', 'send_feedback',
		function ( result ) {
			if( result == '_nologued' ) {
				alert ('Permission Denied. Please Login to Continue!');
			}
			else if( result == '_yes') {
				alert ('The feedback has been sent. Thank you very much for your help.');
				$("#TB_closeWindowButton").click();
			}
		}
	);
}

function changeUser()
{
	var valUser = $(':input[name=username] option:selected').text();
	
	var user = $(':input[name=username] option:selected').val();
	if(user != '0' )
	{
		AddUsersInput( user );
		$(':input[name=username] option:selected').remove();
				
		refreshSel();
		
		var objLink = document.createElement('a');
		objLink.className ='name';
		objLink.appendChild(document.createTextNode( valUser ));
		//self = $(this);
		objLink.onclick = function(){
			 $(':input[name=username] option').removeAttr("selected");
			 RemoveUsersInput( user );
			 var optionUser = document.createElement('option');
			 optionUser.setAttribute('label', $(this).text() );
			 optionUser.setAttribute('value', user );
			 optionUser.setAttribute('selected', 'selected' );
			 optionUser.appendChild(document.createTextNode( $(this).text() ));
			 
			 $('#mySelectText0').text( $(this).text() );
			 $(':input[name=username]').append(optionUser);
			 $(this).remove();

			 refreshSel();				 
		}
		$('div.compose-tocontainer').append( objLink );
	}
}

function refreshSel()
{
	if( typeof( selects[0] ) != 'undefined' ){
		selects[0]._ca = false;
		selects[0]._options = false;
		$('#sarea0').remove();
		$('#optionsDiv0').remove();
		reload();
		$('#sarea0').removeClass('outtaHere');
	}	
}
function AddUsersInput(newValue)
{
	var arr = null;
	if( !$("input[name=username_x]").is(null) ) { if(newValue != null) { arr = ( $("input[name=username_x]").val().length != 0 ) ? $("input[name=username_x]").val() + ',' + newValue : newValue; } $("input[name=username_x]").val(arr); }
}

function RemoveUsersInput(element)
{
	if($("input[name=username_x]").val().length == 1){
		var arr = $("input[name=username_x]").val();
	}
	else{
		var arr = $("input[name=username_x]").val().split(',');
		for(var i=0; i<arr.length; i++){ if(arr[i] == element){ arr.splice(i, 1); } }
	}
	
	$("input[name=username_x]").val( arr );
}

function sendTellFriend() {
	var valid = true;
	var message = document.getElementById('message').value;
	var friends = $('input[name=username_x]').val();
	flipUrl = document.documentURI;

	if (valid) {
		if ( friends == '') {
			alert('Duh! If you want to tell someone about this person you have to choose that someone first. Use your friend list to select users.');
			valid = false;
		}
		else {
			if (message == '') {
				alert('Please enter your message to send!');
				valid = false;
			}
		}
	}
	if (valid) {
		var oParam		= new Object();
		oParam.message	= message;
		oParam.friends	= friends;
		oParam.flipUrl	= flipUrl;
	
		oRootEngine.setParam( oParam );
		
		oRootEngine.doAsyncTaskImp( 'default', '', 'tell_friends',
			function (ee) {
				$("#TB_closeWindowButton").click();
			}
		);
	}
}
function sendTellFriendToFriend() {
	var valid = true;
	var message = document.getElementById('message').value;
	var friends = $('input[name=username_x]').val();
	flipUrl = document.documentURI;
		
	if (valid) {
		if ( friends == '') {
			alert('Please select any friend or write any email to send the flip!');
			valid = false;
		}
		else {
			if (message == '') {
				alert('Please enter your message to send!');
				valid = false;
			}
		}
	}
	if (valid) {
		var oParam		= new Object();
		oParam.message	= message;
		oParam.friends	= friends;
		oParam.flipUrl	= flipUrl;
	
		oRootEngine.setParam( oParam );
		
		oRootEngine.doAsyncTaskImp( 'default', '', 'tell_friendstofriend',
			function (ee) {
				$("#TB_closeWindowButton").click();
			}
		);
	}
}

function chkImage(w, h){
	/*landscape portrait*/	
	if (w > h){
	   return 'landscape';
	}else{
	   return 'portrait'; 
	}
}

function addImage(path, idImg, w, h)
{		
	_image = new Image();
	_image.src = path;
	
	$('#'+idImg)
	.attr('src', _image.src)
    .attr('width', w )
	.attr('height', h );
}

function ResizeImageSubmit(path, idDiv, w, h, max_width, max_height)
{
	var landscape = false;/*landscape portrait*/
	var NewFlipImageSubmit = new Image();
	NewFlipImageSubmit.src = path;

	var x_ratio = max_width / w;
	var y_ratio = max_height / h;
	
	if( (w <= max_width) && (h <= max_height) ){
	    tn_width = w;
	    tn_height = h;
	    landscape = ( w > h) ? true : false;
	}else if ((x_ratio * h) < max_height){
	        tn_height = Math.ceil(x_ratio * h);
	        tn_width = max_width;
	        landscape = true;
	    }else{
	        tn_width = Math.ceil(y_ratio * w);
	        tn_height = max_height;
		} 
		   
  $( '#'+idDiv )
    .hide("slow")
    .slideToggle("slow",function(){
      	$(this).css('padding', '0px');
      	if(landscape)
      	{
      		$(this).css('margin-top', ( (max_height - Math.ceil( x_ratio * h)) / 2 ) + 'px');
      	}	
		else 
			$(this).css('margin', 'auto');
		
      })   
    .error(function(){ /* notify the user that the image could not be loaded */ })
    .attr('src', NewFlipImageSubmit.src) //+ '?' + Math.random()
    .attr('width', tn_width )
	.attr('height', tn_height );	
}

function changeText( side ) {
	var id	= 'btn-'+side+'side';
//	$('a#'+id).html("UPLOAD A DIFFERENT " + side.toUpperCase() + " SIDE IMAGE");
	$('a#'+id).html('Upload a different ' + side + ' side image');
	$('a#'+id).css('font-size','13px');
}

function checkSquare()
{
	var fSquare = 'null';
	var bSquare = 'null';
	
	var strFront = $('#sys_SizeFront').val();
	var fSize = strFront.split(',');
	fSquare = ( fSize[0] == fSize[1] ) ? true : false;
	
	if( $('#sys_SizeBack').val() )
	{
		var strBack = $('#sys_SizeBack').val();
		var bSize = strBack.split(',');
		bSquare = ( bSize[0] == bSize[1] ) ? true : false;
	}
	if( fSquare && bSquare ) 
		return true;
	else
		if (fSquare && typeof(bSquare) == 'null' ) 
			return true;
		else if(fSquare && !bSquare) 
			return false;
}

function doCropAvatar()
{	
	var msgSideFlip		= '';
	var nSideFlip		= '';
    var oForm			= document.getElementById('avatarCropForm');
	var oParam			= new Object();
	oParam.nSide		= $('#sys_nSide').val();
	
	$('#sys_nCrop').val('1');

	if( oParam.nSide == 'crop-image-front')
	{
		oParam.sys_sTmpFront	= oForm.sys_sTmpFront.value;
		oParam.fx1	= oForm.fx1.value;
		oParam.fy1	= oForm.fy1.value;
		
		oParam.fx2	= oForm.fx2.value;
		oParam.fy2	= oForm.fy2.value;
		
		oParam.fw	= oForm.fw.value;
		oParam.fh	= oForm.fh.value;	
		nSideFlip   = 'sys_sOriginalAvatar';
		msgSideFlip = 'msg-crop-image-front';
		FlipFront = true;
	}
	
	oRootEngine.setParam( oParam );
	oRootEngine.doAsyncTaskImp( 'user', '','do_crop',
		function ( result )
		{
			var oForm = parent.document.getElementById('mainForm');
			var oParam = new Object();
			oParam.profile_id = oForm.user_id.value;
			
			oRootEngine.setParam( oParam );
			oRootEngine.doAsyncTaskImp( 'user', '','commentListing',
				function ( result )
				{
					parent.$('ul#commentsList').html(result);
				}
			);
			
			setTimeout(result, 1000);			
		}
	);
}

function doCropThumbnail()
{	
	var msgSideFlip		= '';
	var nSideFlip		= '';
    var oForm			= document.getElementById('thumbnailCropForm');
	var oParam			= new Object();
	oParam.nSide		= $('#sys_nSide').val();
	
	$('#sys_nCrop').val('1');

	if( oParam.nSide == 'crop-image-front')
	{
		oParam.sys_sTmpFront	= oForm.sys_sTmpFront.value;
		oParam.fx1	= oForm.fx1.value;
		oParam.fy1	= oForm.fy1.value;
		
		oParam.fx2	= oForm.fx2.value;
		oParam.fy2	= oForm.fy2.value;
		
		oParam.fw	= oForm.fw.value;
		oParam.fh	= oForm.fh.value;	
		nSideFlip   = 'sys_sOriginalAvatar';
		msgSideFlip = 'msg-crop-image-front';
		FlipFront = true;
		
		oParam.x_sid = parent.document.getElementsByName('sid')[0].value;
	}
	
	oRootEngine.setParam( oParam );
	oRootEngine.doAsyncTaskImp( 'user', '','do_crop_thumbnail',
		function ( result )
		{
			eval(result);
		}
	);
}

function doCropBanner()
{	
	var msgSideFlip		= '';
	var nSideFlip		= '';
    var oForm			= document.getElementById('bannerCropForm');
	var oParam			= new Object();
	oParam.nSide		= $('#sys_nSide').val();
	
	$('#sys_nCrop').val('1');

	if( oParam.nSide == 'crop-image-front')
	{
		oParam.sys_sTmpFront = oForm.sys_sTmpFront.value;
		oParam.fx1	= oForm.fx1.value;
		oParam.fy1	= oForm.fy1.value;
		
		oParam.fx2	= oForm.fx2.value;
		oParam.fy2	= oForm.fy2.value;
		
		oParam.fw	= oForm.fw.value;
		oParam.fh	= oForm.fh.value;	
		nSideFlip   = 'sys_sOriginalBanner';
		msgSideFlip = 'msg-crop-image-front';
		FlipFront = true;
		
		oParam.x_sid = parent.document.getElementsByName('user_id')[0].value;
	}
	
	oRootEngine.setParam( oParam );
	oRootEngine.doAsyncTaskImp( 'user', '','do_crop_banner',
		function ( result )
		{
			eval(result);
		}
	);
}

function adjustPageHeight()
{
	var newHeight = getVisibleBottomYFooter() - getElementHeightFooter('footer') - getElementHeightFooter('header') - 2;
	
	if((getElementHeightFooter('pagewidth') < getVisibleBottomYFooter()))
	{
		$('#main').css({height: newHeight + "px"});
	}
	else
	{
		$('#main').css({height: "auto"});
	}
}

function getVisibleBottomYFooter()
{
	if(typeof window.innerWidth != 'undefined')
	{
		return window.innerHeight;
	}
	else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0)
	{
		return document.documentElement.clientHeight;
	}
	else
	{
		return document.getElementsByTagName('body')[0].clientHeight;
	}
}

function getElementHeightFooter(objectId) {
	y = document.getElementById(objectId);
	return y.clientHeight;
}

function findContactFriends(){
	var oForm = document.getElementById('inviteform');
	var oParam = new Object();
	oParam.userEmail 		= oForm.userEmail.value;
	oParam.pwdEmail 		= base64_encode(oForm.pwdEmail.value);
	oParam.address_book_type= oForm.address_book.value;
	
	$('#invite_loader').html('<b style="font-style:italic;">Processing...</b>');
	$.post(ABS_PATH + "contacts.php", oParam, function(data){
		if ( data == '__fs_error__' ) {
			window.location = ABS_PATH+'error.php';
		}
		MessageAddressBook(data);
	  }, "json");
}

function MessageAddressBook(data) {
	switch (data.address_book) {
	  case 1: //invalid login
	    $('#invite_loader').html( "<b style=\"color:red\">Invalid Login</b>" );
	    break;
	  case 2: //empty username or password
	    $('#invite_loader').html( "<b style=\"color:red\">Enter Your Username and Password</b>" );
	    break;
	  case 3: //no contacts were found, potential error during web requests processing/contacts parsing
	    $('#invite_loader').html( "<b style=\"color:red\">No contacts were found.</b>" );
	    break;
	  default:
	  	if (data.address_book.length == 0) {
	  		$('#invite_loader').html( "<b style=\"color:red\">No contacts were found.</b>" );
	  	} else {
	    	doListContacts(data);
	  	}
	  	break;
	}
}

function doListContacts(data){
	var oParam2 = new Object();
	oParam2.address_book = data.address_book;
	oRootEngine.setParam( oParam2 );
	oRootEngine.doAsyncTaskImp( 'default', '','do_list_contacts',
		function ( result )
		{
			jQuery(function($) {
				$('#TB_ajaxContent').html( result );
				//$('#TB_ajaxContent').height(350);
				tb_init_form();				
			});
		}
	);
}

function addSeriesFlip()
{
	var _sets 		= new Object();
	_sets.Ids 	= '';
	_sets.flipId = $(':input[@name=flip_id]').val();
	   
	$("input[@name=sets]:checked").each(function(){
		_sets.Ids += _sets.Ids ? ", " + this.value : this.value;
	});
	
	var oForm = document.getElementById('sets_for_flip');
	var oParam = new Object();
	oParam.sets_list 	= _sets;
	oRootEngine.setParam( oParam );
	oRootEngine.doAsyncTaskImp( 'default', '','do_add_sets', function ( result ){
			if(result) {
				$('#sets').html(result);
			}
			tb_remove();
		}
	);
}

function addContactFriends(){
   var emails = new Object();
   emails.friends = '';
   emails.names = '';
   
   $("input[@name=addresses]:checked").each(function(){
		emails.friends += emails.friends ? ", " + this.value : this.value;
		var str = $(this).parent().parent().children('td.t2',this).text();
		emails.names	+= emails.names ? ", " + str : str;
	});
	
	var oForm = document.getElementById('inviteform3');
	var oParam = new Object();
	oParam.addresses_list 	= emails;
	oRootEngine.setParam( oParam );
	oRootEngine.doAsyncTaskImp( 'default', '','do_add_contacts',
		function ( result )
		{
			jQuery(function($) { 
				$('#TB_ajaxContent').html(result);
				wordCount();
//				$('#TB_ajaxContent').height(520);
			});
		}
	);	
}

var noTxt = 'You haven\'t enough invites to send to that many friends, uncheck another before checking a new one (current Flipshake users aren\'t counted).';

function refCount(disccounts, chk) {
	if (disccounts) {
		var hInvites = $('#hInvites');
		var cur = parseInt($('#hInvites').html());
		if (chk.checked) {
			//unchecking
			hInvites.html((cur + 1).toString());
		} else {
			//checking
			if (cur == '0') {
				alert(noTxt);
				setTimeout(
					function() {
						chk.checked = false;
						chk._ca.checked = false;
						chk._ca.className = "checkboxArea";
					}, 250);
				} else {
				hInvites.html((cur - 1).toString());
			}
		}
	}
}

function sendContactFriends(){
	var cEmail = $(':input[@name=addresses_list]').val().split(',').length;
	var oForm = document.getElementById('inviteform1');
	var cInvitesControl 	= oForm.cInvites.value;
	
	var oParam = new Object();
	oParam.addresses_list 	= oForm.addresses_list.value;
	oParam.message 			= oForm.messageInvite.value;
	
	if ($('#hInvites').text() !== 'You have exceeded your Friends limit.') {
		oRootEngine.setParam( oParam );
		oRootEngine.doAsyncTaskImp( 'default', '','do_send_emails',
			function ( result )
			{
				jQuery(function($) { 
					$('#TB_ajaxContent').html(result);
				});
			}
		);
	} else {
		alert('Remove some friends, you can\'t send that many invites!');
	}
}

var _wcReq = false;

function wordCount()
{
	if($(':input[@name=addresses_list]').val().length != 0)
	{
		var oParam = new Object();
		oParam.emails = $(':input[@name=addresses_list]').val();
		oRootEngine.setParam( oParam );
		if (_wcReq) {
			_wcReq.abort();
		}
		_wcReq = oRootEngine.doAsyncTaskImp( 'user', '','get_quantity_disccount',
			function ( result )
			{
				var wordLength = parseInt( result );
				cLimit = $(':input[@name=cInvites]').val() - wordLength;
				
				if( wordLength > $(':input[@name=cInvites]').val() )
				{
					$('#hInvites').text( 'You have exceeded your Friends limit.' );
					$('#hInvites').css("font-size","10px");
				}
				else
				{
					$('#hInvites').text( cLimit );
					$('#hInvites').css("font-size","48px");
				}
			}
		);
	}
	
	if($(':input[@name=addresses_list]').val().length == 0)
	{
		$('#hInvites').text( $(':input[@name=cInvites]').val() );
		$('#hInvites').css("font-size","48px");
	}
}

function showMsgUpdate()
{
	$('#view').fadeIn();
}

function hideMsgUpdate()
{
	$('#view').fadeOut();
}

function ToogleReply(divf)
{
	if ( $('#'+divf).css('display') == "block" ) 
	{ $('#'+divf).hide(); }
	else
	{ 
		$('#'+divf).show();
		tinyMCE.execCommand('mceFocus',false, $("textarea[name='x_reply']", $('#'+ divf)).attr("id") ); 
	}
}

function printr(objDat, vista)
{
	var t = typeof(objDat);

	if(t != 'undefined')
	{
		if(t == 'string')
		{
			t = "("+t+") "+objDat;
		} else {
			var r = '';
			var n = '';
			switch(vista)
			{
				case 1:n = "<br>\n";break;
				default:n = "\n";break;
			}
			for(i in objDat)
			{
				t += "["+i+"] => "+objDat[i]+n;
			}
		}
	} else {
		r = t;
	}

	switch(vista)
	{
		case 1:
		var v = window.open(null,null,null);
		v.document.write('<pre>'+t+'</pre>');
		break;
		default:
		alert(t);
		break;
	}
}

function doShareMyMail(fl)
{
	var oParam		= new Object();
 	oParam.stackId	= $(':input[name=stack_id]').val();
 	oParam.suscribe = ( fl ) ? 'YES' : 'NO';
	oRootEngine.setParam( oParam );
	oRootEngine.doAsyncTaskImp( 'stack', '' , 'do_stack_suscribe',
		function ( result ) {
			var aTemp 	    = JSON.parse( result );
		}
	);
}

function doLoginPrehome() {
	var rememberme	= 0;
	var username	= document.getElementById('login_email');
	var password	= document.getElementById('login_password');
	var redir		= document.getElementById('redir');
	$(':input[name=remember]').each(function(){
		if ( this.checked == true ) {
			rememberme	= this.value;
		}
	});
	
	if ( username.value == '' ){
		alert("Username is Empty!");
		username.focus();
		return false;
	} else if ( password.value == '' ){
		alert("Password is Empty!");
		password.focus();
		return false;
	} else {
		var oParam			= new Object();
		oParam.username		= username.value;
		oParam.password		= password.value;
		oParam.redir		= redir.value;
		oParam.rememberme	= rememberme;
		oRootEngine.setParam( oParam );
		oRootEngine.doAsyncTaskImp( 'user','','dologin',
			function ( result ) {
				if ( JSON.parse( result )[0] == 1 ) {
					$('#invalid').addClass('hidden');
					location.reload();
				} else {
					$('#invalid').html( JSON.parse( result )[1] );
					$('#invalid').removeClass('hidden');
					if(JSON.parse( result )[0] == 2){
						var answer = confirm ( JSON.parse( result )[1] );
						if (answer){
							_doReactivate( oParam );
						}
					}
				}
			}
		);
	}
}
