

var animating = false;
var cctypeField = undefined;

function trim(sString)
{

	while (sString.substring(0,1) == ' ')
	{
		sString = sString.substring(1, sString.length);
	}
	while (sString.substring(sString.length-1, sString.length) == ' ')
	{
		sString = sString.substring(0,sString.length-1);
	}
	return sString;	
}

// White Space trim
// Pass a string into this function to remove all white space
function strReplace(str,val1,val2) {
	if(str.indexOf(val1) != -1) {
		do {
			str = str.replace(val1, val2);
		} while (str.indexOf(val1) != -1);
	}
	return str;
}


function showcomment()
{
	new Effect.Appear('comment');
	new Effect.BlindUp('clickhere');
}

function hidecomment()
{
	new Effect.BlindUp('comment');
	new Effect.Appear('clickhere');
}

// Validate Credit Card
function isValidCreditCard(type, ccnum) {
	if (type == "VC") {
		// Visa: length 16, prefix 4, dashes optional.
		var re = /^4\d{3}-?\d{4}-?\d{4}-?\d{4}$/;
	} else if (type == "MC") {
		// Mastercard: length 16, prefix 51-55, dashes optional.
		var re = /^5[1-5]\d{2}-?\d{4}-?\d{4}-?\d{4}$/;
	} else if (type == "DS") {
		// Discover: length 16, prefix 6011, dashes optional.
		var re = /^6011-?\d{4}-?\d{4}-?\d{4}$/;
	} else if (type == "AX") {
		// American Express: length 15, prefix 34 or 37.
		var re = /^3[4,7]\d{13}$/;
	} else if (type == "DC") {
		// Diners: length 14, prefix 30, 36, or 38.
		var re = /^3[0,6,8]\d{12}$/;
	}
	if (!re.test(ccnum)) return false;
	// Remove all dashes for the checksum checks to eliminate negative numbers
	ccnum = ccnum.split("-").join("");
	// Checksum ("Mod 10")
	// Add even digits in even length strings or odd digits in odd length strings.
	var checksum = 0;
	for (var i=(2-(ccnum.length % 2)); i<=ccnum.length; i+=2) {
		checksum += parseInt(ccnum.charAt(i-1));
	}
	// Analyze odd digits in even length strings or even digits in odd length strings.
	for (var i=(ccnum.length % 2) + 1; i<ccnum.length; i+=2) {
		var digit = parseInt(ccnum.charAt(i-1)) * 2;
		if (digit < 10) {
			checksum += digit;
		} else {
			checksum += (digit-9);
		}
	}
	if ((checksum % 10) == 0) {
		return true;
	} else {
		return false;
	}
}




// Image rollover - for use please make sure image names follow the following name scheme:
// Idle Image:  image_i.gif
// Hover Image: image_o.gif
// Active Image (Down state): image_a.gif
// File extension and anything before the _i. does not matter so long as it is consistent between
// the two states (e.g. "image_i.gif" and "hoverimage_o.gif" will not work,
// but "image_i.gif" and "image_o.gif" will work)
//
// Usage: Assign the class "rollOver" to any image or input field. It does not have to be
// the only class on the tag to work.
// <img src="image_i.gif" alt="" class="rollOver" />
// OR
// <input type="image" src="image_i.gif" class="rollOver" />
//
// NOTE: Active states will only be assigned to input tags, not image tags

function rollAssign() {
	// Grab elements to parse
	var images = document.getElementsByTagName("img");
	var inputs = document.getElementsByTagName("input");

	var validInputs = new Array();
	var zI = 0;
	for(z=0;z<inputs.length;z++) {
		if(inputs[z].type == "image") {
			validInputs[zI] = inputs[z];
			zI++;
		}
	}


	var elements = new Array();
	for(z=0;z<images.length;z++) {
		elements.push(images[z]);
	}
	for(z=0;z<validInputs.length;z++) {
		elements.push(validInputs[z]);
	}

	for(z=0;z<elements.length;z++) {
		if(elements[z].className.indexOf("rollOver") != -1) {
			elements[z].onmouseover = function() {
				this.src = this.src.replace("_i.","_o.");
			}
			elements[z].onmouseout = function() {
				this.src = this.src.replace("_o.","_i.");
			}
			if(elements[z].type == "image") {
				elements[z].onmousedown = function() {
					this.src = this.src.replace("_o.","_a.");
				}
				elements[z].onmouseup = function() {
					this.src = this.src.replace("_a.","_i.");
				}
				elements[z].onfocus = function() {
					this.blur();
				}
				elements[z].onmouseout = function() {
					if(this.src.indexOf("_a") != -1) {
						this.src = this.src.replace("_a.","_i.");
					} else {
						this.src = this.src.replace("_o.","_i.");
					}
				}
			}
		}
	}
}




// Open links in external window for XHTML 1.0 Strict compliancy
// To make a link open in external window add the "rel" attribute to the <a> tag
// and set its value to "external" example:
// <a href="http://www.google.com" rel="external">Google</a>
function externalLinks() {
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	var areas = document.getElementsByTagName("area");
	var forms = document.getElementsByTagName("form");
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute("href") &&
		anchor.getAttribute("rel") == "external")
		anchor.target = "_blank";
	}
	for (var x=0; x<areas.length; x++) {
		var area = areas[x];
		if (area.getAttribute("href") &&
		area.getAttribute("rel") == "external")
		area.target = "_blank";
	}
	for (var y=0; y<forms.length; y++) {
		var form = forms[y];
		if (form.getAttribute("rel") == "external")
		form.target = "_blank";
	}
}




// Replace input field with default value on blur if nothing was entered
// Usage: <input type="text" value="Default Value" onfocus="clearField(this,'off');" onblur="clearField(this,'on');" />
function clearField(thefield,onOff) {
	if(onOff == 'off') {
		if (thefield.defaultValue==thefield.value) {
			thefield.value = "";
		}
	} else {
		if (thefield.value=="") {
			thefield.value = thefield.defaultValue;
		}
	}
}

function validatemessage(fElem) {
	// Grab all the names of the elements in the form passed (fElem) as mandatory.
	var mandatory = fElem.mandatory.value.split(",");

	// Init error response
	var errors = false;
	var message = "There were errors in your request:\n\n";
	
	// Parse through each mandatory field
	for(z=0;z<mandatory.length;z++) {
		var tField = document.getElementById(mandatory[z]);
		var fieldFormatted = mandatory[z].substr(6);
		//alert(mandatory[z]+" > "+fieldFormatted+" = "+strReplace(tField.value," ",""));
		
		// Check if field is empty (after removing white space)		
		if(strReplace(tField.value," ","") == "") {
			// Field is empty create error
			errors = true;
			message += "- "+strReplace(fieldFormatted.capitalize(),"-"," ")+" is a required field\n";
			
			}
			document.getElementById('label_'+fieldFormatted).style.color = "#f00";
		}
		
		if(errors==true)
		{
		
			alert(message);
			return false;
		}else
		{
			return true;
		}	
			
	}

function validateflirtmessage(fElem) {
	// Grab all the names of the elements in the form passed (fElem) as mandatory.
	var mandatory = fElem.mandatory.value.split(",");
	
	
	// Init error response
	var errors = false;
	var message = "There were errors in your request:\n\n";
	
	// Parse through each mandatory field
	for(z=0;z<mandatory.length;z++) {
		alert(mandatory[z]);
		var tField = document.getElementById(mandatory[z]);
		alert(tField);
		var fieldFormatted = mandatory[z].substr(6);
		alert(mandatory[z]+" > "+fieldFormatted+" = "+strReplace(tField.value," ",""));
		
		// Check if field is empty (after removing white space)		
		if(strReplace(tField.value," ","") == "") {
			// Field is empty create error
			errors = true;
			message += "- "+strReplace(fieldFormatted.capitalize(),"-"," ")+" is a required field\n";
			
			}
			document.getElementById('label_'+fieldFormatted).style.color = "#f00";
		}
		
		if(errors==true)
		{
		
			alert(message);
			return false;
		}else
		{
			return true;
		}	
			
	}

// Form validation script
function validateForm(fElem) {
	//alert('validation form called');
	// Grab all the names of the elements in the form passed (fElem) as mandatory.
	var mandatory = fElem.mandatory.value.split(",");

	// Init error response
	var errors = false;
	var message = "There were errors in your request:\n\n";

	// Parse through each mandatory field	
	for(z=0;z<mandatory.length;z++) {
		var tField = document.getElementById(mandatory[z]);
		var fieldFormatted = mandatory[z].substr(6);
		//alert(mandatory[z]+" > "+fieldFormatted+" = "+strReplace(tField.value," ",""));

		// Check if field is empty (after removing white space)
		
		if(strReplace(tField.value," ","") == "") {
			// Field is empty create error
			errors = true;

			// Filter what the error message is passed back as for custom
			// field cases such as the "Password2" field, which is actually
			// the password verification field.
			switch(fieldFormatted.toLowerCase()) {
				case "user-password2":
				case "password2":
					// Password verification field
					message += "- Please verify your password\n";
				break;
				case "user-password":
				case "password":
					message += "- Please enter your password\n";
				break;
				case "openidurl":
					message += "- Please enter your OpenID URL\n";
				break;
				case "logopath":
					message += "- Please choose your image\n";
				break;
				case "imagedesc":
					message += "- Please enter a short description or title for this image.\n";
				break;
				case "newsuggestion01":
					message += "- You must make at least one suggestion\n";
				break;
				case "billing-address1":
					message += "- Billing address is a required field\n";
				break;
				case "address-book":
					message += "- You must choose a friend to send to\n";
				break;
				case "billing-ccname":
					message += "- You must enter the name on your credit card\n";
				break;
				case "billing-cctype":
					message += "- You must choose a credit card type\n";
				break;
				case "billing-ccnumber":
					message += "- You must enter a credit card number\n";
				break;
				case "billing-csv":
					message += "- You must enter the CSV number on the back of your credit card\n";
				break;
				case "billing-ccexp":
					message += "- You must enter your credit card's expiration date\n";
				break;
				default:
					// Default required field
					message += "- "+strReplace(fieldFormatted.capitalize(),"-"," ")+" is a required field\n";
				break;
			}
			document.getElementById('label_'+fieldFormatted).style.color = "#f00";
		} else {
			// Reset border color
			document.getElementById('label_'+fieldFormatted).style.color = "#333";

			// Field value is not empty, parse tag type name and then value to
			// do custom error field checking.
			switch(tField.tagName) {
				// Field is an <INPUT> tag
				case "input":
					if(fieldFormatted.toLowerCase().indexOf("url") != -1) {
						// Field is a web address
						if(/^(http:\/\/|https:\/\/|ftp:\/\/){1}([\w]+)(.[\w]+){1,2}$/.test(tField.value)) {
							// Matched! Do nothing!
						} else {
							errors = true;
							message += "- Please make sure your Website URL is formatted\n  correctly (http://yourid.domain.com)\n";
							document.getElementById('label_'+fieldFormatted).style.color = "#f00";
						}
					}

					if(fieldFormatted.toLowerCase().indexOf("email") != -1) {
						// Field is an email field
						if(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(tField.value)) {
							// Matched! Do nothing!
						} else {
							// Email is not formatted properly
							errors = true;
							message += "- Please make sure your email address is formatted correctly\n";
							document.getElementById('label_'+fieldFormatted).style.color = "#f00";
						}
					}

					if(mandatory[z].toLowerCase().indexOf("password") != -1) {
						// Field is a password field
						if(document.getElementById("field_password2")) {
							// Verification field exists, validate
							var valPass = true;
						} else {
							// Verification field does not exist, skip validation
							var valPass = false;
						}
						if(valPass != false) {
							// Verification field was found, validate against primary field
							if(document.getElementById('field_password').value != document.getElementById('field_password2').value) {
								// Passwords do not match!
								errors = true;

								// Since the password and password verification field both
								// have the name password in their tag name, check to see if
								// the matching error has already been appended to the error message.
								if(message.indexOf("Passwords do not match!") == -1) {
									message += "- Passwords do not match!\n";
								}
								document.getElementById('label_'+fieldFormatted).style.color = "#f00";
							}
						}
						if(document.getElementById(mandatory[z]).value.length < 6) {
							// Password length is not long enough
							errors = true;
							if(message.indexOf("Password must be at least 6 characters long.") == -1) {
								message += "- Password must be at least 6 characters long.\n"
							}
							tField.style.border = "1px solid #f00";
						}
					}

					if(mandatory[z].toLowerCase().indexOf("ccnumber") != -1) {
						if(document.getElementById('field_billing-cctype').value == "") {
							if(message.indexOf('You must choose a credit card type') == -1) {
								errors = true;
								message += "- You must choose a credit card type\n";
								document.getElementById('label_'+fieldFormatted).style.color = "#f00";
							} else {
								errors = true;
								message += "- You entered an invalid credit card number\n";
								document.getElementById('label_'+fieldFormatted).style.color = "#f00";
							}
						} else {
							if(isValidCreditCard(document.getElementById('field_billing-cctype').value, tField.value) == false) {
								errors = true;
								message += "- You entered an invalid credit card number\n";
								document.getElementById('label_'+fieldFormatted).style.color = "#f00";
							}
						}
					}

					if(mandatory[z].toLowerCase().indexOf("csv") != -1) {
						if(document.getElementById('field_billing-cctype').value == "AX") {
							if(/^\d{4}$/.test(tField.value)) {
								// Passed - do nothing
							} else {
								message+= "- Please enter a valid CSV number\n";
								errors = 1;
							}
						} else {
							if(/^\d{3}$/.test(tField.value)) {
								// Passed - do nothing
							} else {
								message+= "- Please enter a valid CSV number\n";
								errors = 1;
							}
						}
					}

					if(mandatory[z].toLowerCase().indexOf("ccexp") != -1) {
						if(/^\d{2}\/\d{4}$/.test(tField.value)) {
							// Matched do nothing!
						} else {
							errors = true;
							message += "- Please format your credit card expiration date correctly (MM/YYYY)\n"
						}
					}
				break;

				// Field is a <SELECT> tag (dropdown)
				case "SELECT":
					// Custom select cases go here
				break;
			}
		}
	}

	if(errors == true) {
		alert(message);
		return false;
	} else {
		return true;
	}
}

function initSentMailAccount() {	

	// Enable rollover coloring for result lists
	$$("#results_my-suggestions .draggableLists li.row ul.rowCols").each(function(e){	
		e.observe('mouseover',function(){
			e.addClassName('rowHover').setStyle({cursor:'pointer'});
		});
		e.observe('mouseout',function(){
			e.removeClassName('rowHover');			
		});
		e.observe('click',function(){
			var subSuggestions = e.next('ul.subSuggestionLists');
			Effect.toggle(subSuggestions,'blind',{duration:0.5});
			if(subSuggestions.getStyle('display') == 'block') {
				e.up('li.row').setStyle({'border-color':'#fff'});
				new Effect.Opacity(e.down('li.col2'),{
					duration:0.5,
					from:0.0,
					to:1.0
				});
				new Effect.Opacity(e.down('li.col3'),{
					duration:0.5,
					from:0.0,
					to:1.0
				});				
			} else {
				e.up('li.row').setStyle({'border-color':'#f2f2f2'});
				new Effect.Opacity(e.down('li.col2'),{
					duration:0.5,
					from:1.0,
					to:0.0
				});
				new Effect.Opacity(e.down('li.col3'),{
					duration:0.5,
					from:1.0,
					to:0.0
				});
			}
		});
	});

	// Enable draggable sub-rows
	$$('ol#table_results_my-suggestions li.row ul.rowCols').each(function(e) {
		new Draggable(e,{
				revert: true,
				zindex: 1000,
				onStart: function() {
					e.setStyle({'border-color':'#ffdf61'});
					e.descendants('li').each(function(slr){
						slr.setStyle({'background':'#fefabf'});
					});
				},
				onEnd: function() {
					e.setStyle({'border-color':'#fff'});
					document.body.style.overflowX = "auto";
					e.descendants('li').each(function(slr){
						slr.setStyle({'background':'none'});
					});
				},
				onDrag: function() {
					document.body.style.overflowX = "hidden";
				}
			}
		);
		e.observe('mouseover',function(){
			e.addClassName('rowHover').setStyle({cursor:'pointer'});			

		});
		e.observe('mouseout',function(){
			e.removeClassName('rowHover');			
		});
		new Tip(e.down('li.col1 a'),'Click to view user profile',{
			hook: false,
			effect: 'appear'
		});
		new Tip(e.down('li.col2 a'),'Click to View / Close your sent message',{
			hook: false,
			effect: 'appear'
		});
	});

	// Enable organize category rows to be droppable
	$$('ol#table_organize-suggestions>li').each(function(e){
		Droppables.add(e,
			{
				hoverclass: 'dropRowHover',
				onDrop: function(element,dropon,event) {
					//alert("you are on dropping email to mailbox");
					//var mail_id = element.down('li.row ul.rowCols li.col1').id;
					//var mailbox_id = dropon.id.substr(9);					
					//element.remove();
					//new Ajax.onlinenow.gif('results_organize-suggestions', 'forwardtomailbox?mail_id='+mail_id+'&mailbox_id='+mailbox_id+'',{ 
					//	method: 'get', asynchronous: true});					
					archiveCategory(element,dropon,event);
				}
			}
		);
	});

	// Enable delete suggestion droppable area
	Droppables.add('btn_trash-suggestion',
		{
			hoverclass:'deleteHover',
			onDrop: function(element, dropon, event)
			{
				
			//var messageid = element.down('li.row ul.rowCols li.col1').id;
			//alert("initUseraccount id = "+messageid);
				
				if(confirm("Are you sure you would like to remove the message:\n\n"+element.down('li.row ul.rowCols li.col2 a').innerHTML)) {
					//var parentList = element.up('ul.subSuggestionLists');
					//var parentCompanyList = parentList.up('li.row');
					var messageid = element.down('li.row ul.rowCols li.col1').id;
					element.remove();				
					new Ajax.Request('deletesentmessage?messageID='+messageid,{ method: 'get', asynchronous: true}); 
								
						
					/*if(parentList.getElementsBySelector('li.subRow').length == 0) {
						new Effect.Opacity(parentCompanyList,{duration: 0.5, from: 1.0, to: 0.0});
						new Effect.BlindUp(parentCompanyList,{
							duration: 0.5,
							delay: 0.5,
							afterFinish: function(){
								parentCompanyList.remove();
							}
						});
					}*/
				}
			}
		}
	);
}


function initMailAccount() {	

	// Enable rollover coloring for result lists
	$$("#results_my-suggestions .draggableLists li.row ul.rowCols").each(function(e){	
		e.observe('mouseover',function(){
			e.addClassName('rowHover').setStyle({cursor:'pointer'});
		});
		e.observe('mouseout',function(){
			e.removeClassName('rowHover');			
		});
		e.observe('click',function(){
			var subSuggestions = e.next('ul.subSuggestionLists');
			Effect.toggle(subSuggestions,'blind',{duration:0.5});
			if(subSuggestions.getStyle('display') == 'block') {
				e.up('li.row').setStyle({'border-color':'#fff'});
				new Effect.Opacity(e.down('li.col2'),{
					duration:0.5,
					from:0.0,
					to:1.0
				});
				new Effect.Opacity(e.down('li.col3'),{
					duration:0.5,
					from:0.0,
					to:1.0
				});				
			} else {
				e.up('li.row').setStyle({'border-color':'#f2f2f2'});
				new Effect.Opacity(e.down('li.col2'),{
					duration:0.5,
					from:1.0,
					to:0.0
				});
				new Effect.Opacity(e.down('li.col3'),{
					duration:0.5,
					from:1.0,
					to:0.0
				});
			}
		});
	});

	// Enable draggable sub-rows
	$$('ol#table_results_my-suggestions li.row ul.rowCols').each(function(e) {
		new Draggable(e,{
				revert: true,
				zindex: 1000,
				onStart: function() {
					e.setStyle({'border-color':'#ffdf61'});
					e.descendants('li').each(function(slr){
						slr.setStyle({'background':'#fefabf'});
					});
				},
				onEnd: function() {
					e.setStyle({'border-color':'#fff'});
					document.body.style.overflowX = "auto";
					e.descendants('li').each(function(slr){
						slr.setStyle({'background':'none'});
					});
				},
				onDrag: function() {
					document.body.style.overflowX = "hidden";
				}
			}
		);
		e.observe('mouseover',function(){
			e.addClassName('rowHover').setStyle({cursor:'pointer'});

		});
		e.observe('mouseout',function(){
			e.removeClassName('rowHover');			
		});
		new Tip(e.down('li.col1 a'),'View this message',{
			hook: false,
			effect: 'appear'
		});
		new Tip(e.down('li.col2 a'),'View this message',{
			hook: false,
			effect: 'appear'
		});
	});

	// Enable organize category rows to be droppable
	$$('ol#table_organize-suggestions>li').each(function(e){
		Droppables.add(e,
			{
				hoverclass: 'dropRowHover',
				onDrop: function(element,dropon,event) {
					//alert("you are on dropping email to mailbox");
					//var mail_id = element.down('li.row ul.rowCols li.col1').id;
					//var mailbox_id = dropon.id.substr(9);					
					//element.remove();
					//new Ajax.onlinenow.gif('results_organize-suggestions', 'forwardtomailbox?mail_id='+mail_id+'&mailbox_id='+mailbox_id+'',{ 
					//	method: 'get', asynchronous: true});					
					archiveCategory(element,dropon,event);
				}
			}
		);
	});

	// Enable delete suggestion droppable area
	Droppables.add('btn_trash-suggestion',
		{
			hoverclass:'deleteHover',
			onDrop: function(element, dropon, event)
			{
				
			//var messageid = element.down('li.row ul.rowCols li.col1').id;
			//alert("initUseraccount id = "+messageid);
				
				if(confirm("Are you sure you would like to remove the message:\n\n"+element.down('li.row ul.rowCols li.col1 a').innerHTML)) {
					//var parentList = element.up('ul.subSuggestionLists');
					//var parentCompanyList = parentList.up('li.row');
					var messageid = element.down('li.row ul.rowCols li.col1').id;
					element.remove();				
					new Ajax.Request('deletemessage?messageID='+messageid,{ method: 'get', asynchronous: true}); 
								
						
					/*if(parentList.getElementsBySelector('li.subRow').length == 0) {
						new Effect.Opacity(parentCompanyList,{duration: 0.5, from: 1.0, to: 0.0});
						new Effect.BlindUp(parentCompanyList,{
							duration: 0.5,
							delay: 0.5,
							afterFinish: function(){
								parentCompanyList.remove();
							}
						});
					}*/
				}
			}
		}
	);

	$('btn_add-suggestion').href = "javascript:void(null);";
	$('btn_add-suggestion').observe('click',function(e){
		var folderList = $('table_organize-suggestions');
		var lastRow = folderList.immediateDescendants().last();
				
		var newCatID = lastRow.readAttribute('id').substr(9).succ();


		var newRow = document.createElement('LI');
			//newRow.className = "row";
			newRow.id = "category_"+newCatID;
			newRow.style.margin = "0px";
			newRow.style.padding = "0px";
		var newRowCols = document.createElement('UL');
			//newRowCols.className = "rowCols";
			newRowCols.style.margin = "0px";
			newRowCols.style.padding = "0px";
		var newCol1 = document.createElement('LI');
			newCol1.className = "col1";
		var newEditField = document.createElement('INPUT');
			newEditField.maxLength = "30";
			newEditField.id = "edit_field_"+newCatID;
		var newCol1Link = document.createElement('A');
			newCol1Link.href = "#";
			newCol1Link.innerHTML = "";

/*
		var newCol2 = document.createElement('LI');
			newCol2.className = "col2";
			newCol2.innerHTML = "Drag messages here to folders and archive them";
*/
		newCol1.appendChild(newCol1Link);
		newCol1.appendChild(newEditField);
		newRowCols.appendChild(newCol1);
	
//	newRowCols.appendChild(newCol2);
		newRow.appendChild(newRowCols);
		folderList.appendChild(newRow);


		var editField = $('edit_field_'+newCatID);
			editField.focus();


var ok = document.createElement('A');
ok.id = "return_"+"9999";//groupID;
ok.className = "btn_ok";
ok.innerHTML = "ok";
ok.style.color = "#444";
ok.style.zIndex = "9999";
//alert(newEditField.id);
var okCommandString = "javascript:addNewMailBoxKYOK('" + newCatID +"')";
ok.href = okCommandString;

var cancel = document.createElement('A');
cancel.id = "cancel_"+"9999";//groupID;
cancel.className = "btn_cancel";
cancel.innerHTML = "cancel";
cancel.style.color = "#444";
cancel.style.zIndex = "9999";
var cancelCommandString = "javascript:window.location='/users/myinbox';";
cancel.href = cancelCommandString;
//newRow.appendChild(ok);
//newRow.appendChild(cancel);


		editField.observe('keypress',function(event){
			if(event.keyCode == Event.KEY_ESC) {		
				//editField.up('li.row').remove();
				editField.up('li').remove();
			}
			if(event.keyCode == Event.KEY_RETURN) {				
				//editField.Previous('a').innerHTML = editField.getValue()+' (<span class="amount">0</span>)';				
				addNewMailBoxKY(editField.getValue());
				Droppables.add(editField.up('li.row'),
					{
						hoverclass: 'dropRowHover',
						onDrop: function(element,dropon,event) {	
							//alert("aaa");						
							archiveCategory(element,dropon,event);
						}
					}
				);
				editField.remove();
			}
		});
	});
}

function addNewMailBoxKYOK(editField){
	var element = $('edit_field_'+editField).getValue();
	window.location = 'addnewmailbox?boxname='+element+'';
}

function addNewMailBoxKY(element){	
	//new Ajax.Request('addnewmailbox?boxname='+element+'',{ method: 'get', asynchronous: true});
	window.location = 'addnewmailbox?boxname='+element+'';
}


function archiveCategory(element,dropon,event) {
	//alert("bbb");
	var mail_id = element.down('li.row ul.rowCols li.col1').id;
	var mailbox_id = dropon.id.substr(9);	

//	new Ajax.Request('forwardtomailbox?mail_id='+mail_id+'&mailbox_id='+mailbox_id+'',{ method: 'get', asynchronous: true});	
	

	new Ajax.Request('forwardtomailbox?mail_id='+mail_id+'&mailbox_id='+mailbox_id+'',{ 
		method: 'get',
		onComplete: function(){
			setTimeout("", 1000);
			location.href='myinbox';
			}
	}); //, asynchronous: true});

	//alert("you got it element id = "+element.down('li.row ul.rowCols li.col1').id);
	//alert("you got it dropon id = "+dropon.id.substr(9));

/*
	//alert("you got it element id = "+element.down('li.row ul.rowCols li.col1').id);
	//alert("you got it dropon id = "+dropon.id.substr(9));	
	new Ajax.Request('forwardtomailbox', {method:'post', postBody:escape('thisvar=true&thatvar=Howdy')});
	new Ajax.Request('forwardtomailbox',{
		method: 'post',
		parameters: {
			EID: element.down('li.row ul.rowCols li.col1').id,
			categoryID: dropon.id.substr(9)
		},
		onComplete: function(data) {
			var newAmount = dropon.down('.amount').innerHTML.succ();
			dropon.down('.amount').innerHTML = newAmount;
			var parentList = element.up('ul.subSuggestionLists');
			var parentCompanyList = parentList.up('li.row');
			element.remove();
			if(parentList.getElementsBySelector('li.subRow').length == 0) {
				new Effect.Opacity(parentCompanyList,{duration: 0.5, from: 1.0, to: 0.0});
				new Effect.BlindUp(parentCompanyList,{
					duration: 0.5,
					delay: 0.5,
					afterFinish: function(){
						parentCompanyList.remove();
					}
				});
			}
		}
	});
*/

}




function initSigninBox() {
	if($('link_sign-in') != null) {
		$('link_sign-in').href = "javascript:void(null);";
		Event.observe('link_sign-in','click',function(){
			if($('box_sign-in') == undefined) {
				new Ajax.onlinenow.gif('master_container','/logins/signin_box',{
					method: 'get',
					insertion: Insertion.Bottom,
					onComplete: function() {
						rollAssign();
						new Draggable('box_sign-in',{
								zindex: 999,
								handle: 'h4'
							}
						);
						Effect.SlideDown('box_sign-in',{duration:0.5});
						Effect.Appear('box_sign-in',{duration:0.5});
					}
				});
			}
		});
	}
}

function getRandomString()
{
    return new Date().getTime().toString();
}
function getRandomQSAppend()
{
    return ("&random=" + getRandomString());
}

function initSuggestionInbox() {
	$$("#results_my-suggestions .draggableLists li.subRow ul.subRowCols").each(function(e){
		e.observe('mouseover',function(){
			e.addClassName('rowHover').setStyle({cursor:'pointer'});
		});
		e.observe('mouseout',function(){
			e.removeClassName('rowHover');
		});
		e.observe('click',function(){
			function updateMessage() {
				new Ajax.onlinenow.gif('message_box','elements/suggestion_message.html',{
					method: 'get',
					onComplete: function() {
						opDelay = 0.5;
						if($('message_box').getStyle('display') == "none") {
							Effect.BlindDown('message_box',{duration:0.5});
							opDelay = 0.0;
						}
						new Effect.Opacity('message_box',{
							duration: 0.5,
							from: 0.0,
							to: 1.0,
							delay: opDelay,
							beforeStart: function(effect){
								effect.element.style.background = "#ffffff";
							},
							afterFinish: function(effect){
								effect.element.style.background = "none";
							}
						});
						$('link_reply-message').observe('click',function(){
							new Effect.toggle('reply_box','blind',{
								duration: 0.5,
								afterFinish: function(){
									if($('reply_box').getStyle('display') == "block") {
										new Effect.ScrollTo('reply_box',{
											duration: 0.5,
											afterFinish: function() {
												$('new-message_contents').focus();
											}
										});
									}
								}
							});
						});
						$('link_cancel-message').observe('click',function(){
							new Effect.BlindUp('reply_box',{
								duration: 0.5
							});
						});
					}
				});
			}
			if($('message_box').getStyle('display') == "block") {
				new Effect.Opacity('message_box',{
					duration: 0.5,
					from: 1.0,
					to: 0.0,
					afterFinish: updateMessage()
				});
			} else {
				updateMessage();
			}
		});
	});
}



/*
function initCompanyProfile() {
	var pad = (170 - $('logo_img').getDimensions()['height'])/2;
	$('logo_img').setStyle({
		'paddingTop': pad+'px'
	});

	$('link_make-a-suggestion').href = "javascript:void(null);";
	$('link_make-a-suggestion').observe('click',function(){
		if(animating == false) {
			animating = true;
			if($('box_our-suggestion') != undefined) {
				new Effect.DropOut('box_our-suggestion',{
					duration: 0.5,
					afterFinish: function(){
						$('box_our-suggestion').remove();
						makeASuggestion('make-suggestion',Insertion.Bottom);
					}
				})
			} else {
				makeASuggestion('make-suggestion',Insertion.Bottom);
			}
		}
	});

	$('link_cancel-suggestion').href = "javascript:void(null);";
	$('link_cancel-suggestion').observe('click',function(){
		if(animating == false) {
			animating = true;
			new Effect.BlindUp('suggestion_form_container');
			new Effect.BlindDown('make_suggestion_link_holder');
			new Effect.Fade('nav_cancel-suggestion',{
				afterFinish: function(){
					$('suggestion_form_container').remove();
					animating = false;
				}
			});
		}
	});

	$('add_address-book').down('a').href = "javascript:void(null);";
	$('add_address-book').down('a').observe('click',function(){
		new Ajax.onlinenow.gif('address_book_status','elements/add_address_book.html',{
			method: 'post',
			parameters: {
				userID: userID,
				companyID: companyID
			},
			insertion: Insertion.Top,
			onSuccess: function(data){
				new Effect.Appear('address_book_status',{duration:0.5});
			}
		});
	});
	new Ajax.Request('elements/address_book_check.html',{
		method: 'post',
		parameters: {
			userID: userID,
			companyID: companyID
		},
		onSuccess: function(data) {
			if(data.responseText == "true") {
				$('address_book_status').innerHTML = "Already in address book";
				$('address_book_status').setStyle({display:'block'});
			}
		}
	});
}
*/



function makeASuggestion(loc,how) {
	new Effect.BlindUp('make_suggestion_link_holder');
	new Effect.Appear('nav_cancel-suggestion',{
		duration:0.5,
		beforeStart: function(event){
			event.element.setStyle({'background':'#fff'});
		},
		afterFinish: function(event){
			event.element.setStyle({'background':'none'});
		}
	});
	if($('suggestion_form_container') == undefined && animating == true) {
		new Ajax.onlinenow.gif(loc,'elements/make_suggestion.html',{
			method: 'get',
			insertion: how,
			onComplete: function() {
				rollAssign();
				new Effect.BlindDown('suggestion_form_container');
				new Effect.Appear('suggestion_form_container',{
					afterFinish:function(){
						animating = false;
					}
				});
				$('field_companyID').value = companyID;
			}
		});
	}
}




function submitInlineLogin(formElem) {
	Element.extend(formElem);
	var emailField = $('field_Semail');
	var passField = $('field_Spassword');
	var errors = false;
	var message = "There were errors in your form submission:\n\n";

	if(emailField.present()) {
		if(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(emailField.getValue())) {
			// Passed
		} else {
			// Failed
			errors = true;
			message+= "- Please enter a valid email address\n";
		}
	} else {
		errors = true;
		messasge+= "- You did not enter an email\n";
	}
	if(passField.present()) {
		if(passField.getValue().length < 6) {
			errors = true;
			message+= "- You did not enter a valid password\n";
		}
	} else {
		errors = true;
		message+= "- You did not enter a password\n"
	}

	if(errors == true) {
		alert(message);
	} else {
	
	//new Effect.Appear('kky',{duration: 0.5});
	var emailField = $('field_Semail').value;
	var passField = $('field_Spassword').value;
	// Validation passed, process AJAX login
	
	new Ajax.onlinenow.gif('login','checklogin?email='+emailField+'&pass='+passField, {
		method: 'GET',
		onComplete: function(data) {						
			new Effect.Appear('choose_submit_identity',{
				duration:0.5,
				beforeStart: function(event){						
					new Element.setOpacity(event.element,0);
				}
			});							
			//$('make-suggestion_from').remove();
		}
	});
		
	}
}



function createUserGroupCancelKY(id)
{
    var editField = document.getElementById(id);
    editField.up('li.row').remove();
	document.location = "/welcome/welcome";
	
}
function createUserGroupOkKY(id)
{
	alert(id);
    var editField = document.getElementById(id);
    document.location = "?desc=" + editField.getValue().toString() + getRandomQSAppend();
}
function addUserGroupKY(){
//Start: adding list

	$('btn_add-usergroup').href = "javascript:void(null);";
	$('btn_add-usergroup').observe('click',function(e){		
		var folderList = $('users_group_list');

		var newCatID = "0";
		if(folderList.immediateDescendants().length > 0)
		{
		    var lastRow = folderList.immediateDescendants().last();
		    //newCatID = lastRow.readAttribute('id').substr(6).succ();
		    newCatID = parseInt(lastRow.readAttribute('id').substr(6))+1;		    
		}
		
		var newRow = document.createElement('LI');
			newRow.className = "row";
			newRow.id = "group_"+newCatID;
		var newRowH = document.createElement('H4');
			newRowH.className = "group_label";
		var newRowHLink = document.createElement('A');
			newRowHLink.href = "#";
			newRowHLink.innerHTML = "";
			
		var newEditField = document.createElement('INPUT');
			newEditField.maxLength = "40";
			newEditField.id = "edit_field_"+newCatID;	
			newEditField.style.position="absolute";
			newEditField.style.left = "40px";
			newEditField.style.top = "5px";



		newRowH.appendChild(newRowHLink);
		newRowH.appendChild(newEditField);
		newRow.appendChild(newRowH);
		folderList.appendChild(newRow);

		var ok = document.createElement('A');
		ok.id = "return_"+"999";//groupID;
		ok.className = "btn_ok";
		ok.innerHTML = "ok";
		ok.style.color = "#444";
		ok.style.zIndex = "200";
		
		//alert(newEditField.id);
        var okCommandString = "javascript:createUserGroupOkKY('" + newEditField.id +"');";
		ok.href = okCommandString;
		
		var cancel = document.createElement('A');
		cancel.id = "cancel_"+"999";//groupID;
		cancel.className = "btn_cancel";
		cancel.innerHTML = "cancel";
		cancel.style.color = "#444";
		cancel.style.zIndex = "200";
        //var cancelCommandString = "javascript:document.location='?random="+ getRandomQSAppend()+"';";
        var cancelCommandString = "javascript:createUserGroupCancelKY('" + newEditField.id +"');";
		cancel.href = cancelCommandString;

		newRowH.appendChild(ok);
		newRowH.appendChild(cancel);




/*
		var editField = $('edit_field_'+newCatID);
		editField.focus();
		editField.observe('keypress',function(event){
			if(event.keyCode == Event.KEY_ESC) {
				editField.up('li.row').remove();
			}
			if(event.keyCode == Event.KEY_RETURN) {
				editField.Previous('a').innerHTML = editField.getValue()+' (<span class="amount">0</span>)';
				Droppables.add(editField.up('li.row'),
					{
						hoverclass: 'dropRowHover',
						onDrop: function(element,dropon,event) {
							
							archiveCategory(element,dropon,event);
						}
					}
				);
				editField.remove();			}
		});
	});
*/	


		var editField = $('edit_field_'+newCatID);
			editField.focus();

		editField.observe('keypress',function(event){
			if(event.keyCode == Event.KEY_ESC) {
				//folderList.immediateDescendants().last().remove();						
				editField.up('li.row').remove();
			}
			if(event.keyCode == Event.KEY_RETURN) {
			    document.location = "?desc=" + editField.getValue().toString() + getRandomQSAppend();


//			alert("before request");
//				new Ajax.Request('addusertags',{
//					method:'get',
//					parameters: {
//						desc: editField.getValue().toString()
//					},
//					onComplete: function(){
//			alert("in request");
//        				editField.Previous('a').innerHTML = editField.getValue()+' (<span class="amount">0</span>)';
//					}
//				});
//			
//			alert("after request");
//				Droppables.add(editField.up('li.row'),
//					{
//						hoverclass: 'dropRowHover',
//						onDrop: function(element,dropon,event) {
//							archiveCategory(element,dropon,event);
//						}
//					}
//				);
//				editField.remove();
			}
		});
	});
	
//END adding list
}

function initCompanyAccount() {
	$$('#users_group_list li').each(function(e){											 
		Droppables.add(e,
			{   
				hoverclass:'dropRowHover',
				onHover:function(){
					e.down('a.editGroupLabel').setStyle({display:'none'});					
				},
				onDrop:function(element, dropon, event)
				{   					
					// Place your function to categorize the suggestion here
					//alert("You dropped elementID: "+element.id.substr(11)+" on categoryID: "+dropon.id.substr(6));
					location.href='addtofolder?tid='+element.id.substr(11)+'&folderid='+dropon.id.substr(6)+'';
					//new Ajax.Request('addtofolder?messageid='+element.id.substr(11)+'&folderid='+dropon.id.substr(6),{
					//method:'GET'});
					
					//	element.remove();
				}
			}
		);
		


	});


	$$('a.editGroupLabel').each(function(e){
		editGroupLabel(e);
	});

	$$('h4.group_label a.groupLabelLink').each(function(e){
		e.observe('mouseover',function(){
			e.up('h4').next('a.editGroupLabel').setStyle({display:'block'});
			e.setStyle({'background-position':'0 0'});
		});
		e.observe('mouseout',function(){
			e.up('h4').next('a.editGroupLabel').setStyle({display:'none'});
			e.setStyle({'background-position':'0 -36px'});
		});
	});

	//welcomepage topright corner
	$('group_check-all').setStyle({display:'block'});
	$('group_check-all').observe('click',function(event){
		Event.element(event).blur();
		if(Event.element(event).getValue() == "on") {
			$$('#table_new-company-suggestions input[type=checkbox]').each(function(e){
				e.checked = true;
			});
		} else {
			$$('#table_new-company-suggestions input[type=checkbox]').each(function(e){
				e.checked = false;
			});
		}
	});
	$$('.draggableLists li.row').each(function(e){	
		new Tip(e.down('li.col1 a'),'Visit the '+e.down('li.col1 a').innerHTML+' profile page',{
		hook: false,
		effect: 'appear'
		});											   
		new Draggable(e,{
				revert: true,
				zindex: 1000,
				onStart: function() {
					e.setStyle({'border-color':'#ffdf61'});
					e.descendants('li').each(function(slr){
						slr.setStyle({'background':'#fefabf'});
					});
					
				},
				onEnd: function() {
					e.setStyle({'border-color':'#fff'});
					document.body.style.overflowX = "auto";
					e.descendants('li').each(function(slr){
						slr.setStyle({'background':'none'});						
					});
					
				},
				onDrag: function() {									
					document.body.style.overflowX = "hidden";
					
				}
			}
		);
		e.observe('mouseover',function(){
			e.addClassName('rowHover').setStyle({cursor:'pointer'});
						
		});
		e.observe('mouseout',function(){
			e.removeClassName('rowHover');
			
		});
	});
	
}




function editGroupLabel(e) {
	e.setStyle({display:'none'});
	e.observe('mouseover',function(){
		e.Previous('h4').down('a.groupLabelLink').setStyle({'background-position':'0 0'});
		e.setStyle({display:'block'});
	});
	e.observe('mouseout',function(){
		e.Previous('h4').down('a.groupLabelLink').setStyle({'background-position':'0 -36px'});
		e.setStyle({display:'none'});
	});
	e.href = "javascript:void(null);";
	e.observe('click',function(){
		createGroupEditField(e);
	});
}




function createGroupEditField(e) {
	var parentLI = e.up('li');
	var groupID = parentLI.readAttribute('id').substr(6);
	var edit_input = document.createElement('INPUT');
		edit_input.id = "edit_field_"+groupID;
		edit_input.className = "editGroupField";
		edit_input.maxLength = "20";
		edit_input.value = e.Previous('h4').down('a.groupLabelLink').down('.labelName').innerHTML;
	var ok = document.createElement('A');
		ok.id = "return_"+groupID;
		ok.className = "btn_ok";
		ok.innerHTML = "ok";		
		//ok.href = "javascript: createUserGroupOkKY('"+edit_input.id+"');";
		//ok.href = "javascript:void(null);";
		
		ok.observe('click',function(){
			submitGroupLabel(groupID);
	});


	var cancel = document.createElement('A');
		cancel.id = "cancel_"+groupID;
		cancel.className = "btn_cancel";
		cancel.innerHTML = "cancel";
		cancel.href = "javascript:void(null);";		

	parentLI.appendChild(edit_input);
	parentLI.appendChild(ok);
	parentLI.appendChild(cancel);

	e.Previous('h4.group_label').setStyle({display:'none'});
	e.setStyle({display:'none'});

	//okBtn = $('return_'+groupID);
	//okBtn.observe('click',function(){
	//	submitGroupLabel(groupID);
	//});

	editField = $('edit_field_'+groupID);
	editField.observe('keypress',function(event){
		if(event.keyCode == Event.KEY_ESC) {
			editField.Previous('h4.group_label').setStyle({display:'block'});
			editField.next('a').remove();
			editField.next('a').remove();
			editField.remove();
		}
		if(event.keyCode == Event.KEY_RETURN) {
			submitGroupLabel(groupID);
		}
	});
	editField.focus();

	cancelBtn = $('cancel_'+groupID);
	cancelBtn.observe('click',function(){
		editField.Previous('h4.group_label').setStyle({display:'block'});
		editField.next('a').remove();
		editField.next('a').remove();
		editField.remove();
	});
}




function initCreateCompanyPage() {
	$$('ol.radioList li input').each(function(e){
		if(e.checked == true) {
			e.up('label').setStyle({background:'#e1eef4'});
		}
		Event.observe(e,'click',function(){
			if(e.checked == true) {
				e.blur();
				$$('ol.radioList li label').each(function(r){
					r.setStyle({background:'#fff'});
				});
				e.up('label').setStyle({background:'#e1eef4'});
			}
		});
	});
}





// This function is called to write the new label for user groups in the user
// welcome page. If the group is new, the value for gID will be a string "new"
// instead of an integer for the group ID. An exception should be made in the
// backend processor to accomodate this.
function submitGroupLabel(gID) {

	var editor = $('edit_field_'+gID);
	var newLabel = editor.getValue();

	// Specify the file that will do the DB processing to update the group name
	var url = '/welcome/welcome?action=updatelabel';

	new Ajax.Request(url,{
		method: 'post',
		parameters: {
			id: gID,
			description: newLabel
		},
		onComplete: function(data) {
			if(gID == "new") {
				alert(data);
			}
			field = $('edit_field_'+gID);
			field.Previous('h4.group_label').down('.labelName').innerHTML = newLabel;
			field.Previous('h4.group_label').setStyle({display:'block'});
			field.next('a').remove();
			//field.next('a').remove();
			field.remove();
		}
	});
}


function slideUpDown(divname){	
	if($(divname).getStyle('display')=="none")
	{	new Effect.SlideDown(divname, {duration: 0.5});		
	}
	else
	{		
		new Effect.BlindUp(divname, {duration: 0.5});	
		//new Effect.Fade(divname, {duration: 0.5});			
	}
}

function showHalfFadeAll(divname){	
	if($(divname).getStyle('display')=="none")
	{	new Effect.Appear(divname, {duration: 1.0, from:0.0, to:0.5});		
	}
	else
	{
		new Effect.Fade(divname, {duration: 1.0});	
	}
}
function showSlide1(divname){	
	if($(divname).getStyle('display')=="none")
	{	new Effect.SlideDown(divname, {duration: 1.0});		
	}
	else
	{
		new Effect.SlideUp(divname, {duration: 1.0});	
	}
}
function showFade1(divname){	
	if($(divname).getStyle('display')=="none")
	{	new Effect.Appear(divname, {duration: 0.5});		
	}
	else
	{ 
		new Effect.Fade(divname, {duration: 0.5});	
	}
}
function showFade1NoTime(divname){	
	if($(divname).getStyle('display')=="none")
	{	new Effect.Appear(divname, {duration: 0.0});		
	}
	else
	{ 
		new Effect.Fade(divname, {duration: 0.0});	
	}
}

function showFadeSecond(showArea, fadeArea, sec){		
	new Effect.Fade(fadeArea, {duration: sec});	
	new Effect.Appear(showArea, {duration: sec});
}

function showFade(showArea, fadeArea){		
	new Effect.Fade(fadeArea, {duration: 0.0});	
	new Effect.SlideDown(showArea, {duration: 0.30});	
	new Effect.Appear(showArea, {duration: 0.30});
}

function showFadeNoTime(showArea, fadeArea){		
	new Effect.Fade(fadeArea, {duration: 0.0});	
	new Effect.Appear(showArea, {duration: 0.0});
}

function showFadeDiv(divname){	
	if($(divname).getStyle('display')=="none")
	{	new Effect.Appear(divname, {duration: 0.30});		
	}
	else if($(divname).getStyle('display')=="block")
	{ 
		new Effect.Fade(divname, {duration: 0.30});	
	}
}


/*

function initOurminglelink() {
	$('link_make-a-suggestion').href = "javascript:void(null);";
	$('link_make-a-suggestion').observe('click',function(){
		if($('box_our-suggestion') == undefined) {
			if($('suggestion_form_container') != undefined) {
				if(animating == false) {
					animating = true;
					new Effect.BlindUp('suggestion_form_container',{duration:0.5});
					new Effect.BlindDown('make_suggestion_link_holder',{duration:0.5});
					new Effect.Fade('nav_cancel-suggestion',{
						duration: 0.5,
						afterFinish: function(){
							$('suggestion_form_container').remove();
							animating = false;
							openOurminglelink();
						}
					});
				}
			} else {
				openOurminglelink();
			}
		}
	});
}




function openOurminglelink() {
	new Ajax.onlinenow.gif('master_container','elements/our_suggestion_box.html',{
		method: 'get',
		insertion: Insertion.Bottom,
		onComplete: function() {
			new Draggable('box_our-suggestion',{
					zindex: 999,
					handle: 'our_suggestion_title_handle'
				}
			);
			rollAssign();
			new Effect.SlideDown('box_our-suggestion',{duration:0.5});
			new Effect.Appear('box_our-suggestion',{duration:0.5});
		}
	});
}

*/


function initSuggestionPage() {
	$('btn_reply').href = "javascript:void(null);";
	$('btn_reply').observe('click',function(){
		new Effect.toggle('reply_box','blind',{
			duration:0.5,
			beforeStart: function() {
				if($('forward_suggestion').getStyle('display') == "block") {
					new Effect.BlindUp('forward_suggestion',{duration:0.5});
				}
			},
			afterFinish: function(effect){
				if(effect.element.getStyle('display') == "block") {
					$('new-message_contents').focus();
				}
			}
		});
	});
	$('btn_forward').href = "javascript:void(null);";
	$('btn_forward').observe('click',function(){
		new Effect.toggle('forward_suggestion','blind',{
			duration:0.5,
			beforeStart: function() {
				if($('reply_box').getStyle('display') == "block") {
					new Effect.BlindUp('reply_box',{duration:0.5});
				}
			}
		});
	});
	$('link_cancel-message').href = "javascript:void(null);";
	$('link_cancel-message').observe('click',function(){
		new Effect.BlindUp('reply_box',{duration:0.5});
	});
	new Tip($('help_make-private'),'Coming Soon!',{
		hook: false,
		effect: 'appear'
	});
	new Tip($('help_make-featured'),'Coming Soon!',{
		hook: false,
		effect: 'appear'
	});

	var msgBox = $('new-message_contents');
	$$('#pre-built-responses a.pre-built-response').each(function(e){
		e.observe('click',function(){
			new Ajax.Request('elements/get_response.html',{
				method: 'post',
				parameters: {
					responseID: e.readAttribute('id').substr(11)
				},
				onSuccess: function(data) {
					msgBox.value = msgBox.getValue()+(data.responseText);
				}
			});
		});
	});
}




function initManageGroups() {
	// Enable rollover coloring for result lists
	$$(".draggableLists li.row").each(function(e){
		new Draggable(e,{
				revert: true,
				zindex: 1000,
				onStart: function() {
					e.setStyle({'border-color':'#ffdf61'});
					e.descendants('li').each(function(slr){
						slr.setStyle({'background':'#fefabf'});
					});
				},
				onEnd: function() {
					e.setStyle({'border-color':'#fff'});
					document.body.style.overflowX = "auto";
					e.descendants('li').each(function(slr){
						slr.setStyle({'background':'none'});
					});
				},
				onDrag: function() {
					document.body.style.overflowX = "hidden";
				}
			}
		);
		e.observe('mouseover',function(){
			e.addClassName('rowHover').setStyle({cursor:'pointer'});
		});
		e.observe('mouseout',function(){
			e.removeClassName('rowHover');
		});
		new Tip(e.down('li.col1 a'),'Edit this group',{
			hook: false,
			effect: 'appear'
		});
	});

	// Enable delete suggestion droppable area
	Droppables.add('btn_trash-group',
		{
			hoverclass:'deleteHover',
			onDrop: function(element, dropon, event)
			{
				// Place AJAX function here to delete the suggestion
				if(confirm("Are you sure you would like to remove the category:\n\n"+element.down('li.col1 a').innerHTML)) {
					element.remove();
				}
			}
		}
	);
}




function initManageResponses() {
	// Enable rollover coloring for result lists
	$$(".draggableLists li.row").each(function(e){
		new Draggable(e,{
				revert: true,
				zindex: 1000,
				onStart: function() {
					e.setStyle({'border-color':'#ffdf61'});
					e.descendants('li').each(function(slr){
						slr.setStyle({'background':'#fefabf'});
					});
				},
				onEnd: function() {
					e.setStyle({'border-color':'#fff'});
					document.body.style.overflowX = "auto";
					e.descendants('li').each(function(slr){
						slr.setStyle({'background':'none'});
					});
				},
				onDrag: function() {
					document.body.style.overflowX = "hidden";
				}
			}
		);
		e.observe('mouseover',function(){
			e.addClassName('rowHover').setStyle({cursor:'pointer'});
		});
		e.observe('mouseout',function(){
			e.removeClassName('rowHover');
		});
		new Tip(e.down('li.col1 a'),'Edit this response',{
			hook: false,
			effect: 'appear'
		});
	});

	// Enable delete suggestion droppable area
	Droppables.add('btn_trash-group',
		{
			hoverclass:'deleteHover',
			onDrop: function(element, dropon, event)
			{
				// Place AJAX function here to delete the suggestion
				if(confirm("Are you sure you would like to remove the response:\n\n"+element.down('li.col1 a').innerHTML)) {
					element.remove();
				}
			}
		}
	);
}




function initEditGroup() {
	new Ajax.onlinenow.gif('assigned_resources','elements/resource_list.html',{
		onComplete: function() {
			$$('a.link_resource-remove').each(function(e){
				e.observe('click',function(){
					new Ajax.Request('elements/remove_resource.html',{
						method: 'post',
						parameters: {
							resourceID: e.readAttribute('rel').substr(9),
							groupID: $F('field_group_id')
						},
						onException: function(data,excp) {
							alert(excp);
						},
						onComplete: function(){
							var parentBlock = e.up('ul.resource');
							new Effect.BlindUp(parentBlock,{duration:0.5});
							new Effect.Fade(parentBlock,{
								duration:0.5,
								afterFinish: function(event) {
									event.element.remove();
								}
							});
						}
					});
				});
			});
		}
	});
	$('link_open-add-another-resource').href = "javascript:void(null);";
	$('link_open-add-another-resource').observe('click',function(){
		if($('assign_resource') == undefined) {
			new Ajax.onlinenow.gif('assigned_resources','elements/add_resource_list.html',{
				method: 'get',
				insertion: Insertion.Before,
				onComplete: function() {
					new Effect.BlindDown('assign_resource',{duration:0.5});
					$('link_cancel-add-another-resource').href = "javascript:void(null);";
					$('link_cancel-add-another-resource').observe('click',function(){
						new Effect.BlindUp('assign_resource',{
							duration:0.5,
							afterFinish: function(event) {
								event.element.remove();
							}
						});
					});
					$('link_add-another-resource').href = "javascript:void(null);";
					$('link_add-another-resource').observe('click',function(){
						new Ajax.onlinenow.gif('assigned_resources','elements/resource_list.html',{
							method: 'post',
							parameters: {
								resourceID: $('resources_unassigned').getValue()
							},
							onComplete: function(){
								new Effect.BlindUp('assign_resource',{
									duration:0.5,
									afterFinish: function(event) {
										event.element.remove();
									}
								});
							}
						});
					});
				}
			});
		}
	});
}




function initMySpotlightSuggestions() {
	$$(".draggableLists li.row").each(function(e){
		e.observe('mouseover',function(){
			e.addClassName('rowHover').setStyle({cursor:'pointer'});
		});
		e.observe('mouseout',function(){
			e.removeClassName('rowHover');
		});
		e.down('li.col6').observe('click',function(){
			var sugCheck = e.down('li.col6 input[type=checkbox]');
			sugCheck.checked = false;
			if(confirm("Are you sure you would like to remove the group:\n\n"+e.down('li.col2 a').innerHTML+" for "+e.down('li.col1 a').innerHTML+"?")) {
				new Ajax.Request('elements/remove_spotlight.html',{
					method:'post',
					parameters: {
						userID: userID,
						suggestionID: sugCheck.getValue()
					},
					onComplete: function(){
						new Effect.BlindUp(e,{duration:0.25});
						new Effect.Fade(e,{
							duration:0.25,
							afterFinish: function(event){
								event.element.remove();
							}
						});
					}
				});
			} else {
				sugCheck.checked = true;
			}
		});
		new Tip(e.down('li.col1'),'Visit the '+e.down('li.col1 a').innerHTML+' profile page',{
			hook: false,
			effect: 'appear'
		});
		new Tip(e.down('li.col2'),'View this suggestion',{
			hook: false,
			effect: 'appear'
		});
		new Tip(e.down('li.col6'),'Remove this suggestion from your spotlight suggestions',{
			hook: false,
			effect: 'appear'
		});
	});
}




/* 
function initAddressBook() {
	$$(".draggableLists li.row").each(function(e){
		e.observe('mouseover',function(){
			//e.addClassName('rowHover').setStyle({cursor:'pointer', width:'550px'});
		});
		e.observe('mouseout',function(){
			e.removeClassName('rowHover');
		});
		var company_name = e.down('li.col1 a').innerHTML;
		new Tip(e.down('li.col1'),'Visit '+company_name+' profile page',{
			hook: false
		});
		new Tip(e.down('li.col2'),'Click to send a new invitation to '+company_name,{
			hook: false
		});
		new Tip(e.down('li.col5'),'Remove '+company_name+' from your address book',{
			hook: false
		});
		e.down('li.col5 input[type=checkbox]').observe('click',function(){
			var addressCheck = e.down('li.col5 input[type=checkbox]');
			if(confirm('Are you sure you would like to remove '+company_name+' from your address book?')) {
				var useraddressID = e.down('li.col5 input[type=checkbox]').value;
				new Ajax.Request('removeaddress?user_address_id='+useraddressID,{
					method:'GET',
						onComplete: function(){
						new Effect.BlindUp(e,{duration:0.25});
						new Effect.Fade(e,{
							duration:0.25,
							afterFinish: function(event){
								event.element.remove();
							}
						});
					}
				});
			} else {
				addressCheck.checked = false;
			}
		});
	});
}
 */

function initAddressBook() {
	$$("tbody tr.listrow").each(function(e){
		e.observe('mouseover',function(){
			//e.addClassName('rowHover').setStyle({cursor:'pointer', width:'550px'});
		});
		e.observe('mouseout',function(){
			e.removeClassName('rowHover');
		});
		var company_name = e.down('td.uname a').innerHTML;

		new Tip(e.down('td.thumbnail'),'Visit '+company_name+'\'s profile page.',{
			hook: false
		});
		new Tip(e.down('td.uname'),'Visit '+company_name+'\'s profile page.',{
			hook: false
		});
	});
}

function initMyDrafts() {
	$$(".draggableLists li.row").each(function(e){
		e.observe('mouseover',function(){
			e.addClassName('rowHover').setStyle({cursor:'pointer'});
		});
		e.observe('mouseout',function(){
			e.removeClassName('rowHover');
		});

		new Draggable(e,{
				revert: true,
				zindex: 1000,
				onStart: function() {
					e.setStyle({'border-color':'#ffdf61'});
					e.descendants('li').each(function(slr){
						slr.setStyle({'background':'#fefabf'});
					});
				},
				onEnd: function() {
					e.setStyle({'border-color':'#fff'});
					document.body.style.overflowX = "auto";
					e.descendants('li').each(function(slr){
						slr.setStyle({'background':'none'});
					});
				},
				onDrag: function() {
					document.body.style.overflowX = "hidden";
				}
			}
		);
		e.down('li.col2').observe('click',function(){
			window.open(e.down('li.col2 a').readAttribute('href'),'_self');
		});
		new Tip(e.down('li.col2'),'Resume editing this draft for '+e.down('li.col2 a').innerHTML,{
			hook: false,
			effect: 'appear'
		});

		Droppables.add('btn_trash-draft',
			{
				hoverclass:'deleteHover',
				onDrop: function(element, dropon, event)
				{
					// Place AJAX function here to delete the suggestion
					if(confirm("Are you sure you would like to delete the draft:\n\n"+element.down('li.col2 a').innerHTML)) {
						element.remove();
					}
				}
			}
		);

		e.down('li.col4 input[type=checkbox]').observe('click',function(){
			var sendViaSMS = e.down('li.col4 input[type=checkbox]');
			new Ajax.Request('elements/update_send_sms.html',{
				method:'post',
				parameters: {
					userID: userID,
					draftID: sendViaSMS.getValue()
				}
			});
		});
	});
}




function initMessageUserAccount() {
	if($('btn_save-to-drafts') != undefined) {
		$('btn_save-to-drafts').setStyle({display:'block'});
		$('btn_save-to-drafts').observe('click',function(){
			$('field_status_id').value = 4;
			if(validateForm($('form_create-a-suggestion'))) {
				$('form_create-a-suggestion').submit();
			}
		});
	}

	if($('field_address-book') != undefined) {
		if($('field_address-book').present()) {
			updateCreateSuggestionCompanyInfo();
		}

		$('field_address-book').observe('change',function(){
			if($('sendto_company_container').getStyle('display') == "block") {
				new Effect.Opacity('sendto_company_container',{
					duration: 0.5,
					from: 1.0,
					to: 0.0,
					afterFinish: updateCreateSuggestionCompanyInfo()
				});
			} else {
				updateCreateSuggestionCompanyInfo();
			}
		});
	}
}




function initSignInPage() {
	if($('link_openIDTieIn')) {
		$('link_openIDTieIn').href = "javascript:void(null);";
		$('link_openIDTieIn').observe('click',function(){
			if($('openIDTieIn').getStyle('display') == "none") {
				new Effect.BlindDown('openIDTieIn',{duration:0.5});
			}
		});
	}
}




function initCompanySignup() {
	var info_companyname = $('field_companyname');
	var bill_companyname = $('field_billing-companyname');
	var bill_name = $('field_billing-name');
	var ccname = $('field_billing-ccname');

	info_companyname.observe('keyup',function(){
		bill_companyname.value = info_companyname.getValue();
	});

	bill_name.observe('keyup',function(){
		ccname.value = bill_name.getValue();
	});

	bill_companyname.value = info_companyname.getValue();
	ccname.value = bill_name.getValue();
	info_companyname.focus();
}




function updateCreateSuggestionCompanyInfo() {
		var addressuserid = $('field_address-book').value;
		new Ajax.Updater('suggestion_company_information','/users/usersummary?addressuser_id='+addressuserid,{
		method: 'GET',
		//parameters: {
			//companyID: 45
		//},
		onComplete: function() {
			opDelay = 0.5;
			if($('sendto_company_container').getStyle('display') == "none") {
				Effect.BlindDown('sendto_company_container',{duration:0.5});
				opDelay = 0.0;
			}
			new Effect.Opacity('sendto_company_container',{
				duration: 0.5,
				from: 0.0,
				to: 1.0,
				delay: opDelay,
				beforeStart: function(effect){
					effect.element.style.background = "#ffffff";
				},
				afterFinish: function(effect){
					effect.element.style.background = "none";
				}
			});
		}
	});
		/*new Ajax.onlinenow.gif('suggestion_company_information','usersummary?addressuser_id='+addressuserid,{
		method: 'GET',
		//parameters: {
			//companyID: 45
		//},
		onComplete: function() {
			opDelay = 0.5;
			if($('sendto_company_container').getStyle('display') == "none") {
				Effect.BlindDown('sendto_company_container',{duration:0.5});
				opDelay = 0.0;
			}
			new Effect.Opacity('sendto_company_container',{
				duration: 0.5,
				from: 0.0,
				to: 1.0,
				delay: opDelay,
				beforeStart: function(effect){
					effect.element.style.background = "#ffffff";
				},
				afterFinish: function(effect){
					effect.element.style.background = "none";
				}
			});
		}
	});
		*/
}






function submitNewSuggestion(formElem) {
	if($('choose_submit_identity') != undefined) {
		return validatemessage(formElem);
	}
	/*else {
	alert("You must log in with your account before you can submit a new suggestion.\n\nIf you do not have an account, click on the Sign Up link in the upper right corner of the From box.");
	return false;
	}*/
}



function userNameCheckKY(e){
	new Ajax.Updater('usernamecheckresult', '/logins/usernamecheck?user='+$(e).value+'',{ method: 'get', asynchronous: true}); 
}

function initAutoComplete() {
	// Please see the Script.aclo.us website for full documentation
	// on the options available for the auto-complete script:
	// http://wiki.script.aculo.us/scriptaculous/show/Ajax.Autocompleter	

	new Ajax.Autocompleter(
		'field_find-company',						// The ID of the text field
		'autocomplete',								// The ID of the element to contain the Auto-complete response
		'users/auto_rs.html'		// The name of the file to call that will contain the built auto-complete list
	);
}




// This Event watches the window load status and will run the set of functions
// listed within it when the DOM has initiated.
// Startup on-load appender
function startup() {
	externalLinks();
	rollAssign();
	initSigninBox();
	if(document.getElementById('suggestion') || document.getElementById('home_suggestion')) {
		initAutoComplete();
	}
//	initOurminglelink();
}


function checkSignupForm() 
{

		if (!IsEmailValid(document.registration.email.value))
		{			
			alert ("\n The Email format is incorrect. \n\nPlease enter right format.")
			document.registration.email.focus();
			return false;
		}
		if (document.registration.firstname.value.length < 1)
		{
			alert ("\n Please enter your first name.")
			document.registration.firstname.focus();
			return false;
		}
		if (document.registration.lastname.value.length < 1)
		{
			alert ("\n Please enter your last name.")
			document.registration.lastname.focus();
			return false;
		}		
		if (document.registration.username.value.length < 2)
		{
			alert ("\n User name must be 2 characters or longer. \n\nPlease create your username.")
			document.registration.username.focus();
			return false;
		}
		if (document.registration.password.value.length <= 5)
		{
			alert ("\n Password must be 6 characters or longer. \n\nPlease enter the password.")
			document.registration.password.focus();
			return false;
		}
		if (document.registration.password.value != document.registration.password2.value)
		{
			alert ("\n Passwords don't match. \n\nPlease re-enter both passwords.")
			document.registration.password2.focus();
			return false;
		}

/*		
		if (document.registration.email.value != document.registration.email2.value)
		{
			alert ("\n Both Emails don't match. \n\nPlease re-enter your emails.")
			document.registration.email2.focus();
			return false;		
		}
*/
		if (!$('state').visible) {
			if (document.registration.state.value.length < 1)
			{
				alert ("\n Enter Your State or Province. \n\nIt's required for other members to search for you.")
				document.registration.state.focus();
				return false;
			}
		}
		
		if (!$('city').visible) {
			if (document.registration.city.value.length < 1)
			{
				alert ("\n Enter Your city. \n\nIt's required for other members to search for you.")
				document.registration.city.focus();
				return false;
			}
		}
		
/*
		if (document.registration.zip.value.length < 1)
		{
			alert ("\n Enter Your postal code. \n\nIt's required for other members to search for you.")
			document.registration.zip.focus();
			return false;
		}
*/
		if (document.registration.keyval.value.length != 6)
		{
			alert ("\n Enter Code from image. ")
			document.registration.keyval.focus();
			return false;
		}		
	
		if (!document.registration.terms.checked)
		{		
			alert ("\n Please read the terms, check the box if you agree with the term. ")
			document.registration.terms.focus();
			return false;
		}		
		return true;
}


function submitForms(e) 
{	
		if(e=="withBD")
		{
			var newDate = new Date();		
			var DifYear =  newDate.getFullYear() -  parseInt(document.formR2.bYear.value);		
			var DifMonth = (newDate.getMonth()+1) - parseInt(document.formR2.bMonth.value);		
			var DifDay = newDate.getDate() - parseInt(document.formR2.bDay.value);
			
			if(DifYear <18)
			{ 	alert("\n\nMust be at least 18 years old to sign up");
				return false;
			}
			if(DifYear <= 18 && DifMonth < 0)
			{
				alert("\n\nMust be at least 18 years old to sign up");
				return false;
			}
			if(DifYear <= 18 && DifMonth <=0 && DifDay <0)
			{	
				alert("\n\nMust be at least 18 years old to sign up");
				return false;		
			}		 
		}

				
		if (document.formR2.city.value.length <1)
		{
			alert ("\n\nPlease enter your City.");
			document.formR2.city.focus();
			return false;
		}		
		if (document.formR2.zipcode.value.length <5)
		{
			alert ("\n\nPlease enter your zip code.");
			document.formR2.zipcode.focus();
			return false;
		}/*
		if (document.formR2.profession.value.length < 1)
		{
			alert ("\n The profession field is blank. \n\nPlease enter your profession.");
			document.formR2.profession.focus();
			return false;
		}*/
		if (document.formR2.headline.value.length < 1)
		{
			alert ("\n The headline field is blank. \n\nPlease enter a headline.");
			document.formR2.headline.focus();
			return false;
		}
		
		//var interest = document.formR2.interests.value.replace(/,/g, '');	
		var patt1 = new RegExp("[a-z]","ig");
		var result = document.formR2.interests.value.match(patt1);
		
		var patt2 = /^([a-z]|\s|,)*$/gi;
		var legalchar = patt2.test(document.formR2.interests.value);
		//alert(legalchar); 
		if ( (!result || result.length<1) ||  !legalchar)
		{
			alert ("\n Please enter your interests (ONLY character, space and comma are allowed.), \nsuggest to enter at least five interests for easy match system.");
			document.formR2.interests.focus();
			return false;
		}		
		if (document.formR2.interests.value.indexOf("&") >= 0)
		{
			alert ("\n Please do not use '&' in interests.");
			document.formR2.interests.focus();
			return false;
		}
		
		
		
		
		var patt1 = new RegExp("[A-Z]","ig");
		var result = document.formR2.aboutme.value.match(patt1);		
		//alert(result.length);
		if (!result || result.length  < 10)
		{
			alert ("\n Help your matches get to know you! \n\n You get 3 times as many responses with a more descriptive profile.  with minimum 10 characters!");
			document.formR2.aboutme.focus();
			return false;
		}
		
		var result = document.formR2.firstdate.value.match(patt1);
		//alert(result);
		if (!result || result.length  <10)
		{
			alert ("\n First Date field is required with minimum 10 characters!");
			document.formR2.firstdate.focus();
			return false;
		}
		
		var result = document.formR2.badhabit.value.match(patt1);
		//alert(result.length);
		if (!result || result.length  <10)
		{
			alert ("\n Bad Habit field is required with minimum 10 characters! \n\n ");
			document.formR2.badhabit.focus();
			return false;
		}
		
		var result = document.formR2.willdo.value.match(patt1);
		//alert(result.length);
		if (!result || result.length  <10)
		{
			alert ("\n Will Do field is required with minimum 10 characters! \n\n ");
			document.formR2.willdo.focus();
			return false;
		}
		
		var result = document.formR2.dealbreaker.value.match(patt1);
		//alert(result.length);
		if (!result || result.length  <10)
		{
			alert ("\n Deal Breaker field is required with minimum 10 characters! \n\n ");
			document.formR2.dealbreaker.focus();
			return false;
		}


		
		if (document.formR2.field_password.value.length  <6)
		{
			alert ("\n The password field is to short. \n\n Please enter at least 6 characters.");
			document.formR2.field_password.focus();
			document.formR2.field_password.select();
			return false;
		}	
		

		return true;
}

function smilie(thesmilie) {
// inserts smilie text
	document.forms[0].description.value += thesmilie+" ";
	document.forms[0].description.focus();
}
// End -->



var oldonload = window.onload;

if (typeof window.onload != 'function') {
	window.onload = startup;
} else {
	window.onload = function() {
		oldonload();
		startup();
	}
}


function initCompanyProfile() {
/*	var pad = (170 - $('logo_img').getDimensions()['height'])/2;
	$('logo_img').setStyle({
		'paddingTop': pad+'px'
	});
*/

	$('link_make-a-suggestion').href = "javascript:void(null);";
	$('link_make-a-suggestion').observe('click',function(){
		if(animating == false) {
			animating = true;
			if($('box_our-suggestion') != undefined) {
				new Effect.DropOut('box_our-suggestion',{
					duration: 0.5,
					afterFinish: function(){
						$('box_our-suggestion').remove();
						makeASuggestion('make-suggestion',Insertion.Bottom);
					}
				})
				
			} else {
				makeASuggestion('make-suggestion',Insertion.Bottom);
			}
		}
	});

	$('link_cancel-suggestion').href = "javascript:void(null);";
	$('link_cancel-suggestion').observe('click',function(){
		if(animating == false) {
			animating = true;
			new Effect.BlindUp('suggestion_form_container');
			new Effect.Appear('make_suggestion_link_holder');
			new Effect.Fade('nav_cancel-suggestion',{
				afterFinish: function(){
					$('suggestion_form_container').remove();
					animating = false;
				}
			});
		}
	});

	
}




function makeASuggestion(loc,how) {
	new Effect.BlindUp('make_suggestion_link_holder');
	new Effect.Appear('nav_cancel-suggestion',{
		duration:0.5,
		beforeStart: function(event){
			event.element.setStyle({'background':'#fff'});
		},
		afterFinish: function(event){
			event.element.setStyle({'background':'none'});
		}
	});
	if($('suggestion_form_container') == undefined && animating == true) {
		var login = $('userloggedin').value;
		new Ajax.onlinenow.gif(loc,'send_message?userloggedin='+login,{
			method: 'get',
			insertion: how,
			onComplete: function() {
				rollAssign();
				new Effect.BlindDown('suggestion_form_container');
				new Effect.Appear('suggestion_form_container',{
					afterFinish:function(){
						animating = false;
					}
				});
				
			}
		});
	}
}


function deleteUserGroupKY(e)
{
	if(confirm("Are you sure you want to delete this group?")) 
	{
		
		//$('e').remove();
        document.location = "deleteUsergroup?action=delUsergroup&tid=" + e + "";
    }
}

function editSuggestionCategory(id)
{
	//alert("got id = " + id);
    suggestionCategorySwitchMode(id, true);
}

function suggestionCategorySwitchMode(id, modeIsEdit)
{
	//alert("got id = " + id + "\n\n" + "mode is edit = " + modeIsEdit);
    var showIfModeIsEdit = modeIsEdit? "block" : "none";
    var hideIfModeIsEdit = (!modeIsEdit)? "block" : "none";
    
    $("category_row_label_"+id).style.display = hideIfModeIsEdit;
    $("category_row_edit_"+id).style.display = hideIfModeIsEdit;
    $("category_row_delete_"+id).style.display = hideIfModeIsEdit;
	
    $("category_row_textbox_"+id).style.display = showIfModeIsEdit;
    $("category_row_textbox_"+id).value="";
	$("category_row_textbox_"+id).data[usersfolder][editdesc].focus();
//	document.$("category_row_textbox_"+id).data[usersfolder][editdesc].select();
	
    $("category_row_ok_"+id).style.display = showIfModeIsEdit;
    $("category_row_cancel_"+id).style.display = showIfModeIsEdit;
}
function editSuggestionCategoryOk(id)
{

    var editField = $("category_row_textbox_"+id);
    var newName = editField.getValue().toString();
    if(newName.length <= 0)
    {
        alert("Please enter a label name to continue.");
    }
    else
    {
        document.location = "editMailBoxName?action=editFolder&fid="+ id +"&editdesc=" + newName + "";
        //suggestionCategorySwitchMode(id, false);
    }
}
function editSuggestionCategoryCancel(id)
{
    suggestionCategorySwitchMode(id, false);
}


function deleteSuggestionCategory(id)
{
	if(confirm("Are you sure you want to delete this group?")) 
	{
        document.location = "deleteMailBoxName?action=delFolder&fid=" + id + "";
    }
}


function showhiddendiv(e){		
		new Effect.Appear(e, {duration: 0.5, from: 0, to: 1});
		new Effect.BlindDown(e, {duration: 0.25});
}
function hidediv(e){	
	new Effect.BlindUp(e, {duration: 0});
	new Effect.Fade(e, {duration: 0});	
}
function showHiddenKY(showAry, hideAry){

	for(var i=0; i<hideAry.length; i++)
	{
		hidediv(hideAry[i]);		
	}
	for(var i=0; i<showAry.length; i++)
	{		
		showhiddendiv(showAry[i]);				
	}
}

function showCurrentLink(showAry, hideAry){
	for(var i=0; i<hideAry.length; i++)
	{
		$(hideAry[i]).setStyle({color:"#003399"});
	}
	for(var i=0; i<showAry.length; i++)
	{		
		$(showAry[i]).setStyle({color:"#800000"});
	}		
}
function showCurrentLinkGrayColor(showAry, hideAry){
	for(var i=0; i<hideAry.length; i++)
	{
		$(hideAry[i]+'_link').setStyle({color:"#003399"});
	}
	for(var i=0; i<showAry.length; i++)
	{		
		$(showAry[i]+'_link').setStyle({color:"#800000"});
	}		
}


function showUsernameLogin()
{
	new Effect.Fade('openidLogin',{duration:0.0});
	new Effect.Appear('EmailLogin',{duration:0.5});
}

function showOpenidLogin()
{
	new Effect.Fade('EmailLogin',{duration:0.0});
	new Effect.Appear('openidLogin',{duration:0.5});
	
}


function checkChar(e)
{
	var lastChar = e.value.substring(e.value.length-1);
	if(lastChar == '@' || lastChar =='.' || lastChar == '*')
	 e.value = e.value.substring(0, e.value.length-1);

}

function setMaxKY(e, ee, max) {
	if (e.value.length > max) {
		e.value = e.value.substring(0, max);
	} else {
		ee.value = max - e.value.length;
	}
}

function showFadeAuto(div){
	showFade1(div);
	setTimeout('showFade1(\''+div+'\')',3000);
}
function showFadeAutoSecond(div, second){
	showFade1(div);
	setTimeout('showFade1(\''+div+'\')',second*1000);
}


function showFadeDropAutoSecond(div, second){
	showFade1(div);
	setTimeout('FadeDrop(\''+div+'\')',second*1000);
}
function FadeDrop(divname){	
	if($(divname).getStyle('display')=="none")
	{	new Effect.Appear(divname, {duration: 0.5});	
	}
	else
	{ 
		new Effect.Fade(divname, {duration: 0.5});	
		new Effect.DropOut(divname);
	}
}



function movetonexttab(e,num,id){
	if(e.value.length >= num ){		
		document.getElementById(id).focus();
		document.getElementById(id).select();
	}
	
}
function characteronly(e){
	var flag=false;		
	if(document.getElementById(e).value.length>=1){
		flag = (!/[^a-z]+/gi.test(document.getElementById(e).value));		
	}else{
		flag=true;
	}
	
	if(!flag){
		alert(e + " to have LETTERS only. (No Numerals, No Space)\n Please use your 'Real Name' and correct spelling \nfor your protection and privacy.");
		document.getElementById(e).focus();		
		document.getElementById(e).select();
		//selectfocus(e, flag);
	}
}

function selectfocus(e, bool){	
	if(!bool){
		document.getElementById(e).focus();		
		document.getElementById(e).select();		
	}
}








function initAdminMailAccount() {	

	// Enable rollover coloring for result lists
	$$("#results_my-suggestions .draggableLists li.row ul.rowCols").each(function(e){	
		e.observe('mouseover',function(){
			e.addClassName('rowHover').setStyle({cursor:'pointer'});
		});
		e.observe('mouseout',function(){
			e.removeClassName('rowHover');			
		});
		e.observe('click',function(){
			/*							   
			var subSuggestions = e.next('ul.subSuggestionLists');
			Effect.toggle(subSuggestions,'blind',{duration:0.5});
			if(subSuggestions.getStyle('display') == 'block') {
				e.up('li.row').setStyle({'border-color':'#fff'});
				new Effect.Opacity(e.down('li.col2'),{
					duration:0.5,
					from:0.0,
					to:1.0
				});
				new Effect.Opacity(e.down('li.col3'),{
					duration:0.5,
					from:0.0,
					to:1.0
				});				
			} else {
				e.up('li.row').setStyle({'border-color':'#f2f2f2'});
				new Effect.Opacity(e.down('li.col2'),{
					duration:0.5,
					from:1.0,
					to:0.0
				});
				new Effect.Opacity(e.down('li.col3'),{
					duration:0.5,
					from:1.0,
					to:0.0
				});
			}
			*/
		});
	});

	// Enable draggable sub-rows
	$$('ol#table_results_my-suggestions li.row ul.rowCols').each(function(e) {
		new Draggable(e,{
				revert: true,
				zindex: 1000,
				onStart: function() {
					e.setStyle({'border-color':'#ffdf61'});
					e.descendants('li').each(function(slr){
						slr.setStyle({'background':'#fefabf'});
					});
				},
				onEnd: function() {
					e.setStyle({'border-color':'#fff'});
					document.body.style.overflowX = "auto";
					e.descendants('li').each(function(slr){
						slr.setStyle({'background':'none'});
					});
				},
				onDrag: function() {
					document.body.style.overflowX = "hidden";
				}
			}
		);
		e.observe('mouseover',function(){
			e.addClassName('rowHover').setStyle({cursor:'pointer'});

		});
		e.observe('mouseout',function(){
			e.removeClassName('rowHover');			
		});		
		new Tip(e.down('li.col1 a'),'View this message',{
			hook: false,
			effect: 'appear'
		});
		new Tip(e.down('li.col2 a'),'View this message',{
			hook: false,
			effect: 'appear'
		});
	});

	// Enable organize category rows to be droppable
	$$('ol#table_organize-suggestions>li').each(function(e){
		Droppables.add(e,
			{
				hoverclass: 'dropRowHover',
				onDrop: function(element,dropon,event) {
					//alert("you are on dropping email to mailbox");
					//var mail_id = element.down('li.row ul.rowCols li.col1').id;
					//var mailbox_id = dropon.id.substr(9);					
					//element.remove();
					//new Ajax.onlinenow.gif('results_organize-suggestions', 'forwardtomailbox?mail_id='+mail_id+'&mailbox_id='+mailbox_id+'',{ 
					//	method: 'get', asynchronous: true});					
					adminArchiveCategory(element,dropon,event);
				}
			}
		);
	});

	// Enable delete suggestion droppable area
	Droppables.add('btn_trash-suggestion',
		{
			hoverclass:'deleteHover',
			onDrop: function(element, dropon, event)
			{
				
			//var messageid = element.down('li.row ul.rowCols li.col1').id;
			//alert("initUseraccount id = "+messageid);
				
				if(confirm("Are you sure you would like to remove the message:\n\n"+element.down('li.row ul.rowCols li.col1 a').innerHTML)) {
					//var parentList = element.up('ul.subSuggestionLists');
					//var parentCompanyList = parentList.up('li.row');
					var messageid = element.down('li.row ul.rowCols li.col1').id;
					element.remove();				
					new Ajax.Request('deletemessage?messageID='+messageid,{ method: 'get', asynchronous: true}); 						
					/*if(parentList.getElementsBySelector('li.subRow').length == 0) {
						new Effect.Opacity(parentCompanyList,{duration: 0.5, from: 1.0, to: 0.0});
						new Effect.BlindUp(parentCompanyList,{
							duration: 0.5,
							delay: 0.5,
							afterFinish: function(){
								parentCompanyList.remove();
							}
						});
					}*/
				}
			}
		}
	);

	$('btn_add-suggestion').href = "javascript:void(null);";
	$('btn_add-suggestion').observe('click',function(e){
		var folderList = $('table_organize-suggestions');
		var lastRow = folderList.immediateDescendants().last();
				
		var newCatID = lastRow.readAttribute('id').substr(9).succ();


		var newRow = document.createElement('LI');
			newRow.className = "";//"row";
			newRow.id = "category_"+newCatID;
			newRow.style.margin =  "0";
		var newRowCols = document.createElement('UL');
			newRowCols.className = ""//"rowCols";
			newRowCols.style.margin = "0";
		var newCol1 = document.createElement('LI');
			newCol1.className = "col1";
		var newEditField = document.createElement('INPUT');
			newEditField.maxLength = "30";
			newEditField.id = "edit_field_"+newCatID;
		var newCol1Link = document.createElement('A');
			newCol1Link.href = "#";
			newCol1Link.innerHTML = "";

/*
		var newCol2 = document.createElement('LI');
			newCol2.className = "col2";
			newCol2.innerHTML = "Drag messages here to folders and archive them";
*/
		newCol1.appendChild(newCol1Link);
		newCol1.appendChild(newEditField);
		newRowCols.appendChild(newCol1);
	
//	newRowCols.appendChild(newCol2);
		newRow.appendChild(newRowCols);
		folderList.appendChild(newRow);


		var editField = $('edit_field_'+newCatID);
			editField.focus();


var ok = document.createElement('A');
ok.id = "return_"+"9999";//groupID;
ok.className = "btn_ok";
ok.innerHTML = "ok";
ok.style.color = "#444";
ok.style.zIndex = "9999";
//alert(newEditField.id);
var okCommandString = "javascript:addNewFolderOK('" + newCatID +"')";
ok.href = okCommandString;

var cancel = document.createElement('A');
cancel.id = "cancel_"+"9999";//groupID;
cancel.className = "btn_cancel";
cancel.innerHTML = "cancel";
cancel.style.color = "#444";
cancel.style.zIndex = "9999";
var cancelCommandString = "javascript:window.location='/admin/myinbox';";
cancel.href = cancelCommandString;
//newRow.appendChild(ok);
//newRow.appendChild(cancel);


		editField.observe('keypress',function(event){
			if(event.keyCode == Event.KEY_ESC) {		
				//editField.up('li.row').remove();
				editField.up('li').remove();
			}
			if(event.keyCode == Event.KEY_RETURN) {				
				//editField.Previous('a').innerHTML = editField.getValue()+' (<span class="amount">0</span>)';				
				addNewAdminFolder(editField.getValue());
				Droppables.add(editField.up('li.row'),
					{
						hoverclass: 'dropRowHover',
						onDrop: function(element,dropon,event) {	
							//alert("aaa");						
							adminArchiveCategory(element,dropon,event);
						}
					}
				);
				editField.remove();
			}
		});
	});
}


function adminArchiveCategory(element,dropon,event) {
	//alert("bbb");
	var mail_id = element.down('li.row ul.rowCols li.col1').id;
	var mailbox_id = dropon.id.substr(9);	

	new Ajax.Request('forwardtocontactfolder?mail_id='+mail_id+'&mailbox_id='+mailbox_id+'',{ 
		method: 'get',
		onComplete: function(){
			setTimeout("", 1000);
			location.href='myinbox';
			}
	}); 
}

function addNewAdminFolderOK(editField){
	var element = $('edit_field_'+editField).getValue();
	window.location = 'addnewadminfolder?boxname='+element+'';
}

function addNewAdminFolder(element){	
	//new Ajax.Request('addnewmailbox?boxname='+element+'',{ method: 'get', asynchronous: true});
	window.location = 'addnewadminfolder?boxname='+element+'';
}

function deleteAdminFolder(id)
{
	if(confirm("Are you sure you want to delete this group?")) 
	{
        document.location = "deleteAdminFolder?action=delFolder&fid=" + id + "";
    }
}

/* UTILITIES */

function centerdiv(id)
{
	return true;
	alert(document.getElementById(id).offsetHeight);
	alert(document.getElementById(id).offsetWidth);
}

// form controls
function checkselect(e, tbl){
	var total = $(tbl).tBodies[0].rows.length;

	if(e.checked){
		checkAll(total);
	}else{
		uncheckAll(total);
	}
}

function checkAll(total){		
	for(var j=1; j<total; j++) 
	{
		$('item_'+j).checked = "checked";
	}
}

function uncheckAll(total){
	for(var j=1; j<total; j++) 
	{
		$('item_'+j).checked = "";
	}
}


function isValidEmail(email, required) {
    if (required==undefined) {   // if not specified, assume it's required
        required=true;
    }
    if (email==null) {
        if (required) {
            return false;
        }
        return true;
    }
    if (email.length==0) {  
        if (required) {
            return false;
        }
        return true;
    }
    if (! allValidChars(email)) {  // check to make sure all characters are valid
        return false;
    }
    if (email.indexOf("@") < 1) { //  must contain @, and it must not be the first character
        return false;
    } else if (email.lastIndexOf(".") <= email.indexOf("@")) {  // last dot must be after the @
        return false;
    } else if (email.indexOf("@") == email.length) {  // @ must not be the last character
        return false;
    } else if (email.indexOf("..") >=0) { // two periods in a row is not valid
	return false;
    } else if (email.indexOf(".") == email.length) {  // . must not be the last character
	return false;
    }
    return true;
}

function allValidChars(email) {
  var parsed = true;
  var validchars = "abcdefghijklmnopqrstuvwxyz0123456789@.-_";
  for (var i=0; i < email.length; i++) {
    var letter = email.charAt(i).toLowerCase();
    if (validchars.indexOf(letter) != -1)
      continue;
    parsed = false;
    break;
  }
  return parsed;
}

/*
 * %lea% 20090526
 */
function clickOn(link_name){
	new Ajax.Request('/admin/clickOn/'+link_name, {method: 'get', asynchronous: true});		
}
