/* -----------------------------------------------------------------
$Date: 2010-04-14 23:01:43 -0700 (Wed, 14 Apr 2010) $
$LastChangedBy: Jim Edlin $
$Revision: 176 $

Consolidated javascript code for site

Copyright © 2008-2009 The2ofYou.com
----------------------------------------------------------------- */

/*-----------------------------------------------------------
GENERAL UTILITIES
---------------------------------------------------------*/

/*-----------------------------------------------------------
Toggle element's display value
Input: any number of element id's
Output: none 
---------------------------------------------------------*/
function toggleDisp() {
    for (var i=0;i<arguments.length;i++){
        var d = $(arguments[i]);
        if (d.style.display == 'none')
            d.style.display = 'block';
        else
            d.style.display = 'none';
    }
}

/*-----------------------------------------------------------
Toggle tabs - Closes any open tabs, and then opens current tab
Input:     1.The number of the current tab
           2.The number of tabs
           3.(optional) The number of the tab to leave open
           4.(optional) true or false - animate open/close of tabs
Output: none 
---------------------------------------------------------*/
function toggleTab(num,numelems,opennum,animate) {
	if ($('tabContent'+num).style.display == 'none'){
		for (var i=1;i<=numelems;i++){
			if ((opennum == null) || (opennum != i)){
				var temph = 'tabHeader'+i;
				var h = $(temph);
				if (!h){
					var h = $('tabHeaderActive');
					h.id = temph;
				}
				var tempc = 'tabContent'+i;
				var c = $(tempc);
				if(c.style.display != 'none'){
					if (animate || typeof animate == 'undefined')
						Effect.toggle(tempc,'blind',{duration:0.5, queue:{scope:'menus', limit: 3}});
					else
						toggleDisp(tempc);
				}
			}
		}
		var h = $('tabHeader'+num);
		if (h)
			h.id = 'tabHeaderActive';
		h.blur();
		var c = $('tabContent'+num);
		c.style.marginTop = '2px';
		if (animate || typeof animate == 'undefined'){
			Effect.toggle('tabContent'+num,'blind',{duration:0.5, queue:{scope:'menus', position:'end', limit: 3}});
		}
		else{
			toggleDisp('tabContent'+num);
		}
	}
}

function getActiveTabName() {
	if ( $('tabHeaderActive') ) {
		return $('tabHeaderActive').childElements()[0].childElements()[0].innerHTML;
	}
	else return "Error"
}

/* Toggles panels open or closed accordion-style */
function accordionToggle(control, target) {
	if ( $(target).visible() ) {
		new Effect.BlindUp($(target), {duration : 0.5});
	}
	else {
		new Effect.BlindDown($(target), {duration : 0.5});
	}
	$(control).toggleClassName("expanded");
	$(control).toggleClassName("collapsed");
}

	
var lastselectopt = '';	//initialize to empty
function selectRow(id){
	// used in exercise.cfm
	if (lastselectopt != '') $(lastselectopt).parentNode.parentNode.style.backgroundColor = 'transparent';
	$(id).parentNode.parentNode.style.backgroundColor = '#E7F7F5';
	$(id).blur();
	lastselectopt = id;
}

function submitit(){
	// used in exercise.cfm, exercise_intro.cfm, exercise_profile.cfm, invite.cfm, signin.cfm, signup.cfm
	$('submitbtn').style.display='none';
	$('ajaxloader').style.display='block';
	return true;
}

function imageScaleToFit(img,width,height){
	// used in albums_view.cfm, goals_action.cfm and sveral other pages
	widthdiff = 0;
	heightdiff = 0;
	percentage = 1;
	if (width != ''){
		widthdiff = img.width - width; // (75 - 70) 5
	}
	if (height != ''){
		heightdiff = img.height - height; // (50 - 70) -20
	}
	if (widthdiff > heightdiff && widthdiff > 0){// resize based on width
		percentage = width/img.width;
	} else if (heightdiff > 0) { // resize based on height
		percentage = height/img.height;
	}
	if (percentage < 1){ // resizing needed
		newheight = Math.round(img.height * percentage);
		newwidth = Math.round(img.width * percentage);
		// alert(newwidth + 'x' + newheight + '(' + percentage + ')');
		img.style.height = newheight+'px';
		img.style.width = newwidth+'px';
	}
}

function decrementCounter(e) {
	// gets the numeric value of an element and decrements by one to min of 0
	var n = parseInt($(e).innerHTML);
	if ( ! isNaN(n) ) {
		n = Math.max(--n, 0);
		$(e).update(n);
	}
	return e;
}

function incrementCounter(e) {
	// gets the numeric value of an element and increments by one 
	var n = parseInt($(e).innerHTML);
	if ( ! isNaN(n) ) $(e).update(++n);
	return e;
}


/*=============================================================================
SIGN-IN SCRIPT
==============================================================================*/
function doSignin() {
	var form = $('signin_form'); 
	var msg = ""
	$("signin_button").hide();
	$("signin_working").show();
	$('signin_messagebox').update('');
	if ($F('email_signin').empty()) { msg = "Please enter your email address.<br>"; }
	else if ( ! isValidEmail($F('email_signin')) ) { msg += "&quot;" +$F('email_signin' )+ "&quot; is not a valid email.<br>";  }
	if ($F('password_signin').empty()) { msg += "Please enter a password.<br>"; }
	if (msg.length > 0) {
		$('signin_messagebox').update(msg);
		$("signin_working").hide();
		$("signin_button").show();
	}
	else {
		form.request(
			{
			onSuccess: function (transport) {
				var r = transport.responseText.strip();
				// returns 0 (failure) or 1 (success)
				if (r == 0) { 
					$('signin_messagebox').update("Sorry, email or password was not recognized.");
					$("signin_working").hide();
					$("signin_button").show();
				}

				else window.location= "members/index.cfm";
 			},	/* ...onSuccess */
				
			onFailure: function () {
    		$('signin_messagebox').update("Sorry - there was a problem connecting to the2ofyou.com. Please try again in a moment.");
				$("signin_working").hide();
				$("signin_button").show();
			}	/* ...onFailure */
		});	/* ...form.request */
	}	/* if (msg.length > 0) */
}	/* ...doSignin() */


/*=============================================================================
AJAX FORM-RELATED FUNCTIONS
==============================================================================*/
function popUnderForm(formDiv, targetDiv, url) {
if (formDiv == undefined) { 
			Element.update($('clipboard'), targetDiv.innerHTML);
			new Ajax.Updater({ success: targetDiv, failure: targetDiv }, url, {
		  method: 'get',
			insertion: 'bottom',
			evalScripts: true
		});	
	};
}

function popinForm(formDiv, targetDiv, url) {
	if (formDiv == undefined) {
			Element.update($('clipboard'), targetDiv.innerHTML);
			new Ajax.Updater({ success: targetDiv, failure: targetDiv }, url, {
		  method: 'get',
			evalScripts: true
		});
	};
}

submitPopinForm = function(actionPage, formId, formContainerId, resultContainerId, resultId) {
	new Ajax.Request(actionPage, {
	  method: 'post',
		parameters: $(formId).serialize(true),
		onSuccess: function(transport){
			var r = transport.responseText.strip() || 0;
			var s = r.charAt(0); // first character is 0 (failure) or 1 (success)
			r = r.sub(/[0-1]/, '', 1); // strip first character
			if (s == 0) {
				// show error msg
				$("popInMessagebox").addClassName('errmsg');
				$("popInMessagebox").update(r);
			}
			else {
				// hide popin form
				new Effect.BlindUp(formContainerId, { duration : 0.2} );
				setTimeout("submitPopinForm_step2()", 250);
				
				// clear contents of form div, reveal result of form action
				submitPopinForm_step2 = function() {
					Element.update(formContainerId, '');
					$(resultContainerId).insert({'top': r});
					new Effect.BlindDown($(resultContainerId).down().id, {duration : 0.2});
					new Effect.Highlight($(resultContainerId).down().id, {duration : 1.5});							
				}	// submitPopinForm_step2
			}	// else (s != 0) -- i.e. success
		},// onSuccess
		onFailure: function(){ alert('Something went wrong...') }
	});	// new Ajax.Request
};	// submitPopinForm

cancelPopInForm = function(divToHide, divToRemove) {
	var str = "cancelPopInForm2('" + $(divToRemove).id + "');";
	Effect.BlindUp(divToHide, { duration : 0.2} );
	setTimeout(str, 250);
}

cancelPopInForm2 = function(divToRemove) {
	Element.remove(divToRemove);
	$('clipboard').innerHTML = "";
}

/*-----------------------------------------------------------
RESPONDING TO EXERCISES / QUESTIONS 
---------------------------------------------------------*/
qResponseSubmit = function(formID) {
	var btnID = "subBtn"+formID;
	if ( $(btnID) )
		$(btnID).replace('<img src="../images/ajax-loader.gif" alt="...processing..." class="ajaxloader">');
	return true;
}

qContinue = function(btn) {
	// on click of continue button, reveals next element, hides continue button
	var myDiv = $(btn).ancestors()[0].nextSiblings()[0];
	$(btn).hide();
	Effect.BlindDown(myDiv, {duration:0.4});
}

sliderWidget = function(id, leftVal, rightVal, startVal) {
  new Control.Slider($(id).down('.handle'), $(id), {
    range: $R(leftVal,rightVal),
    sliderValue: startVal ,
    onSlide: function(value) {
		$(id).down('.slider_value').value=Math.round(value);
    }
  });
};

/*-----------------------------------------------------------
GOAL EDITING 
---------------------------------------------------------*/
goalEditSubmit = function() {
	Element.replace('goalEditFormButtons', '<img src="../images/ajax-loader_24px.gif" alt="...processing..." class="ajaxloader" id="goalEditFormSpinner">');
}

goalEditCancel = function(formDiv, targetDiv, restorePrev) {
	var str = "goalEditCancel2('" + $(formDiv).id + "', '" + $(targetDiv).id + "', " + restorePrev + ");";
	Effect.BlindUp('goalEditForm', { duration : 0.2} );
	setTimeout(str, 250);
}

goalEditCancel2 = function(formDiv, targetDiv, restorePrev) {
	Element.remove(formDiv);
	if (restorePrev == true)  {
		$(targetDiv).innerHTML = $('clipboard').innerHTML;
		$('clipboard').innerHTML = "";
	}
}


showMoreActivities = function(lastAssignmentRecordID, lastActivityRecordID) {
	Element.replace('moreActivitiesButton', '<img src="../images/spin.gif" alt="...processing..." class="spinner" id="moreActivitiesSpinner">');
	new Ajax.Updater({ success: 'activityList' }, 'activity_list_more.cfm', {
		method: 'get',
	  parameters: { nasm : lastAssignmentRecordID, nact : lastActivityRecordID},
		insertion: 'bottom',
		onComplete: showMoreActivitiesCleanup()
	});
}

showMoreActivitiesCleanup = function() {
	Element.remove('moreActivitiesControl');
	/*fb.anchors.length = 0;
  fb.tagAnchors(document);*/
}

/*-----------------------------------------------------------
FORM FIELD VALIDATIONS 
---------------------------------------------------------*/
function isValidEmail(str) {
	var rx = new RegExp("^([0-9a-zA-Z]+[-._+&amp;])*[0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$");
	return str.match(rx);
}

/*-----------------------------------------------------------
ACTIONS 
---------------------------------------------------------*/

//re-send partner invitaiton email
function resendInvitation(id) {
	alert("Re-sending invitations coming soon. Invitation ID = " + id);
	return;
}
