
var is_opera = (navigator.userAgent.indexOf('Opera') != -1);
var is_ie = (! is_opera && navigator.userAgent.indexOf('MSIE') != -1);

var session = {
	mouse: new Object(), 
	key: new Object(), 
	window: new Object()
};

if(! is_ie)	{
	document.captureEvents(Event.MOUSEDOWN);
	document.captureEvents(Event.MOUSEUP);
	document.captureEvents(Event.MOUSEMOVE);
	document.captureEvents(Event.KEYDOWN);
	window.captureEvents(Event.RESIZE);
}

document.onmousedown = mouse_down;
document.onmouseup = mouse_up;
document.onmousemove = mouse_position;
document.onkeydown = key_pressed;
window.onresize = window_resize;

window_resize();

function window_resize(e)	{

	e = (e) ? e : ((window.event) ? window.event : "");

	if(window.innerWidth)	{
		session.window.width = window.innerWidth;
		session.window.height = window.innerHeight;
	}
	else if(document.documentElement && document.documentElement.clientWidth != 0)	{
		session.window.width = document.documentElement.clientWidth;
		session.window.height = document.documentElement.clientHeight;
	}
	else if(document.body)	{
		session.window.width = document.body.clientWidth;
		session.window.height = document.body.clientHeight;
	}
}


function mouse_up(e)	{
	
	e = (e) ? e : ((window.event) ? window.event : "");
	
	session.mouse.up = true;
	session.mouse.down = false;
	
	session.key = {
		ctrlKey: e.ctrlKey, 
		shiftKey: e.shiftKey, 
		altKey: e.altKey
	};
}


function mouse_down(e)	{
	
	e = (e) ? e : ((window.event) ? window.event : "");
	
	session.mouse.up = false;
	session.mouse.down = true;
	
	session.key = {
		ctrlKey: e.ctrlKey, 
		shiftKey: e.shiftKey, 
		altKey: e.altKey
	};
}


function mouse_position(e)	{
	var x;
	var y;
	
	e = (e) ? e : ((window.event) ? window.event : "");
	
	if(is_ie)	{
		x = e.clientX + document.body.scrollLeft;
		y = e.clientY + document.body.scrollTop;
	}
	else	{
		x = e.pageX;
		y = e.pageY;
	}

	if(x < 0)	{
		x = 0;
	}
	if(y < 0)	{
		y = 0;
	}

	session.mouse.x = x;
	session.mouse.y = y;
}


function key_pressed(e)	{

	e = (e) ? e : ((window.event) ? window.event : "");
	
	var pressed;
	
	if(is_ie)	{
		pressed = String.fromCharCode(e.keyCode);
	}
	else	{
		pressed = String.fromCharCode(e.which);
	}
	
	key = {
		triggerKey: pressed, 
		ctrlKey: e.ctrlKey, 
		shiftKey: e.shiftKey, 
		altKey: e.altKey
	};
}


var calendar_day;

function highlight_calendar_day(obj)	{

	var unixtime = document.getElementById(obj.id + "_unixtime").firstChild.nodeValue;
	
	document.getElementById("timeout_unixtime").value = unixtime;
	var current_day = document.getElementById("timeout_day").value;
	
	if(current_day != obj.id)	{
		remove_highlighted_box();
		new_highlighted_box(obj, unixtime);
	}
}


function new_highlighted_box(obj, unixtime)	{

	//if(document.getElementById("timeout_popup"))	{
	//	return(false);
	//}

	var date = new Date(unixtime * 1000);
	var f_unixtime;
	if(is_ie) {
	   f_unixtime = month_name(date.getMonth()) + " " + obj.id + ", " + (date.getYear());
        }
	else   {
	   f_unixtime = month_name(date.getMonth()) + " " + obj.id + ", " + (date.getYear()+1900);
        }
	
	var y = find_y_pos(obj);
	var x = find_x_pos(obj);

	// Main box
	var main_box = document.createElement("DIV");
	main_box.id = "timeout_popup";
	main_box.style.position = "absolute";
	main_box.style.top = y - 70 + "px";
	main_box.style.left = x - 70 + "px";
	main_box.style.width = "211px";
	main_box.style.height = "211px";
	document.body.appendChild(main_box);

	// Transparent background
	var div = document.createElement("DIV");
	div.id = "timeout_popup_background";
	div.style.position = "relative";
	div.style.width = "200px";
	div.style.height = "200px";
	div.style.backgroundColor = "#00a766";
	div.style.opacity = ".75";
	div.style.filter = "alpha(opacity=75)";
	div.style.border = "solid black 1px";
	div.style.MozBorderRadius = "6px";
	main_box.appendChild(div);

	// Right Shadow
	div = document.createElement("DIV");
	div.style.position = "relative";
	div.style.marginTop = "-190px";
	div.style.left = "201px";
	div.style.width = "10px";
	div.style.height = "200px";
	div.style.MozBorderRadiusTopright = "6px";
	div.style.MozBorderRadiusBottomright = "6px";
	div.style.backgroundColor = "black";
	div.style.opacity = ".25";
	div.style.filter = "alpha(opacity=25)";
	main_box.appendChild(div);

	// Bottom Shadow
	div = document.createElement("DIV");
	div.style.position = "relative";
	div.style.width = "191px";
	div.style.height = "10px";
	div.style.left = "10px";
	div.style.marginTop = "-10px";
	div.style.fontSize = "1px";
	div.style.MozBorderRadiusBottomleft = "6px";
	div.style.backgroundColor = "black";
	div.style.opacity = ".25";
	div.style.filter = "alpha(opacity=25)";
	main_box.appendChild(div);
	
	
   // Encasing DIV
   div = document.createElement("DIV");
   div.style.position = "relative";
   if(is_ie)   {
      div.style.marginTop = "-210px";
   }
   else	 {
      div.style.marginTop = "-225px";
   }
   div.style.width = "200px";
   div.style.height = "200px";
   main_box.appendChild(div);

	var img = document.createElement("IMG");
        setOnClick(img, "remove_highlighted_box();");
	img.style.cssFloat = "right";
	img.src = "/image/declined.gif";
	div.appendChild(img);
	
	div1 = document.createElement("DIV");
	div1.id = "f_unixtime_display";
	div1.style.marginTop = "15px";
	div1.style.fontWeight = "bold";
	div1.style.fontFamily = "Verdana";
	div1.style.color = "white";
	div1.style.fontSize = "20px";
	div1.style.padding = "10px";
	div1.appendChild(document.createTextNode(f_unixtime));
	div.appendChild(div1);

	div.appendChild(document.createElement("BR"));
	
	div1 = document.createElement("DIV");
	div1.style.marginTop = "-10px";
	div1.style.marginRight = "auto";
	div1.style.marginLeft = "auto";
	div1.style.padding = 0;
	div1.style.textAlign = "center";
	div1.style.border = "solid black 5px";
	div.appendChild(div1);

	var span = document.createElement("DIV");
	span.id = "timeout_hours";
	setOnClick(span, "change_timeout(this);");
	span.style.cssFloat = "left";
	span.style.width = "20px";
	span.style.backgroundColor = "white";
	span.style.fontFamily = "verdana";
	span.style.border = "solid black 1px";
	span.style.padding = "2px";
	span.style.fontSize = "15px";
	span.style.cursor = "pointer";
	var hours = date.getHours();
	if(hours > 12)	{
		hours -= 12;
	}
	span.appendChild(document.createTextNode(hours));
	div1.appendChild(span);
	
	span = document.createElement("DIV");
	span.id = "timeout_minutes";
	setOnClick(span, "change_timeout(this);");
	span.style.cssFloat = "left";
	span.style.width = "20px";
	span.style.fontFamily = "verdana";
	span.style.backgroundColor = "white";
	span.style.border = "solid black 1px";
	span.style.padding = "2px";
	span.style.fontSize = "15px";
	span.style.cursor = "pointer";
	var minutes = date.getMinutes();
	if(minutes < 10)	{
		span.appendChild(document.createTextNode("0" + minutes));
	}
	else	{
		span.appendChild(document.createTextNode(minutes));
	}
	div1.appendChild(span);
	
	span = document.createElement("DIV");
	span.id = "timeout_ampm";
	setOnClick(span, "change_timeout(this);");
	span.style.cssFloat = "left";
	span.style.width = "23px";
	span.style.backgroundColor = "white";
	span.style.fontFamily = "verdana";
	span.style.border = "solid black 1px";
	span.style.padding = "2px";
	span.style.fontSize = "15px";
	span.style.cursor = "pointer";
	if(date.getHours() < 13)	{
		span.appendChild(document.createTextNode("AM"));
	}
	else	{
		span.appendChild(document.createTextNode("PM"));
	}
	div1.appendChild(span);

	div1.appendChild(document.createElement("BR"));
	div1.appendChild(document.createElement("BR"));
	
	div1 = document.createElement("DIV");
	div1.style.textAlign = "center";
	div1.style.marginTop = "5px";
	div1.style.padding = "5px";
	div1.style.fontFamily = "verdana";
	div1.style.fontSize = "12px";
	div1.style.border = "solid black 1px";
	div.appendChild(div1);
	
	div1.appendChild(document.createTextNode("Click time values to increase.  [SHIFT]+click to decrease.  "));
	div1.appendChild(document.createElement("BR"));
	div1.appendChild(document.createElement("BR"));
	div1.appendChild(document.createTextNode("Click AM/PM to toggle."));
}


function remove_highlighted_box()	{

	var popup = document.getElementById("timeout_popup");
	if(popup)	{
		popup.parentNode.removeChild(popup);
	}
}


function find_x_pos(obj)	{

	var curtop = 0;
	if(obj.offsetParent)	{
		while(obj.offsetParent)	{
			curtop += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	}
	else if(obj.y)	{
		curtop += obj.x;
	}

	return(curtop);
}


function find_y_pos(obj)	{

	var curtop = 0;
	if(obj.offsetParent)	{
		while(obj.offsetParent)	{
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	else if(obj.y)	{
		curtop += obj.y;
	}

	return(curtop);
}


function calculate_timeout(input, calendar_day)	{
	input.value = calendar_day*86400;
}


function spell_check(text)	{

	show_status_text("Spell checking...[" + text + "]");

	if(! document.getElementById('spell_check_section'))	{


		// Return false if no elements exist to show spell check results
		return(false);
	}
	
	// Determine whether to remove or create search results
	var table;
	if(table = document.getElementById("spell_results"))	{
		// Table exists, remove, change toggle image, & return
		
		table.parentNode.removeChild(table);
	}

	// Table does not exist, get categories & create elements

	// xmlhttp.js retrieve method
	var url = "/xml/spell_check.xml?text=" + text;
	
	var xmlhttp = new Object();

	if(window.ActiveXObject)	{
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	else	{
		xmlhttp = new XMLHttpRequest();
	}

	xmlhttp.onreadystatechange = function()	{

		show_status_text("readyState " + xmlhttp.readyState);
		
		if(xmlhttp.readyState == 1)	{		
			show_status_bar();
		}
		else if(xmlhttp.readyState == 4)	{

			show_status_text("in ready 4");			
			
			var doc = xmlhttp.responseXML;

			show_spell_check(doc);

			// var count = doc.getElementsByTagName("items")[0].getElementsByTagName("count")[0].firstChild.nodeValue;
			// if(count > 0)	{
			// 	// Results found
			// 	//update_search_history('category', category_id, name);
			// }

			show_status_text("hiding status bar..");
			hide_status_bar();
			show_status_text("hiding status bar done");
	
			session.active_requests--;
		}
	};
	session.active_requests++;
	xmlhttp.open("GET", url, true);
	xmlhttp.send(null);

	return(false);
}


function show_spell_check(doc)	{

	var spell_check_section = document.getElementById('spell_check_section');
	//alert(spell_check_section);

	for(var i in doc.getElementsByTagName("words")[0])	{
		//alert(i.nodeValue);
	}
	//.getElementsByTagName("word")[0].getElementsByTagName("value")[0].firstChild.nodeValue;
	//alert(count);
	//spell_check_section.appendChild(document.createTextNode(count));
}


function post_load(request)   {

   return(false);

   if(request.fn == "search") {
      search_test(request, request.name);
   }
   else if(! request.count)   {
      if(document.getElementById('search_results_section'))  {
	 search_test( { cache: "previous_search" } );
      }
   }

   if(session.load)  {
      for(var i in session.load) {
	 //alert(i);
      }
   }

}


function toggle_category_children(id, type)	{

	// Determine whether to remove or create children
	var table;
	if(table = document.getElementById("t" + id))	{

		// Table exists
		if(table.style.display == 'none')	{
			table.style.display = '';
			document.getElementById("img"+id).src = "/image/minus.gif";
		}
		else	{
			table.style.display = 'none';
			document.getElementById("img"+id).src = "/image/plus.gif";
		}
			
		return(true);
	}


	// Table does not exist, get categories & create elements

	
	// xmlhttp.js retrieve method
	var xmlhttp = new Object();

	if(window.ActiveXObject)	{
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	else	{
		xmlhttp = new XMLHttpRequest();
	}
	
	xmlhttp.open("GET", "/xml/category_children.xml?id=" + id, true);
	show_status_bar();

	xmlhttp.onreadystatechange = function()   {
	
		if(xmlhttp.readyState == 4)   {

			add_to_cache("category_children", doc);
			
			var doc = xmlhttp.responseXML;
			
			if(type == "choose")	{
				generate_category_choose_list(id, doc);
			}
			else	{
			     generate_category_browse_list(id, doc);
			}
		
			// Change toggle image to minus (expanded)
			document.getElementById("img"+id).src = "/image/minus.gif";

			hide_status_bar();
		}
	};

	xmlhttp.send(null);

	return(false);
}


function add_to_cache(type, doc)	{
	
	//var yaml = new YAML(); 
	//alert(yaml.dump(doc));


	setCookie('chochzky', 'bishes');
	if(type == "category_children")	{
		setCookie('hello', 'bishes');
	}
}


// DO NOT TOUCH
// function sample_loop_through_xml_data	{
// 
// 	// Loop through categories
// 	for(var i=0; i<doc.getElementsByTagName("category").length; i++)	{
// 		
// 		// Category block
// 		var category = doc.getElementsByTagName("category")[i];
// 		remove_text_nodes(category);
// 
// 		// Loop through category elements
// 		for(var j=0; j<category.childNodes.length; j++)	{
// 			alert(category.childNodes[j].firstChild.nodeValue);
// 		}
// 	}
// }


function generate_category_browse_list(id, doc)	{

	var ctr = document.getElementById('c' + id);
	remove_text_nodes(ctr);

	// Get parent's href and parse its parameters and values
	//alert("id" + id + " " + ctr.childNodes[1].nodeName + " 1st " + ctr.childNodes[1].firstChild + " ch "  + ctr.childNodes[1].childNodes.length);
	var phref;
	if(ctr.childNodes[1].childNodes.length == 3) { // 1st + depth
	   phref = ctr.childNodes[1].childNodes[1].href;
	} else {
	   phref = ctr.childNodes[1].childNodes[0].href; // ctr.childNodes[1].firstChild.href;
	}
	//var phref = ctr.childNodes[1].childNodes[1].href;
	var url = phref.split("?");
	var host = url[0];

	var params = url[1].split("&");
	var name = new Array();
	var value = new Array();
	var tmp;
	for (var i=0 ; i < params.length ; i++) {
	   tmp = params[i].split("=");
	   name[i] = tmp[0];
	   value[i] = tmp[1];
	} 

	var tbody = document.createElement("TBODY");

	// Loop through categories
	for(var i=0; i<doc.getElementsByTagName("category").length; i++)	{

		// Category block
		var category = doc.getElementsByTagName("category")[i];
		remove_text_nodes(category);


		// Create Item
		var tr = document.createElement("TR");
		tr.id = "c" + category.getElementsByTagName("id")[0].firstChild.nodeValue;

		var td = document.createElement("TD");
		td.setAttribute("vAlign", "top");
		td.setAttribute("align", "absmiddle");
		td.style.paddingLeft = "15px";

		if(category.getElementsByTagName("children_count")[0])	{
			
			// Category has children, create an expander option

			var img = document.createElement("IMG");
			img.id = "img" + category.getElementsByTagName("id")[0].firstChild.nodeValue;
			
			setOnClick(img, "toggle_category_children("
				+ category.getElementsByTagName("id")[0].firstChild.nodeValue
				+ ");"
			);

			img.src = "/image/plus.gif";
			img.border = 0;
			td.appendChild(img);
		}

		tr.appendChild(td);
		
		var a = document.createElement("A");
		a.setAttribute("title", category.getElementsByTagName("id")[0].firstChild.nodeValue);
		
		a.href = host + "?";
		for (var j=0 ; j < name.length ; j++) {
		   if(j > 0)
		      a.href += "&";
		   switch (name[j]) {
		      case "category_id":
		      case "within_category_id":
			 a.href += name[j] + "=" + category.getElementsByTagName("id")[0].firstChild.nodeValue;
			 break;
		      case "name":
			 a.href += name[j] + "=" + category.getElementsByTagName("u_name")[0].firstChild.nodeValue;
			 break;
		      default:
			 a.href += name[j] + "=" + value[j];
			 break;
		   }
		}
		//a.href = "/b2.html?"
		//  + "active=1"
		//  + "&within_category_id=" + category.getElementsByTagName("id")[0].firstChild.nodeValue 
		//  + "&name=" + category.getElementsByTagName("u_name")[0].firstChild.nodeValue
		//  ;
	       a.style.textDecoration = "none";

	       //setOnClick(a, "update_search_history("
	       // 		+ "'category', '" 
	       // 		+ category.getElementsByTagName("id")[0].firstChild.nodeValue
	       // 		+ "', '"
	       // 		+ category.getElementsByTagName("name")[0].firstChild.nodeValue
	       // 		+ "'); "
	       // 		+ "search_test("
	       // 		+ " { active: 1, within_category_id: '"
	       // 		+ category.getElementsByTagName("id")[0].firstChild.nodeValue
	       // 		+ "' }, '"
	       // 		+ category.getElementsByTagName("name")[0].firstChild.nodeValue
	       // 		+ "');"
	       //);
	       //a.style.cursor = "pointer";
		
		a.appendChild(document.createTextNode(
			category.getElementsByTagName("name")[0].firstChild.nodeValue
		) );
		td = document.createElement("TD");
		td.appendChild(a);
		

		
		tr.appendChild(td);
		tbody.appendChild(tr);	

		// Loop through category elements
		//for(var j=0; j<category.childNodes.length; j++)	{
			//alert(category.childNodes[j].firstChild.nodeValue);
		//}
	}

	var table = document.createElement("TABLE");
	table.id = "t" + id;
	table.appendChild(tbody);

	ctr.childNodes[1].appendChild(table);
}


function generate_category_choose_list(id, doc)	{

	var ctr = document.getElementById('c' + id);

	remove_text_nodes(ctr);

	var tbody = document.createElement("TBODY");

	// Loop through categories
	for(var i=0; i<doc.getElementsByTagName("category").length; i++)	{

		// Category block
		var category = doc.getElementsByTagName("category")[i];
		remove_text_nodes(category);


		// Create Item
		var tr = document.createElement("TR");
		tr.id = "c" + category.getElementsByTagName("id")[0].firstChild.nodeValue;
		var td = document.createElement("TD");
		td.setAttribute("vAlign", "top");
		td.setAttribute("align", "absmiddle");
		td.style.paddingLeft = "15px";

		if(category.getElementsByTagName("children_count")[0])	{
			
			// Category has children, create an expander option

			var img = document.createElement("IMG");
			img.id = "img" + category.getElementsByTagName("id")[0].firstChild.nodeValue;

			setOnClick(img, "toggle_category_children("
				+ category.getElementsByTagName("id")[0].firstChild.nodeValue
				+ ", "
				+ "'choose');"
			);

			img.src = "/image/plus.gif";
			img.border = 0;
			td.appendChild(img);
		}

		tr.appendChild(td);
		
		
		if(category.getElementsByTagName("children_count")[0])	{
			td = document.createElement("TD");
			td.appendChild(document.createTextNode(category.getElementsByTagName("name")[0].firstChild.nodeValue));
		}
		else	{

			var a = document.createElement("A");
			a.setAttribute("title", category.getElementsByTagName("id")[0].firstChild.nodeValue);
			a.href = "/new_item.html?category_id=" + category.getElementsByTagName("id")[0].firstChild.nodeValue;
			a.appendChild(document.createTextNode(
				category.getElementsByTagName("name")[0].firstChild.nodeValue
			) );
			td = document.createElement("TD");
			td.appendChild(a);
		}	

		
		tr.appendChild(td);
		tbody.appendChild(tr);	

		// Loop through category elements
		//for(var j=0; j<category.childNodes.length; j++)	{
			//alert(category.childNodes[j].firstChild.nodeValue);
		//}
	}

	var table = document.createElement("TABLE");
	table.id = "t" + id;
	table.appendChild(tbody);

	ctr.childNodes[1].appendChild(table);
}


function remove_all_nodes(element)	{
   
   	if(! element.hasChildNodes())	{
		return(false);
	}

	for(var i=0; i<element.childNodes.length; i++)	{
		element.removeChild(element.childNodes[i]);
	}
}


function remove_text_nodes(tbody)   {
   
   	if(! tbody.hasChildNodes())	{
		return(false);
	}

	for(var i=0; i<tbody.childNodes.length; i++) {
		
		if(tbody.childNodes[i].nodeType == 3)  {
			tbody.removeChild(tbody.childNodes[i]);
		}
	}
}


function remove_empty_text_nodes(tbody)   {
   
	if(! tbody.hasChildNodes())	{
		return(false);
	}

	for(var i=0; i<tbody.childNodes.length; i++) {

		if(tbody.childNodes[i].nodeType == 3 && tbody.childNodes[i].nodeValue.match(/^\s*$/))	{
			tbody.removeChild(tbody.childNodes[i]);
		}
	}
}


function encode64(input) {
   // Function retrieved from http://rumkin.com/tools/compression/base64.php

   var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   do {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);

      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
         enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
         enc4 = 64;
      }

      output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + 
         keyStr.charAt(enc3) + keyStr.charAt(enc4);
   } while (i < input.length);
   
   return output;
}


function decode64(input) {
   // Function retrieved from http://rumkin.com/tools/compression/base64.php

   var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
   input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

   do {
      enc1 = keyStr.indexOf(input.charAt(i++));
      enc2 = keyStr.indexOf(input.charAt(i++));
      enc3 = keyStr.indexOf(input.charAt(i++));
      enc4 = keyStr.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output = output + String.fromCharCode(chr1);

      if (enc3 != 64) {
         output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
         output = output + String.fromCharCode(chr3);
      }
   } while (i < input.length);

   return output;
}


function update_search_history(type, id, name)	{
show_status_text("TYPE:" + type + ", ID:" + ", NAME:" + name);
	var history = document.getElementById("search_history");
	remove_empty_text_nodes(history);
	
	var length = 0;
	for(var i=0; i<history.childNodes.length; i++)	{
		if(history.childNodes[i].nodeName == "A")	{
			if(history.childNodes[i].firstChild.nodeType == 3)	{
				length += history.childNodes[i].firstChild.length;
			}
		}
		if(length > 70)	{
			history.removeChild(history.childNodes[i]);
			history.removeChild(history.childNodes[i]);
		}
	}

	if(history.childNodes.length > 0)	{
		if(history.firstChild.firstChild.nodeValue == name)	{
			return(false);
		}
	}
	
	var a = document.createElement("A");
	
	history.insertBefore(document.createTextNode(", "), history.firstChild);
	history.insertBefore(a, history.firstChild);
	
	a.style.textDecoration = "underline";
	a.href = "#";
	setOnClick(a, "search_test( { active: 1, within_category_id: '"+id+"' }, '"+name+"');");
	a.appendChild(document.createTextNode(name));

	show_status_text("update_search_history done");
}


function show_status_bar()	{

	var bar = document.getElementById('status_bar');
	if(! bar)	  {
	  return(false);
        }

	var width = (window.innerWidth) ? window.innerWidth : document.body.offsetWidth;

	bar.style.position = "absolute";
	bar.style.top = '0px';
	bar.style.left = (width - bar.width) + 'px';
	bar.style.visibility = "visible";
}


function clear_status_text()  {
	
	var box = document.getElementById('status_text');
	
	while(box.hasChildNodes())  {
	   box.removeChild(box.firstChild);
	}

	var date = new Date();
	box.appendChild(document.createTextNode("cleared " + date.getTime()));
	box.appendChild(document.createElement("BR"));
	return(true);
}


function show_status_text(text)	{

	// return(false);

	var box = document.getElementById('status_text');

	box.insertBefore(document.createElement("BR"), box.firstChild);
	box.insertBefore(document.createTextNode(text), box.firstChild);

	var width = (window.innerWidth) ? window.innerWidth : document.body.offsetWidth;

	box.style.color = "black";
	box.style.fontSize = "11px";
	box.style.position = "absolute";
	box.style.top = '100px';
	box.style.left = (width - 275) + 'px';
	box.style.visibility = "visible";
}


function hide_status_text()	{
	//var bar = document.getElementById('status_text');
	//bar.style.visibility = "hidden";
}


function hide_status_bar()	{
	var bar = document.getElementById('status_bar');
	if(bar)	  {
	 bar.style.visibility = "hidden";
      }
}


function open_spell_checker(name)	{

	// then call the openChecker() method.
	// var text1 = document.login.name;
	// var textarea1 = document.login.comment;
	// var speller = new spellChecker( text1, textarea1 );
	// speller.openChecker();
	
	var textarea = document.getElementById(name);
	var text = encodeURIComponent(textarea.value);
	
	if(text.length > 5000)	 {
           text = text.substr(0, 5000);
        }

	window.open("/popup_spell_check.html?comment=" + text,"spellchecker","menu=no,width=440,height=350,top=70,left=120,resizable=no,status=yes");

}




// Functions related to choosing a timeout for blind auctions
function nozeros(input)	{
	
	return(input);
	
	if((input.length > 1) && (input.substr(0,1) == "0"))	{
		return input.substr(1);
	}
	else	{
		return( input);
	}
}


function GetDay(intDay)	{
	
	var DayArray = new Array("Sunday", "Monday", "Tuesday", "Wednesday","Thursday", "Friday", "Saturday");
	return DayArray[intDay];
}


function month_name(month)	{
	var MonthArray = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
	return MonthArray[month];
}

function GetMonth(intMonth)	{
	var MonthArray = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
	return MonthArray[intMonth];
}


function getDateStrWithDOW(myday)   {

   var year = myday.getYear();
   if(is_ie && year < 1000)   {
      year+=1900;
   }

   var mydayStr = GetDay(myday.getDay()) + ", ";
   mydayStr += GetMonth(myday.getMonth()) + " " + myday.getDate();
   mydayStr += ", " + year;
   
   return(mydayStr);
}


function getTimeStr(mydate)	{
	
	var curDateTime = mydate;
	var curHour = curDateTime.getHours();
	var curMin = curDateTime.getMinutes();
	var curSec = curDateTime.getSeconds();
	var curAMPM = " AM";
	var curTime = "";
	
	if (curHour >= 12)	{
		
		curHour -= 12;
		curAMPM = " PM";
	}
	
	if (curHour == 0) curHour = 12;
	curTime = curHour + ":" + ((curMin < 10) ? "0" : "") + 
	curMin + ":" + ((curSec < 10) ? "0" : "") + 
	curSec + curAMPM;
	
	return(curTime);
}


function unixtimetodate(myunixtime)	{
	var theDate = new Date(myunixtime * 1000);
	return(theDate);
}

function datetounixtime(theDate)	{
	
	var yy = theDate.getFullYear();
	var mm = theDate.getMonth() ;
	var dd = theDate.getDate();
	var hh = theDate.getHours();
	var min = theDate.getMinutes();
	var sec = theDate.getSeconds();         		
	var humDate = new Date(Date.UTC(yy,mm,dd,hh,min,sec));
	return (humDate.getTime()/1000.0);
}

function timeout_change()	{

	var cboDay = document.getElementById("cboDay");		
	var cboMonth = document.getElementById("cboMonth");
	var cboYear = document.getElementById("cboYear");
	var cboHour = document.getElementById("cboHour");
	var cboMinutes = document.getElementById("cboMinutes");
	var cboAMPM = document.getElementById("cboAMPM");
	var theDate = unixtimetodate(document.forms["frm"].timeout.value);
	var yy = theDate.getFullYear();
	var mm = theDate.getMonth();
	var dd = theDate.getDate();
	var hh = theDate.getHours();
	var min = theDate.getMinutes();
	var sec = theDate.getSeconds();        
	cboDay.options[dd-1].selected = "true";
	cboMonth.options[mm].selected = "true";
	
	for(i=0;i<cboYear.length;i++)	{
		
		if (nozeros(cboYear.options[i].value) == yy)	{
			
			cboYear.options[i].selected = "true";
		}
	}
	
	if (hh>12)	{ 
		hh = hh - 12;
		cboAMPM.options[1].selected = "true"; 
	}
	else	{
		cboAMPM.options[0].selected = "true";
	}
	cboHour.options[hh-1].selected = "true";
	cboMinutes.options[min-1].selected = "true";
	
	return(true);
}

function date_change()	{
	
	var Day = document.forms["frm"].day.selectedIndex + 1;
	var Month = document.forms["frm"].month.selectedIndex;
	var Hour = document.forms["frm"].hour.selectedIndex + 1;
	var Min = document.forms["frm"].minutes.selectedIndex + 1;
	var Year = document.forms["frm"].year.options[document.forms["frm"].year.selectedIndex].value;
	var ampm = document.forms["frm"].ampm.options[document.forms["frm"].ampm.selectedIndex].value;
	
	if (ampm == "pm") {
	      Hour = Hour + 12;       
	}
	
	var theDate = new Date(Year,Month,Day,Hour,Min);   
	var unixtime = datetounixtime(theDate);
	var tagSpan = document.getElementById("timeout_s");
	tagSpan.innerHTML = getDateStrWithDOW(theDate) + "[" + getTimeStr(theDate) + "]"; 
	document.forms["frm"].timeout.value = unixtime;

	return(true);
}


function toggle_ampm(obj)	{
	
	var date = new Date();
	var ampm;
	
	if(obj.firstChild)	{
		ampm = obj.firstChild.nodeValue;
		obj.removeChild(obj.firstChild);
	}
	else	{
		if(date.getHours() < 13)	{
			ampm = "PM";
		}
		else	{
			ampm = "AM";
		}
	}
	
	if(ampm.toUpperCase() == "AM")	{
		obj.appendChild(document.createTextNode("PM"));
		change_timeout(43200);
	}
	else	{
		obj.appendChild(document.createTextNode("AM"));
		change_timeout(-43200);
	}
}


function change_timeout(obj)  {

   var unixtime = 0;

   if(obj.id == "timeout_minutes")  {
      
      if(session.key.shiftKey)	 {
	 unixtime -= 60;
      }
      else  {
	 unixtime += 60;
      }
   }
   else if(obj.id == "timeout_hours")  {
      
      if(session.key.shiftKey)	 {
	 unixtime -= 3600;
      }
      else  {
	 unixtime += 3600;
      }
   }
   else if(obj.id == "timeout_ampm")   {
      
      if(obj.firstChild)   {
	 
	 if(obj.firstChild.nodeValue.toUpperCase() == "AM") {
	    // Changing to PM - Add 12 hours
	    unixtime += 43200;
	 }
	 else  {
	    unixtime -= 43200;
	 }
      }
   }

   var timeout_unixtime = document.getElementById("timeout_unixtime");
   timeout_unixtime.value = parseInt(timeout_unixtime.value) + unixtime;

   update_timeout_display(timeout_unixtime.value);
}


function update_timeout_display(unixtime)   {

   var date = new Date(unixtime * 1000);
   
   var hours = document.getElementById("timeout_hours");
   var minutes = document.getElementById("timeout_minutes");
   var ampm = document.getElementById("timeout_ampm");

   if(hours.firstChild)	{
      hours.removeChild(hours.firstChild);
      var hour = date.getHours();
      if(hour > 12) {
	 hour = hour - 12;
      }
      if(hour == 0)  {
	 hour = 12;
      }
      hours.appendChild(document.createTextNode(hour));
   }
   if(minutes.firstChild)	{
      minutes.removeChild(minutes.firstChild);
      var minute = date.getMinutes();
      
      if(minute < 10)	{
	 minute = "0" + minute;
      }
      minutes.appendChild(document.createTextNode(minute));
   }
   if(ampm.firstChild)	{
      ampm.removeChild(ampm.firstChild);
      if(date.getHours() < 12) {
	 ampm.appendChild(document.createTextNode("AM"));
      }
      else  {
	 ampm.appendChild(document.createTextNode("PM"));
      }
   }

   var f_unixtime_display = document.getElementById("f_unixtime_display");
   if(f_unixtime_display.firstChild)   {
      f_unixtime_display.removeChild(f_unixtime_display.firstChild);
   }

   var f_unixtime = month_name(date.getMonth()) + " " + date.getDate() + ", ";
   if(is_ie)   {
      f_unixtime = date.getYear();
   }
   else	 {
      f_unixtime = date.getYear()+1900;
   }

   f_unixtime_display.appendChild(document.createTextNode(f_unixtime));
   
   var timeout_display = document.getElementById("timeout_display");
   
   if(timeout_display.firstChild)   {
      timeout_display.removeChild(timeout_display.firstChild);
   }
   timeout_display.appendChild(document.createTextNode(
   hours.firstChild.nodeValue + ":" + minutes.firstChild.nodeValue + ampm.firstChild.nodeValue + " on " + GetDay(date.getDay()) + " " + month_name(date.getMonth()) + " " + date.getDate() + ", " + (date.getYear()+1900)
   ));
}


function reset_time(day)   {

	var hours = document.getElementById("timeout_hours");
	var minutes = document.getElementById("timeout_minutes");
	var ampm = document.getElementById("timeout_ampm");

	var date = new Date();

	document.getElementById("timeout_unixtime").value = date.getTime()/1000;

	if(hours.firstChild)	{
		hours.removeChild(hours.firstChild);
	}

	if(minutes.firstChild)	{
		minutes.removeChild(minutes.firstChild);
	}

	if(ampm.firstChild)	{
		ampm.removeChild(ampm.firstChild);
	}

	change_hours(hours);
	change_minutes(minutes);
	toggle_ampm(ampm);
}


function change_minutes(obj)	{
	
	var date = new Date();
	var minutes;
	
	if(obj.firstChild)	{
		minutes = parseInt(obj.firstChild.nodeValue);
		obj.removeChild(obj.firstChild);
	}
	else	{
		minutes = date.getMinutes();
	}

	if(session.key.shiftKey)	{
		if(minutes < 1)	{
			minutes = "59";
		}
		else	{
			minutes--;
			if(minutes < 10)	{
				minutes = "0" + minutes;
			}
		}
		change_timeout(-60);
	}
	else	{
		if(minutes > 58)	{
			minutes = "00";
		}
		else	{
			minutes++;
			if(minutes < 10)	{
				minutes = "0" + minutes;
			}
		}
		
		change_timeout(60);
	}

	obj.appendChild(document.createTextNode(minutes));
}


function update_inverse_status() {

   var start_amount_num = (document.getElementById("start_amount").value*1);
   var decrement_amount_num = (document.getElementById("decrement_amount").value*1);
   var minimum_amount_num = (document.getElementById("minimum_amount").value*1);

   var start_amount_str = (start_amount_num*1).toDecimals(2);
   var decrement_amount_str = (decrement_amount_num*1).toDecimals(2);
   var minimum_amount_str = (minimum_amount_num*1).toDecimals(2);

   if(start_amount_num <= 0) {
      return(false);
   }
   if(decrement_amount_num <= 0) {
      return(false);
   }
   if(minimum_amount_num <= 0) {
      return(false);
   }

   var days = document.getElementById("decrement_interval_days").value*1;
   var hours = document.getElementById("decrement_interval_hours").value*1;
   var minutes = document.getElementById("decrement_interval_minutes").value*1;

   var interval = 0;
   
   if(days) {
      // Add days in seconds
      interval += (days * 86400);
   }
   if(hours)   {
      // Add hours in seconds
      interval += (hours * 3600);
   }
   if(minutes) {
      // Add minutes in seconds
      interval += (minutes * 60);
   }
   
   var message = document.createElement("SPAN");
   
   if(start_amount_num < minimum_amount_num || start_amount_num < minimum_amount_num) {
      // Logic errors exist

      if(start_amount_num < minimum_amount_num)   {
	 message.appendChild(document.createTextNode("The Starting amount cannot be less than the minimum amount."));
      	 message.appendChild(document.createElement("BR"));
      }
      if(start_amount_num < decrement_amount_num) {
         message.appendChild(document.createTextNode("The Starting amount cannot be less than the decrement amount."));
         message.appendChild(document.createElement("BR"));
      }
         
      message.appendChild(document.createElement("BR"));
      message.appendChild(document.createTextNode("Please adjust your values."));
   
   }
   else if(start_amount_num && decrement_amount_num && minimum_amount_num && interval)   {
      // All required information is present - update display

      message = "Auction will begin at $" + start_amount_num;
      message += ", and decrease by $" + decrement_amount_num;
      message += " every ";
      if(days > 1) {
	 message += days + " Days";
      }
      if(hours || days) {
	 if(days > 1 && hours > 1)  {
	    message += ", ";
	 }
	 
	 if(days == 1)  {
	    message += (parseInt(hours) + 24) + " Hours";
	 }
	 else if(hours > 1)   {
	    message += hours + " Hours";
	 }
      }
      if(minutes)   {
	 if(hours > 1 || days > 0)  {
	    message += ", ";
	 }
	 
	 if(hours == 1) {
	    message += (parseInt(minutes) + 60) + " Minutes";
	 }
	 else  {
	    message += minutes + " Minutes";
	 }
      }
      
      message += " until the amount decreases to $" + minimum_amount_str + ".";
      var timeout = compute_inverse_timeout(start_amount_num, minimum_amount_num, decrement_amount_num, interval);

      if(((timeout*1000)-(new Date()).getTime()) > 2592000000) {
	 // Auction > 30 days, trim
	 //	 timeout = ((new Date()).getTime() + 2592000000)/1000;
	 // timeout--;
	 //	 message += "  Auctions last a maximum of 30 days, so this auction will be cut short to that amount.  ";
	 // recompute decrement_amount to fit auction in 30 days
	 var nint = Math.floor( (30*60*60*24)/interval ); // # of intervals in 30 days
	 var suggested_decrement_amount_num = Math.ceil((start_amount_num - minimum_amount_num)/nint);
	 var suggested_timeout = compute_inverse_timeout(start_amount_num, minimum_amount_num, suggested_decrement_amount_num, interval);
	 // alert("suggested timeout " + suggested_timeout + " " + getCalendarDate(suggested_timeout*1000) + getClockTime(suggested_timeout*1000));
	  message += "  Auctions last a maximum of 30 days, so this auction must be modified to fit in that interval.";
	  message += " Change 'Decreasing Amount' to $" + suggested_decrement_amount_num + " to end the auction in 30 days.";
	  //  message += ", auction will end on " + getCalendarDate(suggested_timeout*1000) + ", at " + getClockTime(suggested_timeout*1000) + ".";

      } else {
	      message += "  Auction will end on " + getCalendarDate(timeout*1000);
	      message += ", at " + getClockTime(timeout*1000) + ".";
      }
      message = document.createTextNode(message);
   }

   // set timeout_unixtime field
   var timeout_unixtime = document.getElementById("timeout_unixtime");
   timeout_unixtime.value = timeout*1000;
   
   var container = document.getElementById("inverse_status").parentNode;
   container.removeChild(document.getElementById("inverse_status"));
   
   var div = document.createElement("DIV");
   div.id = "inverse_status";
   div.appendChild(message);
   container.appendChild(div);
}


var timeout = new Object();

function update_blind_status(obj)   {

   if(timeout["year"] && timeout["month"] && timeout["day"])   {
      // Day currently highlighted - remove highlight
      var obj2 = document.getElementById(timeout.year + "-" + timeout.month + "-" + timeout.day);
      obj2.style.backgroundColor = "";
      obj2.style.color = "";
   }

   if(obj)  {
      
      if(obj["year"])   {
         timeout.year = parseInt(obj.year);
      }
      if(obj["month"])  {
         timeout.month = parseInt(obj.month);
      }
      if(obj["day"]) {
         timeout.day = parseInt(obj.day);
      }
   }

   //if(timeout["year"] && timeout["month"] && timeout["day"])   {
   //   // Day currently highlighted - remove highlight
   //   // var obj2 = document.getElementById(timeout.year + "-" + timeout.month + "-" + timeout.day);
   //   // obj2.style.backgroundColor = "";
   //   // obj2.style.color = "";
   //}
   //else	 {
   //   return(false);
   //}
   
   if(document.getElementById("blind_timeout_hour"))  {
      timeout.hour = document.getElementById("blind_timeout_hour").value;
   }
   if(document.getElementById("blind_timeout_minute"))	 {
      timeout.minute = document.getElementById("blind_timeout_minute").value;
   }
   if(document.getElementById("blind_timeout_ampm"))  {
      timeout.ampm = document.getElementById("blind_timeout_ampm").value;
   }

  
   //alert(timeout.year + "-" + timeout.month + "-" + timeout.day);
   // Highlight selected cell
   var cell = document.getElementById(timeout.year + "-" + timeout.month + "-" + timeout.day);
   cell.style.backgroundColor = "#00a766";
   cell.style.color = "white";

   // Check entered date against now() and display error message if entered a earlier date
   var hour = parseInt(timeout.hour);
   hour = ampm_to_absolute(hour, timeout.ampm);    // Convert hour from AMPM to 0-23 
   var date = new Date(timeout.year, timeout.month-1, timeout.day, hour, timeout.minute, 0);
   var now = new Date();
   
   // Build the message
   var message = document.createElement("SPAN");
   if (date.getTime() > now.getTime()) {
      message = "Auction will end on " + getCalendarDate(date.getTime()) + " at " + getClockTime(date.getTime());

      var minimum_amount = (document.getElementById("minimum_amount").value*1).toFixed(2);
      if(minimum_amount.match(/^(\d+|\d+\.\d+)$/))  {
           message += ", but only if a bid has been made for $";
	   message += minimum_amount + " or higher.";
      }
      message = document.createTextNode(message);
   } else {
       message.appendChild(document.createTextNode("The end date cannot be earlier than actual date."));
       message.appendChild(document.createElement("BR"));
       message.appendChild(document.createElement("BR"));
       message.appendChild(document.createTextNode("Please adjust your values."));
   }

   var timeout_unixtime = document.getElementById("timeout_unixtime");
   
   //alert("blind_date: " + timeout.year + " " + timeout.month + " " + timeout.day + "  " + timeout.hour + "(" + hour + ") " + timeout.minute);
   //alert("Date " + date + " UTC: " + date.toUTCString());
   //alert("unixtime " + date.getTime()/1000);
   timeout_unixtime.value = date.getTime();

   var container = document.getElementById("blind_status").parentNode;
   container.removeChild(document.getElementById("blind_status"));

   var div = document.createElement("DIV");
   div.id = "blind_status";
   div.appendChild(message);
   container.appendChild(div);
}

// Convert hour from AMPM to 0-23 
function ampm_to_absolute (hour, ampm) {

	if(ampm.toUpperCase() == "PM")   {
		if (hour != 12)  // 12PM -> 12
			hour += 12; 
	} else { 
		if (hour == 12)  // 12 AM -> 0
			hour = 0;
	}
	return hour;
}

// Timezone offset, f ex:  GMT-3
function timezone_gmt_offset(obj) {
	 if (obj)	 
	    d = obj;
	 else 
	    d = new Date();

	 var offset = d.getTimezoneOffset()/60;
	 return ( "GMT" + (offset>0 ? '-' : '+') + (offset>0 ? offset : -offset) );
}

function compute_inverse_timeout(start, minimum, decrement, interval) {
      // Calculate timeout datetime
      var timeout = parseInt(new Date().getTime()/1000);
      for(var i=start; i>minimum; i=i-decrement)   {
	 timeout += interval;
	 // round to 4 decimals to avoid arithmetic errors (start = 5, decrement = 0.05, minimum 4.75 takes 1 extra interval)
	 i = Math.round(i*10000)/10000;
	 //alert('i ' + i);
      }
      return timeout;
}

Number.prototype.toDecimals = function(n) {
    n=(isNaN(n))?
        2:
        n;
    var
        nT=Math.pow(10,n);
    function pad(s){
            s=s||'.';
            return (s.length>n)?
                s:
                pad(s+'0');
    }
    return (isNaN(this))?
        this:
        (new String(
            Math.round(this*nT)/nT
        )).replace(/(\.\d*)?$/,pad);
}


function getCalendarDate(date)
{
   if(date) {
      date = new Date(date);
   }
   else	 {
      date = new Date();
   }
   
   var months = new Array(13);
   months[0]  = "January";
   months[1]  = "February";
   months[2]  = "March";
   months[3]  = "April";
   months[4]  = "May";
   months[5]  = "June";
   months[6]  = "July";
   months[7]  = "August";
   months[8]  = "September";
   months[9]  = "October";
   months[10] = "November";
   months[11] = "December";
   var monthnumber = date.getMonth();
   var monthname   = months[monthnumber];
   var monthday    = date.getDate();
   var year        = date.getYear();
   if(year < 2000) { year = year + 1900; }
   var dateString = monthname + 
                    ' ' + 
                    monthday + 
                    ', ' + 
                    year;
   return dateString;
} // function getCalendarDate()

function getClockTime(date)
{
   if(date) {
      date = new Date(date);
   }
   else	 {
      date = new Date();
   }
   
   var hour   = date.getHours();
   var minute = date.getMinutes();
   var second = date.getSeconds();
   var ap = "AM";
   if (hour   > 11) { ap = "PM";             }
   if (hour   > 12) { hour = hour - 12;      }
   if (hour   == 0) { hour = 12;             }
   if (hour   < 10) { hour   = "0" + hour;   }
   if (minute < 10) { minute = "0" + minute; }
   if (second < 10) { second = "0" + second; }
   var timeString = hour + 
                    ':' + 
                    minute + 
                    ':' + 
                    second + 
                    " " + 
                    ap +
		    " " + timezone_gmt_offset(date);
   return timeString;
} // function getClockTime()

//-->

function setOnClick(obj, value)	 {
   if(is_ie)   {
      obj.onclick = new Function(value);
   }
   else  { 
      obj.setAttribute("onClick", value); 
   }

   return(true);
}


function getTimeZoneOffset()  {
   var rightNow = new Date();
   var date1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);
   var date2 = new Date(rightNow.getFullYear(), 6, 1, 0, 0, 0, 0);
   var temp = date1.toGMTString();
   var date3 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
   var temp = date2.toGMTString();
   var date4 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
   var hoursDiffStdTime = (date1 - date3) / (1000 * 60 * 60);
   var hoursDiffDaylightTime = (date2 - date4) / (1000 * 60 * 60);

   if (hoursDiffDaylightTime == hoursDiffStdTime)  {
      return(hoursDiffStdTime);
   }
   else	 {
      return(hoursDiffDaylightTime);
   }

   //    alert("Time zone is GMT " + hoursDiffStdTime + ".\nDaylight Saving Time is NOT observed here.");
   // } else {
   //    alert("Time zone is GMT " + hoursDiffStdTime + ".\nDaylight Saving Time is observed here.");
   // }
}


function checkShortDescription(obj) {
   if(obj.value.length > 40)  {
      alert(obj.value.length);
   }
}


