

//first, initialize global variables
var auth_token;
var seals_username;
var req;


//items to take care of during / after loading


Event.observe(window, "load", function() {
	Pager.init();
	Load.init();
});


//Pager class
//provides interface to login / authentication when paging

var Pager = {


	
	//add login window to href elements that have class pager
	init: function()
	{
		
		$$("a.pager-first", "a.pager-last", "a.pager-next", "a.pager-previous", "tertiary-links", "a.res").each(function (el){
			
			Event.observe(el, 'click',Pager.bind.bindAsEventListener());
		
		});

	},
	
	//mangles a query string, so it can be passed around inside another querystring
	//(call me insane)
	link_mangle: function(link)
	{
		link = link.replace("=", "||");
		link = link.replace("?", "~~");
		link = link.replace("&", "^^");
		return link;
	},
	
	
	//unmangles a query string, that was mangled by link_mangle, so it can be used as a URI
	//(call me insane)
	link_unmangle: function(link)
	{
		link = link.replace("||", "=");
		link = link.replace("~~", "?");
		link = link.replace("^^", "&");
		return link;
	},
	
	
	//binds event to all pager links, if we are not logged in
	bind: function(e)
	{
		e.preventDefault();
		new Ajax.Request("/server.php?c=sealsuser&m=is_logged_in", {
	  		onSuccess: function(transport) {
	  			
	  			var el = Event.element(e);
	  			
	  			if(transport.responseText.indexOf("true") == "-1")
	  			{
	  				
		
					//var tag = Event.element(e).tagName.toLowerCase();
					
					if(el)
					{
						var link = Pager.link_mangle(el.href);
						Pager.click_greybox(link);
					}
			  		
	  
	  			}
	  			else
	  			{
	  				
	  				window.location = el.href;
	  			}
	  		}
	  	});
	  	
	},
	
	
	
	
	//handles clicking on a greybox link
	click_greybox: function(dest)
	{
		
			/*alert("test");
			event.preventDefault();*/
			if(dest)
			{
				var link = "/login-box.php?s=box&goto=" + dest;
			}
			else
			{
				var link = "/login-box.php";
			}
	
			GB_showCenter("Log In", link, 380, 380);
		
	}

}



//loads page elements
var Load = {

	//initializes page by loading required elements via AJAX call
	init: function()
	{

		//first, process breaking news area
		//check if rendering area is available and render element
		el_id = "breaking_news_render_area";
		if($(el_id))
		{
			Load.breaking_news(el_id);
		}
		
		
		//then, process what's new area
		el_id = "whatsnew_render_area";
		if($(el_id))
		{
			Load.whatsnew(el_id);
		}
		
		//initializes drop-down menu bar
		Load.menu();
		
	},
	
	
	//remotely fetches the breaking news / seals news section and loads it into a container div
	breaking_news: function(el_id)
	{
		var url = "/seals/remotes/render.php?e=breakingnews";
		new Ajax.Updater(el_id, url, { evalScripts: true });
	},
	
	//remotely fetches the what's new section and loads it into a container div
	whatsnew: function()
	{
		var url = "/seals/remotes/render.php?e=whatsnew";
		new Ajax.Updater("whatsnew_render_area", url, { evalScripts: true });
	},
	
	//initializes drop-down menu bar
	menu: function()
	{
		$$("li.droppable").each(function (el){
		
			Event.observe(el, 'mouseover',Load.drop_menu.bindAsEventListener());
			Event.observe(el, 'mouseout',Load.hide_menu.bindAsEventListener());
			
		});
		
		$$("div.menuslider").each(function (el){
	
			Event.observe(el, 'mouseout',Load.hide_slider.bindAsEventListener());
		
		});
		
	},
	
	
	
	//makes the menu item show / hide slider on mouse event
	drop_menu: function(e)
	{
		
		var from = e.relatedTarget || e.fromElement;
		
		var el = Event.element(e);
		var li_element = el.up("li");
		//alert("el id = " + li_element.id);
		
		var slider = $(li_element.id + "_s");
		var wrapper = $(li_element.id + "_w");

		var arr_offset = Element.cumulativeOffset(el);
		var eh = Element.getHeight(el);
		//alert("length: " + arr_offset.length + "offset: " + arr_offset[1]);
		var lo = arr_offset[0];
		var to = arr_offset[1] + eh;
		
		if(($(wrapper).getStyle("top") == "0px") && ($(wrapper).getStyle("left") == "0px"))
		{
			$(wrapper).setStyle({
		  		left: lo + 'px',
		  		top: to + 'px'
			});
		}
		//slider.style.left = arr_offset[0];
		//slider.style.top = arr_offset[1];
	//	Event.observe(slider, "mouseout", function (el) {
	//		new Effect.BlindUp(slider);
	//	});
		if(from && from.id.indexOf("undefined") == "-1")
		{
			if(!(from.hasClassName("menuslider")))
			{
				Load.slide_down(slider);
				//new Effect.BlindDown(slider, { queue: {position: 'end', scope: slider.id}});
			}
		}
		else
		{
			Load.slide_down(slider);
		}
		
			
		
		//alert(slider.id);
		
		
	},
	
	
	//hides menu slider on mouse event
	hide_menu: function(e)
	{
		var from = e.relatedTarget || e.fromElement;
		var to = e.relatedTarget || e.toElement;
	
		
		var el = Event.element(e);
		var li_element = el.up("li");
		
		
		
		var slider = $(li_element.id + "_s");
		
	
		if(to && to.id.indexOf("undefined") == "-1")
		{
			if(!(to.hasClassName("menuslider")))
			{
				
				Load.slide_up(slider);
			}
		}
		else
		{
			Load.slide_up(slider);
		}
			
		
	},
	
	
	//hides menu slider on mouse event (for event on slider only)
	hide_slider: function(e)
	{
		
		var from = e.relatedTarget || e.fromElement;
		var to = e.relatedTarget || e.toElement;
		
		var el = Event.element(e);
		var slider = el.up("div").up("div");
		
		if(to && to.id.indexOf("undefined") == "-1")
		{
			if( (!(to.hasClassName("droppable"))) && (to.tagName != "A") )
			{
				Load.slide_up(slider);
	
			}
		}
		else
		{
			Load.slide_up(slider);
		}
	},
	
	
	//slides slider down with scriptaculous effect
	slide_down: function(slider)
	{
	
		if(slider && slider.id.indexOf("undefined") == "-1")
		{
			new Effect.BlindDown(slider, { duration: 0.3, queue: {position: 'end', scope: slider.id}});
		}
		
	},
	
	//slides slider up with scriptaculous effect
	slide_up: function(slider)
	{
		if(slider && slider.id.indexOf("undefined") == "-1")
		{
			new Effect.BlindUp(slider, { duration: 0.3, queue: {position: 'end', scope: slider.id}});
		}
		
	}
	


}



var user_callback = 
{
    // after a review we get a chunk of html that we can update the reviewList with
   process_registration: function(result) 
	{
		

		if(result.indexOf("error") != -1) //errors were encountered during registration
		{
			update_login_status(result);
		}
		else if(result.indexOf("success") != -1) //registration was successful
		{
			grow_smoothbox();
			var arr_result = result.split("|");
			added_new_user(arr_result[1]);
			go_next();
			//grow_smoothbox();
		}
		
		grow_smoothbox();
    },
	check_pass: function(result)
	{
		if(result == true)
		{
			show("chpw_new1");
			show("chpw_new2");
			show("change_password_button");
			hide("chpw_current");
			document.getElementById("chpw_new1").focus();
			update_password_status("<span>Correct.</span> Enter your new password:");
		}
		else
		{
			hide("chpw_new1");
			hide("chpw_new2");
			hide("change_password_button");
			update_password_status("Incorrect Password. Please try again:");
			document.getElementById("chpw_current").focus();
		}
		
		grow_smoothbox();
	},

	exists: function(result)
	{
		if(result == true)
		{
			var sun = document.getElementById("seals_login").value;
			//update_login_status("Welcome back, " + sun + ".<br><br><button class = \"sealsbutton\" id = \"continue_login_button\" onclick = \"continue_login()\" >Log In</button> <button class = \"sealsbutton\" id = \"cancel_login_button\" onclick = \"cancel_login()\" >Cancel</button><br><br>Click Log In to log in as " + sun + ",<br> or Cancel if you are not " + sun + ".");
			//show_spw_field();
			//hide_signup_form();
			//hide_login_button();
			continue_login();
			grow_smoothbox();
		}
		else
		{
			var sun = document.getElementById("seals_login").value;
			update_login_status("Please fill out the fields below to register a new account:.");
			update_login_prompt("Username " + sun + " is available!");
			// document.getElementById("login_prompt").style.color = "green";
			show_signup_form();
			hide_login_button();
			grow_smoothbox();
		}
		//else
		//{
		//	update_login_status("ERROR: Login is currently not available. Please contact customer service.");
		//}
		
		preload_images();
		grow_smoothbox();

	},
	
	email_exists: function(result)
	{
		if(result == true)
		{
			
			update_password_status("Please stand by while we process your request...");

			lost_password();
			//update_login_status("Welcome back, " + sun + ".<br><br><button class = \"sealsbutton\" id = \"continue_login_button\" onclick = \"continue_login()\" >Log In</button> <button class = \"sealsbutton\" id = \"cancel_login_button\" onclick = \"cancel_login()\" >Cancel</button><br><br>Click Log In to log in as " + sun + ",<br> or Cancel if you are not " + sun + ".");
			//show_spw_field();
			//hide_signup_form();
			//hide_login_button();
			//continue_login();
			//grow_smoothbox();
		}
		else
		{
			
			//var sun = document.getElementById("chpw_new1").value;
			update_password_status("The e-mail address you entered is not registered in our system; please try again or <a href = '/loginhelp'>contact us</a>");
			//update_login_status("Please fill out the fields below to register a new account:.");
			//update_login_prompt("Username " + sun + " is available!");
			// document.getElementById("login_prompt").style.color = "green";
			//show_signup_form();
			//hide_login_button();
			//grow_smoothbox();
		}
		//else
		//{
		//	alert("error");
		//	update_password_status("ERROR: Login is currently not available. Please contact customer service.");
		//}
		
		preload_images();
		grow_smoothbox();

	},

	do_login: function(result)
	{
		if(result == true)
		{
			//figure out the password
			//spw = document.getElementById("seals_spw").value;
			hide_login_button();
			hide_cancel_button();
			update_login_status("Login Successful. Please wait...<br><img src = '/images/progressbar.gif' />");
			//fresult = community_login(document.getElementById("seals_login").value, spw);
			
			//proceed to the next page
			go_next();
		}
		else
		{
			update_login_status("<br><br>Invalid Login; please try again.<br><a href = '/forgot-password' style = 'color: white'>Trouble Logging In?</a><br><br>Trouble logging in? <br><a href = '/loginhelp'><span style = 'color: orange; text-decoration: underline'>Contact customer service</a>");
			//update_login_status(result);
			grow_smoothbox();
		}
	},

	logout: function(result)
	{
		document.getElementById("welcome_message_small").style.display = "none";
		if(result == true)
		{init
			update_welcome_message("<span style = 'font-size:12pt; font-weight:bold; color:white'>You have successfully logged out of NavySEALS.com.</span><br>Click <a href = '/'>here</a> to return to the main page.<br>");
		}
		else
		{
			update_welcome_message("There was a problem logging out of the web site. Please contact technical support.");
		}
	},
	
	reset_password: function(result)
	{
		update_login_status("");
		hide_signup_form();
		hide_cancel_button();
		
		if(result == true)
		{
			//update_login_prompt("A new password has been sent to your e-mail address on file. Use your new password to log in below:");
			var sun = document.getElementById("chpw_new1").value;
			update_password_status("<strong>An e-mail has been sent to " + sun + " with a link to reset your password</strong>");

			//show_spw_field();
		}
		else
		{
			update_password_status("There was a problem resetting your password. Please <a href = '/loginhelp'>contact customer service</a> for assistance.");
			//hide_spw_field();
			//hide_login_button();
			//show_cancel_button();
		}
		
		grow_smoothbox();

		
	},

	change_password: function(result)
	{
		if(result == true)
		{
			update_password_status("<span style = 'color:green'><strong>Your password has been changed successfully<strong></span><br><a href = '/' style = 'color: white'>Return Home</a>");
			setVal("chpw_new1", "New Password");
			setVal("chpw_new2", "Repeat Password");
			setVal("chpw_current", "Current Password");
			hide("chpw_new1");
			hide("chpw_new2");
			hide("change_password_button");
			hide("cancel_change_password_button");
			hide("change_password_form");
		}
		else
		{
			update_password_status("An error occurred while trying to change your password. Your password has not been changed. <br>Please <a href = '/forgot-password' style = 'color:white'>try again</a>, or <a href = '/loginhelp' style = 'color:white'>contact customer service</a> if the problem persists.<br><br>Click <a href = '/forgot-password' style = 'color:white'>here</a> to continue.");
			setVal("chpw_new1", "New Password");
			setVal("chpw_new2", "Repeat Password");
			setVal("chpw_current", "Current Password");
			hide("chpw_new1");
			hide("chpw_new2");
			hide("change_password_button");
			hide("change_password_form");
		}
		
		grow_smoothbox();
	},
	
			
			
	
    nodeList: []
}










//adds subscription product with given pid to order and launches checkout process
function add_subscription_and_checkout(pid)
{
	if(!pid)
	{
		return false;
	}
	

	
}

//attaches an event handler to el to make it 
//change color when the user moves the mouse over it
function make_hover_color(el)
{
    var e = $(el);
    
}



//sealsElement stuff
function set_hover_prompt(el, prompt, target)
{
    if($(target))
    {
        $(target).hide();
        if($(el))
        {
        		$(el).observe("mouseover", function(event){show_hover_prompt(target, prompt)});
        		$(el).observe("mouseout" , function(event){hide_hover_prompt(target)});
        	}
    }
}


//sets the innerHTML of element to prompt,
//optionally with effect
function show_hover_prompt(el, prompt)
{
    //alert("test");
    //$(el).show();
    if($(el))
    {
        $(el).update(prompt);
        new Effect.Appear(el);
        new Effect.Highlight(el);
    }
}

//sets innerHTML of target to empty
function hide_hover_prompt(el)
{
    if($(el))
    {
        //$(el).update("");
        new Effect.Fade(el);
        //$(el).hide();
    }
}




//end sealsElement stuff


//-----------login popup stuff------------//

//checks if a user is logged in
function is_logged_in()
{

	new Ajax.Request("/server.php?c=sealsuser&m=is_logged_in", {
  		onSuccess: function(transport) {
  			if(transport.responseText.indexOf("true") == "-1")
  			{
  				pager_init();
  			}
  
  		}
  	});
}




//advances the user to the next page
function go_next()
{
	//first, determine where we are going from the query string
	var dest = queryString("goto");
	
	//if we have a predetermined destination...
	if(dest != "false" && dest != "")
	{
		//first, unmangle the link, to reconstruct the query string
		dest = Pager.link_unmangle(dest);
		
		if(parent)
		{
			//alert("parent");
			parent.parent.location = dest;
		}
		else
		{
			if(window)
			{
				//alert("window");
				window.location = dest;
			}
		}
	}
	else //no destination is specified, simply reload the current window, or the parent window
	{
		if(parent)
		{
			parent.location.reload();
		}
		else
		{
			//alert("dest =" + dest +"//");
			if(window)
			{
				window.location.reload();
			}
		}
	}
}



//runs when loading box initially
function loadBox()
{
	if(parent.adjustIFrameSize)
	{
    	parent.adjustIFrameSize(window);
	}
}




//sets up slider effect for login status area
function set_status_slider()
	{
		//show("login_status_area");
		mySlide = new Fx.Slide('login_status_area', {duration: 2000});
		mySlide.hide();
	//	mySlide.show();
	}


function continue_login()
{
	var sunel = document.getElementById("seals_login");
	if(sunel)
	{
		if(sunel.value != "")
		{
			update_login_prompt('Enter your password to log in as ' + sunel.value + '.<br>New user? try a different username');
			update_login_button("Log In");
			show("spw_field");
			show_login_button();
			show_cancel_button();
			hide_signup_form();
			show_spw_field();
			update_login_status("");
		}
		else
		{
			update_login_prompt("You must enter a user name to continue");
		}
	}
	
}





//preload images for login
function preload_images()
{
	if (document.images)
    {
      preload_image = new Image(25,25); 
      preload_image.src="/images/progressbar.gif"; 
    }
}


//fires when user hits cancel button; reverts login box to original state
function cancel_login()
{
	update_login_prompt("Re-enter your user name:");
	update_login_status("");
	// document.getElementById("login_prompt").style.color = "black";
	document.getElementById("seals_login").value = "";
	hide_spw_field();
	hide_signup_form();
	update_login_button("Continue");
	hide_login_button();
	hide_cancel_button();
	hide_login_status_area();
	hide("login_status");
	
	grow_smoothbox();
	
}



//called when the user engages the login form
//(by typing something in it)
function engage_login(e, el)
{
	//first, capture enter key
	checkLoginEnter(e, el);
	
	update_login_prompt('Press Enter when you are done:');
	//update_login_status("");
	hide_signup_form();
	hide_spw_field();
	hide_cancel_button();
	// show_login_button();
	// update_login_button("Continue");
	hide_login_status_area();
	// document.getElementById("login_status_area").style.display = "none";
	document.getElementById("login_status").innerHTML = "";
}

//called when the user engages the login form
//(by typing something in it)
function engage_chpw_oldpass(e, el)
{
	

	update_password_status('Press Enter to continue:');

	//then, capture enter key
	checkLoginEnter(e, el);


}


//executes when user types something into current password field
//for changing password
function validate_chpw_oldpass()
{
	var oldpass = getVal("chpw_current")
	var remoteUser = new sealsuser(user_callback);
	remoteUser.check_pass(oldpass)

}



//executes when user types something into first new password field
//for changing password
function engage_chpw_new1(e, el)
{
	update_password_status('Enter your new password and press Enter to continue:');
	//then, capture enter key
	checkLoginEnter(e, el);
}



//executes when user types something into second new password field
//for changing password
function engage_chpw_new2(e, el)
{
	update_password_status('Repeat your new password and press Enter to continue:');
	//then, capture enter key
	checkLoginEnter(e, el);
	
	//now, compare passwords and tell the user
	compare_passwords();

}


//checks if new password 1 and new password 2 are identical
function compare_passwords()
{
	var new1 = getVal("chpw_new1");
	var new2 = getVal("chpw_new2");
	if(new1 == new2)
	{
		//passwords match
		update_password_status("<span style = 'color:green'>Passwords match. Press enter to reset password.</span>");
		show("change_password_button");
		return true;
	}
	else
	{
		//passwords do not match
		update_password_status("Passwords do not match. Repeat your password in the second field below:");
		hide("change_password_button");
		return false;
	}
}

//processes password reset
function process_change_password(id, token)
{
	var remoteUser = new sealsuser(user_callback);
	//var oldpass = getVal("chpw_current");
	var new1 = getVal("chpw_new1");
	var new2 = getVal("chpw_new2");
	
	if(!new1)
	{
		return false;
	}
	if(!new2)
	{
		return false;
	}
	
	if(new1 == "" || new2 == "")
	{
		update_password_status("Password cannot be blank");
	}
	if(compare_passwords() == false)
	{
		//passwords do not match
		update_password_status("Passwords do not match");
		return false;
	}
	else
	{
		remoteUser.change_password(id, token, new1, new2);
		return true;
	}
	
	return false;
	
}


//if the user hits the enter key, extracts the email address entered and submits it to request_password_reset() for processing
function engage_password_reset(e, email_element)
{
	var email = email_element.value;
	var is_not_enter = checkEmailEnter(e, email_element);
	
	update_password_status('Press Enter to reset your password');
	
	if(! is_not_enter)
	{

		return true;

	}
	
	return false;
	
}


//processes the e-mail address provided, submits it to the server, and displays the result to the GUI
function request_password_reset(email)
{
	if(email)
	{
		update_password_status('Please stand by while we process your request...');
		check_email(email);
		return true;
	}
	
	return false;
	
}


//called when the user engages the password field
//(by typing something in it)
function engage_spw(e, el)
{
	//first, capture enter key
	checkLoginEnter(e, el);
	update_login_prompt('Press Enter to log in');
}

//changes the message that appears in the login_prompt div
//which is above the login form
function update_login_prompt(msg)
{
	el = document.getElementById("login_prompt");
	el.innerHTML = msg;
	// el.style.color = "maroon";
}

//chagnes the message for the login status div
//which is below the login form
function update_login_status(msg)
{

	el = document.getElementById("login_status");
	if(el)
	{
		el.innerHTML = "<br><br>"  + msg;
	}
	show("login_status");
	show_login_status_area();
	
}

//changes the message that appears above the change password form
//in the password_status div
function update_password_status(msg)
{
	show("password_status");
	el = document.getElementById("password_status");
	if(el)
	{
		el.innerHTML = msg + "<br>";
		return true;
	}
	else
	{
		return false;
	}
	//el.style.color = "maroon";
}

function update_welcome_message(msg)
{
	el = document.getElementById("welcome_message");
	show("welcome_message");
	el.innerHTML = msg;
}

function focuson(fieldid)
{
	el = document.getElementById(fieldid);
	el.focus();
}

function show_login_button()
{
	show("login_button_span");
	// document.getElementById("login_button").style.display = "inline";
}

function hide_login_button()
{
	hide("login_button_span");
	// document.getElementById("login_button").style.display = "none";
}

function update_login_button(string)
{
	document.getElementById("login_button").innerHTML = string;
}

function show_cancel_button()
{
	show("cancel_button_span");
	// document.getElementById("cancel_button").style.display = "inline";
}

function hide_cancel_button()
{
	hide("cancel_button_span");
	// document.getElementById("cancel_button").style.display = "none";
}


//returns true if the user pressed the enter key
function checkEnter(e)
{ //e is event object passed from function invocation
	var characterCode //literal character code will be stored in this variable

	if(e && e.which){ //if which property of event object is supported (NN4)
		e = e
		characterCode = e.which //character code is contained in NN4's which property
	}
	else{
		e = event
		characterCode = e.keyCode //character code is contained in IE's keyCode property
	}

	if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
		//document.forms[0].submit() 
		//submit the form
		return true
	}
	else{
		return false
	}

}



//shows the login status area
function show_login_status_area()
{
	show("login_status_area");

	
}

//hides the login status area
function hide_login_status_area()
{

	hide("login_status_area");
}


//shows the change password form
function show_change_password()
{
	update_password_status("Please fill out the fields below to change your password:");
	toggle("change_password_form");
	show_login_status_area();
	show("cancel_change_password_button");
	
	hide("change_password_button");
}


//cancels the user's change password request and reverts back to the original prompt
function cancel_change_password()
{
	setVal("chpw_new1", "New Password");
	setVal("chpw_new2", "Repeat Password");
	setVal("chpw_current", "Current Password");
	hide("chpw_new1");
	hide("chpw_new2");
	hide("change_password_button");
	show("chpw_current");
	hide("change_password_form");
	hide_login_status_area();
	update_password_status("<span onclick='show_change_password();' style = 'text-decoration: underline; font-weight:bold'>change password</span>");
	
	grow_smoothbox()
}

//gets value for DOM element id
function getVal(id)
{
	el = document.getElementById(id);
	if(el)
	{
		return el.value;
	}
	else
	{
		return false;
	}
	
	//sanity check...
	return false;
}

//gets value for DOM element id
function setVal(id, val)
{
	if(!val)
	{
		return false;
	}

	el = document.getElementById(id);
	if(el)
	{
		el.value = val;
		return true;
	}
	else
	{
		return false;
	}
	
	//sanity check...
	return false;
}


//toggles the visibility of a DOM element
function toggle(id)
{
	el = document.getElementById(id);
	if(el)
	{
		if(el.style.display == "none")
		{
			el.style.display = "inline";
		}
		else
		{
			el.style.display = "none";
		}
		return true;
	}
	else
	{
		return false;
	}
	
	return false;
		
	
}



//shows specified DOM element -- returns true on success
function show(id)
{
	el = document.getElementById(id);
	if(el)
	{
		if(el.style.display == "none")
		{
			el.style.display = "inline";
			return true;
		}
		else
		{
			return false;
		}
		
	}
	else
	{
		return false;
	}
	//sanity check...
	return false;
}


//hides specified DOM element -- returns true on success
function hide(id)
{
	el = document.getElementById(id);
	if(el)
	{
		if(el.style.display == "none")
		{
			//if the element is already hidden, do nothing
			return false;
		}
		else
		{
			//if the element is visible, set it to invisible
			el.style.display = "none";
			return true;
		}
		
	}
	else
	{
		return false;
	}
	//sanity check...
	return false;
}


//queries the server via xmlhttprequest and retrieves authentication token;
//the server will store this token as a session variable and requires all subsequent login requests
//to provide the same auth token
function get_auth_token()
{
	var r;
	return get_remote("/dologin.php?action=get_auth_token");
}

//queries server via xmlhttprequest to see if the username exists
//requires username and auth_token
//returns user status code (0 = does not exist; 1 = exists)
function user_exists(username, auth_token)
{
	result = get_remote("/dologin.php?action=check_user&sun=" + username + "&sat=" + auth_token, "", "spinner");
	if(result == 1)
	{
		return true;
	}
	else
	{
		return false;
	}
}


//processes the event handler for form input
//blurs the focus for element el if enter key is pressed
function checkLoginEnter(e, el)
{ //e is event object passed from function invocation
	var characterCode //literal character code will be stored in this variable

	if(e && e.which){ //if which property of event object is supported (NN4)
		e = e
		characterCode = e.which //character code is contained in NN4's which property
		
	}
	else{
		if(event)
		{
			e = event
			characterCode = e.keyCode //character code is contained in IE's keyCode property
		}
	}

	if(!characterCode)
	{
		return false;
	}
	
	if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
		//document.forms[0].submit() 
		//submit the form
		el.blur();
		return false
	}
	else{
		return true
	}

}


//processes the event handler for form input
//blurs the focus for element el if enter key is pressed
function checkEmailEnter(e, el)
{ //e is event object passed from function invocation
	var characterCode //literal character code will be stored in this variable

	if(e && e.which){ //if which property of event object is supported (NN4)
		e = e
		characterCode = e.which //character code is contained in NN4's which property
	}
	else{
		e = event
		characterCode = e.keyCode //character code is contained in IE's keyCode property
	}

	if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
		//document.forms[0].submit() 
		//submit the form
		el.blur();
		return false
	}
	else{
		return true
	}

}

//hides the password field
function hide_spw_field()
{
	document.getElementById("seals_spw").style.display = "none";
}

//shows a password input box in the div called spw_field
function show_spw_field()
{
	//first, hide the signup form if it's visible
	document.getElementById("seals_signup_form").style.display = "none";

	//first, get a hold of the field in question...
	el = document.getElementById("seals_spw");
	//...and then make sure it exists

	if(el)
	{
		//now, show it
		el.style.display = "inline";
		el.focus();
		
	}

	document.getElementById("login_button").style.display = "inline";


}

//loads a page into an iframe
function load_iframe(iframe_id, uri)
{
	if(uri == "")
	{
		uri = "/seals/nothing.html";
	}
	if(iframe_id == "")
	{
		return false;
	}
	
	iel = document.getElementById(iframe_id);
	if(iel)
	{
		iel.src = uri;
		return true;
	}
	else
	{
		return false;
	}
	
	return false;
	
}


//resizes the element with given ID
function resize_element(id, width, height)
{
	el = document.getElementById(id);
	//first, make sure the element exists
	if(el)
	{
		if(width)
		{
			if(width != "-1")
				el.width = width + "px";
		}
		
		if(height)
		{
			if(height != "-1")
			el.height = height + "px";
		}
	}
	else
	{
		return false;
	}
}


//finds the smoothbox elements and increases the height of the smoothbox
function grow_smoothbox()
{
	
	//first, make sure we have a height
	//if(height == "")
	//{
	//	return false;
	//}
	

	//get a handle for the login box
	//el = document.getElementById("login-box");
	//if(el)
	//{
		//el.style.height = height + "px";
	//}
	

	if(parent.adjustIFrameSize)
	{
		  parent.adjustIFrameSize(window);
		  //return true;
	}
              
	//return false;

	
}


//shows a signup form under the user name field
function show_signup_form()
{
	hide_cancel_button();
	//first, hide the password field, if it's visible
	el = document.getElementById("seals_spw");
	//...and then make sure it exists

	if(el)
	{
		//now, show it
		el.style.display = "none";
	}

	//then, proceed to showing the signup form

	//first, get a hold of the field in question...
	el = document.getElementById("seals_signup_form");
	//...and then make sure it exists
	if(el)
	{
		//show the signup form
		el.style.display = "inline";
		//load the tracking page into the tracking iframe
		load_iframe("seals_signup_form_iframe", "/seals/registration_form.php");
	}


}


//hides the signup form
function hide_signup_form()
{
	
	el = document.getElementById("seals_signup_form");
	if(el)
	{
		el.style.display = "none";
	}

}


//send a request to the server to reset the password 
//for the current user, and sends a new password
function lost_password()
{
	var email = document.getElementById("chpw_new1").value;
	var remoteUser = new sealsuser(user_callback);
	remoteUser.reset_password(email);
}


//uses ajax call to determine whether or not user exists
function check_username(username)
{
	var remoteUser = new sealsuser(user_callback);
	remoteUser.exists(username);
}

//uses ajax call to determine whether or not user exists
function check_email(email)
{
	var remoteUser = new sealsuser(user_callback);
	remoteUser.email_exists(email);
}


function send_registration() {
	var ae = document.getElementsByTagName('input');
    var remoteUser = new sealsuser(user_callback);
    var payload = new Object();
    for(var i = 0; i < ae.length; i++) {
        if (ae[i].name) {
            payload[ae[i].name] = ae[i].value;
        }
    }

	as = document.getElementsByTagName('select');
	var payload2 = new Object();
    for(var i = 0; i < as.length; i++) {
        if (as[i].name) {
            payload2[as[i].name] = as[i].value;
        }
    }

    // do any needed validation here

    remoteUser.process_registration(payload, payload2, auth_token);
}



function added_new_user(username)
{
	//hide the signup form
	spwel = document.getElementById("seals_spw1");
	if(spwel)
	{
		var spw = spwel.value;
	}
	
	document.getElementById("seals_signup_form").style.display = "none";
	document.getElementById("seals_login").style.display = "none";
	document.getElementById("login_prompt").style.display = "none";
	document.getElementById("login_button").style.display = "none";
	seals_username = username;
	update_login_prompt("Successfully registered new account for " + username + ".<br>");
	//update_login_status("A confirmation e-mail has been sent to you which contains your login information.<p><iframe src = '/seals/featured-products.php' height = 300 width = 350 frameborder = '0'><b>Click <a onclick = 'go_next()' href = '/' >here</a> to continue</b><iframe src='/seals/registration_success.php' height='1' width='1' frameborder='0' scrolling='no'></iframe>");
	update_login_status("A confirmation e-mail has been sent to you which contains your login information.<br>Please stand by while this page reloads...");

}


function do_login()
{
	
	var username = document.getElementById("seals_login").value;
	var spw = document.getElementById("seals_spw").value;
	var remoteUser = new sealsuser(user_callback);
	
	remoteUser.do_login(username, spw);
}



//submits login info via xmlhttprequest to forum login
function forum_login(username, password)
{
	params = "do=login&vb_login_username=" + username + "&vb_login_password=" + password + "act[login]=Login&cookieuser=1&url=" + location.href;
	url = "/forums/login.php";
	result = get_remote(url, params, "", "", "post");
}


//submits login info via xmlhttprequest to forum login
function community_login(username, password)
{
	params = "sun=" + username + "&spw=" + password + "&cookieuser=1&url=" + location.href;
	url = "/community/plugins/vbulletin/vb_login_pat.php";
	result = get_remote(url, params, "", "", "post");
}


//logs the user out
function process_logout()
{
	var result;
	//result = get_remote("/dologin.php?action=logout");
	remoteUser = new sealsuser(user_callback);
	remoteUser.logout();

	fresult = get_remote("/logout.php");
	window.location.reload();
}



//continues to rotate items
function start_rotation(item_id, e)
{
	
	//if (!e) var e = window.event;
	var from = e.relatedTarget || e.fromElement;
	var to = e.relatedTarget || e.toElement;
	
	var fromId = from.id;
	var toId = to.id;
	
	if((fromId != "whatsnew_inner_" + item_id) && (fromId != item_id + "_summary_container") && (fromId != "whatsnewitem_" + item_id) && (fromId != item_id + "_date") && (fromId != item_id + "_category") && (fromId != item_id + "_summary"))
	{
		if(typeof(current_rotator) != "undefined")
		{
			clearInterval(current_rotator);
		}
		test_status("START: fromElement: " + fromId + " | toElement: " + toId);
	
		test_status("START: OK");
		//test_status("START: fromElement: " + fromId + " | toElement: " + toId);
		//alert(relTarg.id + " != " + "whatsnewitem_" + item_id);
		do_start_rotation(item_id);
	}
	
}



function do_start_rotation(item_id)
{
	var whatsnewitem = document.getElementById('whatsnewitem_' + item_id);
	

	//start by immediately rotating to the next item...
	rotate_item(item_id)
	
	//...and then, continue to rotate subsequent items
	current_rotator = setInterval("rotate_item(" + item_id + ")", 2500);
}




function stop_rotation(item_id, e)
{
	var from = e.relatedTarget || e.fromElement;
	var to = e.relatedTarget || e.toElement;
	
	var fromId = from.id;
	var toId = to.id;
	
	
	if((fromId != "whatsnew_inner_" + item_id) && (fromId != item_id + "_summary_container") && (fromId != "whatsnewitem_" + item_id) && (fromId != item_id + "_date") && (fromId != item_id + "_category") && (fromId != item_id + "_summary"))
	{
		test_status("STOP: fromElement: " + fromId + " | toElement: " + toId);
	
		test_status("STOP: OK");
		do_stop_rotation(item_id);
	}
}



function do_stop_rotation(item_id)
{
	//alert("stopping");
	
	var whatsnewitem = document.getElementById('whatsnewitem_' + item_id);
	
	clearInterval(current_rotator);

		
	var queue = Effect.Queues.get(item_id + '_scope');
	for(property in queue)
	{
		//test_status(property);
	}
	test_status("queue size" + queue.size());
	//queue.each(function(e) { e.cancel() });
}



//creates a scriptaculous effect that rotates the subtitle of the given element
function rotate_item(item_id)
{
	//set an array of divs to rotate through
	var divs = new Array(item_id + '_description', item_id + '_date');
	
	//first, determine the current position in the rotation queue we are currently displaying
	var container_element = $(item_id + '_summary_container');
	var position = container_element.position;
	var original_position = position;
	if(position == null)
	{
		//we are starting out...
		position = 0;
	}
	
	
	//get the position of the next element
	var new_position = position + 1;
	//check if we are done iterating through each element
	if(new_position > divs.length - 1)
	{
		//if so, stop the rotation
		//do_stop_rotation(item_id);
		//div_rotate_effect(divs[position], divs[new_position], item_id);
		new_position = 0;
	}
	
	if(original_position == 0 && original_position != null)
	{
		do_stop_rotation(item_id);
	
		div_rotate_effect(divs[position], divs[0], item_id);
		
		
		container_element.position = null;
	}
	else
	{	
		//check to see if the element has content
		if(divs[position] != "undefined" && divs[new_position] != "undefined" && $(divs[new_position]).innerHTML.indexOf("[none]") == -1)
		{
			//now, slide the old item out and the new item in
			test_status("rotating up " + divs[position] + "; rotating down " + divs[new_position]);
			div_rotate_effect(divs[position], divs[new_position], item_id);
			test_status(divs[new_position] + " content = " + $(divs[new_position]).innerHTML);
			//divSwap(divs[new_position], item_id + '_summary_container');
			//alert(divs[new_position]);
		}
		//increment the position counter to display the next div in the rotation
		container_element.position = new_position;
		//container_element.writeAttribute(position, new_position);
	}
	


	
	

	return true;

	
}


function div_rotate_effect(div1, div2, item_id)
{


	//alert(item_id + "_scope");
	Effect.SlideUp(div1, {queue: {position:'end', scope: item_id + "_scope", limit: 2} });
	Effect.SlideDown(div2, {queue: {position:'end', scope: item_id + "_scope", limit: 2} });
	
}


function test_status(msg)
{
	//$("status").innerHTML =  msg + "<br>" + $("status").innerHTML;
}







//retrieves a remote document via xmlhttprequest
//takes the URL to retrieve as an argument and the request variables as a string argument
function get_remote(url, request_vars, spinner_span, spinner_path, method) {
	
	req = false;
	if(spinner_path == undefined)
	{
		spinner_path = "/images/spinner.gif";
	}
    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest && !(window.ActiveXObject)) {
    	try {
			req = new XMLHttpRequest();
        } catch(e) {
			req = false;
        }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
       	try {
        	req = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		req = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		req = false;
        	}
		}
    }
	//var req = new XMLHttpRequest();
	if(req) {
	
		if(spinner_span != undefined)
		{
			req.onreadystatechange = show_spinner;
		}
		if(method == "post")
		{
			req.open("POST", url, false)
			req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			req.setRequestHeader("Content-length", params.length);
			req.setRequestHeader("Connection", "close");
			req.send(params);
		}
		else
		{
			req.open("GET", url, false);
			req.send(request_vars);
		}
		result = req.responseText;
		return result;
	}
}


function show_spinner(spinner_span, spinner_path)
{
	//alert(req.readyState);
	/*
	sp = document.getElementById(spinner_span);
	if(req.readyState == 1)
	{
		//if we are loading
			if(sp)
			{
				//if the spinner span exists
				se = document.createElement("img");
				se.id = "spinner_graphic";
				se.src = spinner_path;
				sp.appendChild(se);
				
			}
	}
	if(req.readyState == 4)
	{
		//if we are done loading
		if(sp)
		{
			se = document.getElementById("spinner_graphic");
			//sp.removeChild(se);
		}



	}
	*/

}

function processReqChange() {
    // only if req shows "loaded"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            // ...processing statements go here...
        } else {
            alert("There was a problem retrieving the XML data:\n" +
                req.statusText);
        }
    }
}


function PageQuery(q) {
	if(q.length > 1) this.q = q.substring(1, q.length);
	else this.q = null;
	this.keyValuePairs = new Array();
	if(q) {
	for(var i=0; i < this.q.split("&").length; i++) {
	this.keyValuePairs[i] = this.q.split("&")[i];
	}
	}
	this.getKeyValuePairs = function() { return this.keyValuePairs; }
	this.getValue = function(s) {
	for(var j=0; j < this.keyValuePairs.length; j++) {
	if(this.keyValuePairs[j].split("=")[0] == s)
	return this.keyValuePairs[j].split("=")[1];
	}
	return false;
	}
	this.getParameters = function() {
	var a = new Array(this.getLength());
	for(var j=0; j < this.keyValuePairs.length; j++) {
	a[j] = this.keyValuePairs[j].split("=")[0];
	}
	return a;
	}
	this.getLength = function() { return this.keyValuePairs.length; }
}


function queryString(key){
	var page = new PageQuery(window.location.search);
	return unescape(page.getValue(key));
}





//returns a random string of length length
function randomString(length) {
	if(!length)
	{
		length = 8;
	}

	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var string_length = length;
	var randomstring = '';
	for (var i=0; i<string_length; i++) 
	{
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}

	return randomstring;
}








//------------SCRIPTACULOUS ADDONS-------------//

divSwap = function(element,container){
    var div = document.getElementById(container);
    var nodeList = div.childNodes;
    var queue = Effect.Queues.get('menuScope');

    if(queue.toArray().length<1){
        if(Element.visible(element)==false){
            for(i=0;i<nodeList.length;i++){
                if(nodeList.item(i).nodeName=="div" && nodeList.item(i).id!=element){
                    if(Element.visible(nodeList.item(i))==true){
                        Effect.SlideUp(nodeList.item(i),{queue:{position:'end',scope:'menuScope',limit:2}})
                    }
                }
            }
            Effect.SlideDown(element,{queue:{position:'end',scope:'menuScope',limit:2}})
       }
   }
}





