/*******************************************************************************
* Project: StuffSpace 1.0                                                      *
* File: stuff.js (Javascript File for stuffspace)                              *
* Author: Cody Garvin                                                          *
*                                                                              *
********************************************************************************
* Date: 10/20/05                                                               *
* Version: 0.1                                                                 *
* History:                                                                     *
*  10/20/05 - Initial script created.                                          *
*                                                                              *		
*******************************************************************************/
/* Stufflist index page that shows stufflists and "Stuff I love" as default */


function refresh()
{
	//  This version of the refresh function will be invoked
	//  for browsers that support JavaScript version 1.2
	//
	
	//  The argument to the location.reload function determines
	//  if the browser should retrieve the document from the
	//  web-server.  In our example all we need to do is cause
	//  the JavaScript block in the document body to be
	//  re-evaluated.  If we needed to pull the document from
	//  the web-server again (such as where the document contents
	//  change dynamically) we would pass the argument as 'true'.
	//  
	
	parent.location.reload( false );
}

function checkAccountForm()
{
		if (document.account.firstname.value == "")
		{
			alert("The First Name field is blank, Please fill it in.");
			document.account.firstname.focus();
			return false;
		}
		
		if (document.account.username.value == "")
		{
			alert("The Username field is blank, Please fill it in.");
			document.account.username.focus();
			return false;
		}
		
		if ((document.account.pass.value == "") || (document.account.pass2.value == ""))
		{
			alert("Your password field is blank, Please fill it in.");
			document.account.pass.focus();
			return false;
		}
		
		if (document.account.pass.value != document.account.pass2.value)
		{
			alert("Your password fields do not match, Please re-type them.");
			document.account.pass.focus();
			return false;
		}
		
		if (document.account.email.value == "")
		{
			alert("The Email field is blank, Please fill it in.");
			document.account.pass.focus();
			return false;
		}
		
		if (!isEmailAddress(document.account.email.value))
		{
			alert("Your email is not a valid format, Please re-type it.");
			document.account.pass.focus();
			return false;
		}
		
		if ((document.account.month.value == "0") || (document.account.day.value == "0") || (document.account.year.value == "0"))
		{
			alert("You have not selected a proper birthdate, Please select the proper month, day, and year.");
			return false;
		}
		
		/*if (document.account.zip.value == "")
		{
			alert("You have not entered a zip code, Please fill it in.");
			document.account.zip.focus();
			return false;
		}*/
		
		if (!document.account.tos.checked)
		{
			alert("You did not check the Terms of Service agreement. You must agree to the Terms of Service and Privacy Policy to create an account.");			
			return false;
		}
		
		// Made it through the jungle of if statements
		return true;
}

////////////////////////////////////////////////////////
// Test Email Format Validity
function isEmailAddress(emailAddress)
{
	return emailAddress.match(/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/);
}
	
////////////////////////////////////////////////////////
// Rating Star Functions

// Set up the stars
var starHalves = 10;
var count = 0;
var starArray = new Object;
var emptyStar = new Object;
var textArray = new Object;
var filledStar = 0;
var timeoutID  = 0;

function setStars(star)
{
	if(!(star >= 5) && !(star <= 50))
	{
		star = 5;
	}
	
	while(count < starHalves)
	{
		var tempNum = count + 2;
		var textNum = count + 1;
		starArray[count] = new Image();
		starArray[count].src = "../stars/images/stars_r2_c"+ tempNum +"_f2.gif";
		emptyStar[count] = new Image();
		emptyStar[count].src = "../stars/images/stars_r2_c"+ tempNum +".gif";
		textArray[count] = new Image();
		textArray[count].src = "../stars/images/stars_r1_c1_f"+textNum+".gif";
		
		count++;
	}
	
	filledStar = star;
}


// Fill the stars from first to "star"
function fillStars(star)
{
	var starNum = star;
	var count;	
		
	if((starNum % 10) == 0)
	{
		count = 9;
	}
	else
	{
		count = 8;
	}
	
	clearStars(); // Clear them before write so fill works correctly
	
	displayTitle(starNum); // Show the text for that star
	
	while(starNum >= 10)
	{		
		var starID = document.getElementById('star_' + starNum);
		starID.src = starArray[count].src;
		
		starNum = starNum - 5;
		count--;
	}
}

// Reset Stars on MouseOut using timer
function resetTheStars()
{
		
	// Clear the timeout so the rollovers will work
	clearTimeout(timeoutID);
	
	//alert(filledStar);
	// Set timeout until the filled stars are shown
	if(filledStar != 0)
	{
		timeoutID = setTimeout('fillClickedStar();', 2000);
	}
}

// Clear the stars
function clearStars()
{
	var maxStars = 50;
	var count    = 9;
	
	while(maxStars >= 10)
	{
		var sID = document.getElementById('star_' + maxStars);
		sID.src = emptyStar[count].src;
		
		maxStars = maxStars - 5;
		count--;
	}
}

// Check filled star
function checkClicked()
{
	if(filledStar != "")
	{
		fillClickedStar();
	}
}

// Displays the Title of the star
function displayTitle(starNum)
{
//	alert(starNum);
	var header = document.getElementById('star_head');
	switch(starNum)
	{
		case 50:
			header.src = textArray[9].src;
			break;
		case 45:
			header.src = textArray[8].src;		
			break;
		case 40:
			header.src = textArray[7].src;
			break;	
		case 35:
			header.src = textArray[6].src;
			break;
		case 30:
			header.src = textArray[5].src;		
			break;
		case 25:
			header.src = textArray[4].src;		
			break;
		case 20:
			header.src = textArray[3].src;		
			break;
		case 15:
			header.src = textArray[2].src;
			break;			
		case 10:
			header.src = textArray[1].src;
			break;
		default:
			header.src = "../stars/images/stars_r1_c1_f1.gif";
	}
}

// Saves a clicked star and displays the stars
function clickStar(starNum)
{
	filledStar = starNum;
	document.writeform.rate.value = starNum;
	fillClickedStar();
}

// Fills the stars up to the clicked star
function fillClickedStar()
{
	var tempStar = filledStar;
	var count;	
	
	//alert("heh");
		
	if((tempStar % 10) == 0)
	{
		count = 9;
	}
	else
	{
		count = 8;
	}
	
	clearStars(); // Clear them before write so fill works correctly
	
	displayTitle(tempStar); // Show the text for that star
	
	while(tempStar >= 10)
	{		
		var starID = document.getElementById('star_' + tempStar);
		starID.src = starArray[count].src;
		
		tempStar = tempStar - 5;
		//alert(starNum);
		count--;
	}
}

// Load the images upon page load
function preloadImages() 
{
	var d = document; 
 	if(d.images)
 	{ 
 		if(!d.storage) 
 			d.storage = new Array();
 	
   		var i, j = d.storage.length, a = preloadImages.arguments; 
   	
   		for(i = 0; i < a.length; i++)
	   	{
   			if (a[i].indexOf("#") != 0)
	   		{ 
   				d.storage[j] = new Image; 
   				d.storage[j++].src = a[i];
   			}
   		}
 	}
}

/////////////////////////////////////////////////////////////////////////////
// Functions for messaging
// Sets the action for the form
function setAction(target)
{
	if(target == 'reply')
	{
		document.mailform.action="replymessage.php";
		document.mailform.submit();
	}
	else if(target == 'delete')
	{
		document.mailform.action="deletemessage.php";
	}
	else if(target == 'trash')
	{
		document.mailform.action="movemessages.php";
		document.mailform.mailbox.value="trashbox";
	}
	else if(target == 'abox')
	{
		document.mailform.action="movemessages.php";
		document.mailform.mailbox.value="abox";
	}
	else if(target == 'compose')
	{
		document.mailform.action="compose.php";
	}
	
	if(target == 'compose')
		document.mailform.submit();
	else if(document.mailform.killmessage.value != "")
		document.mailform.submit();
	else
		alert("Sorry, you must first select a message");
}

// Sets the ids to be deleted
function addID(id)
{
	var totalboxes = document.mailform.messagecount.value;
	var boxes = "";

	if(totalboxes > 1)
	{
		for(var count = 0; count < totalboxes; count++)
		{
			if(document.mailform.message[count] != undefined)
			{
				//if a box is check add it to checked boxes
				if(document.mailform.message[count].checked)
				{
					boxes = boxes+document.mailform.message[count].value+"|";
				}
			}
		}
	}
	else
	{
		if(document.mailform.message.checked)
			boxes = boxes+document.mailform.message.value+"|";
	}
	document.mailform.killmessage.value = boxes;
}

/////////////////////////////////////////////////////////////////////////////
// Selects all the messages
function checkAllMessages()
{	
	var totalboxes = document.mailform.messagecount.value;

	if(document.mailform.checkall.checked)
	{
		for( var count = 0; count < totalboxes; count++)
		{
			//if a box is check add it to checked boxes
			document.mailform.message[count].checked = true;
		}
		
		addID();
	}
	else
	{
		for( var count = 0; count < totalboxes; count++)
		{
			//if a box is check add it to checked boxes
			document.mailform.message[count].checked = false;
		}
		
		document.mailform.killmessage.value = "";
	}
}


/////////////////////////////////////////////////////////////////////////////
// Toggles an element to show or hide
function toggle( targetId )
{ 
	if (document.getElementById)
	{ 
    	target = document.getElementById( targetId ); 
        
        if (target.style.display == "none")
        { 
        	target.style.display = ""; 
        } 
        else 
        { 
        	target.style.display = "none"; 
        } 
	} 
}

/////////////////////////////////////////////////////////////////////////////
// Toggles Show or Hide for the tour navigation
function toggleTour( targetId )
{ 
	var itemsArray = new Array(8);
	itemsArray[0] = 'Welcomeid';
	itemsArray[1] = 'StuffPageid';
	itemsArray[2] = 'Reviewsid';
	itemsArray[3] = 'Blogsid';
	itemsArray[4] = 'Communityid';
	itemsArray[5] = 'Watchlistsid';
	itemsArray[6] = 'StuffBucksid';
	itemsArray[7] = 'Collectionsid';
	
	if (document.getElementById)
	{
		for(var count = 0; count < 8; count++)
		{
	    	target = document.getElementById( itemsArray[count] ); 
		
			if(itemsArray[count] == targetId)
			{
				if (target.style.display == "none")
				{ 
					target.style.display = ""; 
				} 
				else 
				{ 
					target.style.display = "none"; 
				} 				
			}
			else
			{
				target.style.display = "none";				
			}
		}
	} 
}


/////////////////////////////////////////////////////////////////////////////
// Toggles on and off the cards
function toggleCards( targetId )
{ 
	if (document.getElementById)
	{ 
    	target = document.getElementById( targetId ); 
        
        if (target.style.display == "none")
        { 
        	target.style.display = ""; 
        } 
        else 
        { 
        	target.style.display = "none"; 
        } 
	} 
}


/////////////////////////////////////////////////////////////////////////////
// Functions for blogging and forums
// Adds an image to the textarea
function addImage(imageId)
{
	var image = imageId;
	var blog = tinyMCE.activeEditor.getContent();
	
	tinyMCE.activeEditor.setContent(blog+" [img]"+image+"[/img] ");
	document.writeform.textpost.focus();			
}

// Adds an image to the textarea
function addForumImage(imageId)
{
	var image = imageId;
	//var blog  = parent.document.writeform.textpost.value;
	var blog  = parent.tinyMCE.activeEditor.getContent();
	
    	//tinyMCE.activeEditor.setContent("yay"); 
	//parent.document.writeform.textpost.value = blog+" [img]"+image+"[/img] ";
	parent.tinyMCE.activeEditor.setContent(blog+" [img]"+image+"[/img] ");
	
	parent.document.writeform.textpost.focus();			
}

// Adds a bold link to the text area
function addBold()
{
	var blog = document.writeform.textpost.value;
	var adv  = document.writeform.advanced.value;
	
	if(adv != "")
	{
		document.writeform.textpost.value = blog+" [b]"+adv+"[/b] ";
		document.writeform.textpost.focus();
		document.writeform.advanced.value = "";
	}
	else
	{
		document.writeform.textpost.value = blog+" [b]ENTER TEXT HERE[/b] ";
		document.writeform.textpost.focus();
	}
}

// Adds an italic link to the text area
function addItalic()
{
	var blog = document.writeform.textpost.value;
	var adv  = document.writeform.advanced.value;
	
	if(adv != "")
	{
		document.writeform.textpost.value = blog+" [i]"+adv+"[/i] ";
		document.writeform.textpost.focus();
		document.writeform.advanced.value = "";
	}
	else
	{
		document.writeform.textpost.value = blog+" [i]ENTER TEXT HERE[/i] ";
		document.writeform.textpost.focus();
	}
}

//
// For forum posting only.... saves the old blog
function setPostValue()
{
	var blog  = tinyMCE.activeEditor.getContent();
	if(document.writeform.topic != null)
		document.addimage.oldtopic.value = document.writeform.topic.value;
	document.addimage.oldpost.value = blog;
	document.addimage.submit();
}

// Adds an underline link to the text area
function addUnderline()
{
	var blog = document.writeform.textpost.value;
	var adv  = document.writeform.advanced.value;

	if(adv != "")
	{
		document.writeform.textpost.value = blog+" [u]"+adv+"[/u] ";
		document.writeform.textpost.focus();
		document.writeform.advanced.value = "";
	}
	else
	{
		document.writeform.textpost.value = blog+" [u]ENTER TEXT HERE[/u] ";
		document.writeform.textpost.focus();
	}
}

///////////////////////////////////////////////////////////////////
// Focuses on the first form field if text or text area or select
function formFocus(formNum, offset) 
{
	if(formNum == null)
	{
		formNum = 0;
	}
	
	if(offset == null)
	{
		offset = 0;
	}
		
	if (document.forms.length > 0) 
	{
		var field = document.forms[formNum];
		if(field != null)
		{
			for (count = 0; count < field.length; count++) 
			{
				if ((field.elements[count].type == "text") || (field.elements[count].type == "textarea") || (field.elements[count].type.toString().charAt(0) == "s")) 
				{
					document.forms[formNum].elements[count+offset].focus();
					break;
				}
			}
		}
   	}
}


function selectAll()
{
	var totalboxes = window.sortframe.document.sort.length;

	if(document.sortform.checkall.checked)
	{
		for( var count = 0; count < totalboxes; count++)
		{
			//if a box is check add it to checked boxes
			window.sortframe.document.sort.elements[count].checked = true;
			var theName = window.sortframe.document.sort.elements[count].name;
			var theValue = window.sortframe.document.sort.elements[count].value;			
			document.sortform.elements[theName].value = theValue;
		}
	}
	else
	{
		for( var count = 0; count < totalboxes; count++)
		{
			//if a box is check add it to checked boxes
			window.sortframe.document.sort.elements[count].checked = false;
			var theName = window.sortframe.document.sort.elements[count].name;
			document.sortform.elements[theName].value = 0;
		}
	}
}

///////////////////////////////////////////////////////////////////
function selectAllLink(choice)
{
	var totalboxes = window.sortframe.document.sort.length;

	if(choice == 'all')
	{
		for( var count = 0; count < totalboxes; count++)
		{
			//if a box is check add it to checked boxes
			window.sortframe.document.sort.elements[count].checked = true;
			var theName = window.sortframe.document.sort.elements[count].name;
			var theValue = window.sortframe.document.sort.elements[count].value;			
			document.sortform.elements[theName].value = theValue;
		}
	}
	else
	{
		for( var count = 0; count < totalboxes; count++)
		{
			//if a box is check add it to checked boxes
			window.sortframe.document.sort.elements[count].checked = false;
			var theName = window.sortframe.document.sort.elements[count].name;
			document.sortform.elements[theName].value = 0;
		}
	}
}


///////////////////////////////////////////////////////////////////
// Outputs the code needed for a user's badge
function getBadgeCode(badgeNum, usercode)
{
	document.badgeform.codearea.value = "<a href=\"http://www.stuffspace.com/user/index.php?id="+usercode+"__view_1\"><img src=\"http://www.stuffspace.com/user/imageLink.php?id="+usercode+"__style_"+badgeNum+"\" border=\"0\"></a>";
}

///////////////////////////////////////////////////////////////////
// Outputs the code needed for a user's badge
function getBadgeCode2(badgeNum, usercode)
{
	document.badgeform.codearea.value = "<a href=\"http://www.stuffspace.com/user/index.php?id="+usercode+"__view_1\"><img src=\"http://www.stuffspace.com/images/ssbadgebutton"+badgeNum+".png\" border=\"0\"></a>";
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// Generic function to process forms
function processForm()
{
	document.saveForm.submit();
}

////////////////////////////////////////////////////////////////////////////////////////////////////
// Build a basic error handler
function ajaxError(data, ioArgs) 
{
	//alert('Error when retrieving data from the server!');
	return false;
}	

////////////////////////////////////////////////////////////////////////////////////////////////////
// Count down function
function countdown(elementString, dateString, mode, name) 
{ 
	if (mode == null) mode = 0;
	if (name == null) name = '0';
	var clock = document.getElementById(elementString);
	var eventdate = new Date(dateString); // in format "January 1, 2005 00:00:00 GMT"
	now = new Date();
	nowtime = now.getTime(); // now in milliseconds
	eventtime = eventdate.getTime(); // event in milliseconds
		
	var eventhour = eventdate.getHours();
	var eventminute = eventdate.getMinutes();
	var eventsecond = eventdate.getSeconds();
	var eventmonth = eventdate.getMonth()+1;
	var eventday = eventdate.getDate();
	var eventyear = eventdate.getFullYear();

	timeleft = Math.round((eventtime-nowtime) / 1000); // timeleft in seconds
	
	var passed = 0;
	if (timeleft < 0) 
	{ 
		// if event has passed
		timeleft = Math.abs(timeleft);
		passed = 1;
	}
	
	if (timeleft != 0) 
	{
		// Let's get a whole bunch of values
		years = Math.floor(timeleft/31556926);
		months = Math.floor((timeleft%31556926)/2629744);
		days = Math.floor(((timeleft%31556926)%2629744)/86400);
		hours = Math.floor((((timeleft%31556926)%2629744)%86400)/3600);
		minutes = Math.floor(((((timeleft%31556926)%2629744)%86400)%3600)/60);
		seconds = Math.floor(((((timeleft%31556926)%2629744)%86400)%3600)%60);
	}
	
	// Now lets build a response to print
	var togo = ''; // set up our variable
	
	if (mode == 0) 
	{
		togo += 'Time ';
		if (passed != 1) {
			togo += 'until ';
		} else {
			togo += 'since ';
		}
	}
	
	if ((mode != 2) && (mode != 3)) {
		togo += '<strong>';
		if (name != '0') togo += name + ' - ';
		if ((eventhour + eventminute + eventsecond) != 0) {
			togo += eventhour + ':' + eventminute;
			if (eventsecond != 0) togo += ':' + eventsecond;
			togo += ' on ';
		}
		togo += eventmonth + '/' + eventday;
		if (eventyear != now.getFullYear()) togo += '/' + eventyear;
		togo += '</strong>: ';
	}
	togo="";
	if (timeleft != 0) {
		if (years > 0) {
			togo += years + ' year';
			if (years > 1) togo += 's';
			if (months > 0) togo += ',';
			if ((minutes!=0)||(seconds!=0)||(hours!=0)||(days!=0)||(months!=0)) togo += ' ';
		}
		
		if (months > 0) {
			togo += months + ' month';
			if (months > 1) togo += 's';
			if (days > 0) togo += ',';
			if ((minutes!=0)||(seconds!=0)||(hours!=0)||(days!=0)) togo += ' ';
		}
		
		if (days > 0) {
			togo += days + ' day';
			if (days > 1) togo += 's';
			if (hours > 0) togo += ',';
			if ((minutes!=0)||(seconds!=0)||(hours!=0)) togo += ' ';
		}
		
		if (hours > 0) {
			togo += hours + ' hour';
			if (hours > 1) togo += 's';
			if (minutes > 0) togo += ',';
			if ((minutes!=0)||(seconds!=0)) togo += ' ';
		}
		
		if (minutes > 0) {
			togo += minutes + ' minute';
			if (minutes > 1) togo += 's';
			if (seconds > 0) togo += ',';
			if (seconds != 0) togo += ' ';
		}
		
		if (seconds > 0) {
			togo += seconds + ' second';
			if (seconds > 1) togo += 's';
		}
		
		var expld = togo.split(', ');
		
		var exlast = expld.length-1;
		var todo = '';
		var i;
		
		for (i=0 ; i<expld.length ; i++) {
			value = expld[i];
			todo += value;
			if ((i != exlast) && (expld.length!=2)) todo += ' ';
			if ((expld.length == 2) && (i != exlast)) todo += ' ';
			if ((i == exlast) && (passed == 1)) todo += ' ago';
		}
	} else {
		var todo = togo + ' Now!';
	}
	
	// Now lets print it
	clock.innerHTML = todo;
	
	setTimeout('countdown(\'' + elementString + '\', \'' + dateString + '\', ' + mode + ', "' + name + '");', 1000); // re-execute the function in 1 second
}