function $(id) {
	return document.getElementById(id);
}

var i = 0;
var nrOfItems = 0;
var optionName = "";
var optionName2 = "";
var optionValue
var closingUrl = "";
var statusTicker = 0;
var q = "";
function updateFields(nrItems)
{

	
	if(nrOfItems == 0)
		nrOfItems = nrItems;
//Test Data
	var checkStatus = false;
	var k = 0;
	for(k = 0; k < nrItems; k++)
	{
//	alert(k);
		if(k == 0)
		{
			checkStatus = false;
			closingUrl = "http://www.warehog.com/items/getItemsStatus?";
		}
		var startPrice = "";
		var endPrice = "";
		var timeRemaining = "";
		var auctionPeriod = "";
		var priceRange = "";
		var currency = "";
		var itemID = "";
		var highBid = 0.0;
                var nrBids = 0;
		var statusHidden = "";
		
		var startPriceObj = "startPrice" + k;
		var endPriceObj = "endPrice" + k;
		var timeRemainingObj = "timeRemainingx" + k;
		var auctionPeriodObj = "auctionPeriod" + k;
		var currencyObj = "currency" + k;
		var IDObj = "itemID" + k;
		var nrBidsObj = "bids" + k;
                var highBidObj = "bidAmount" + k;
		var statusObj = "status" + k;
		var statusHiddenObj = "statusHidden" + k;
                
	//	alert(startPriceObj);
		startPrice = $(startPriceObj).innerHTML;
		
		endPrice = $(endPriceObj).innerHTML;
		timeRemaining = $(timeRemainingObj).innerHTML;
		auctionPeriod = $(auctionPeriodObj).innerHTML;
		currency = $(currencyObj).innerHTML;
		itemID = $(IDObj).innerHTML;
		if($(highBidObj))
			highBid = $(highBidObj).innerHTML;
		if($(nrBidsObj))
			nrBids = $(nrBidsObj).innerHTML;
		
                if($(statusHiddenObj))
			statusHidden = $(statusHiddenObj).innerHTML;
		//alert(closingUrl);
		priceRange = startPrice - endPrice;
		//alert(priceRange);		
		var timeRemainingDisplay = "timeRemaining" + k;
		var currentPriceDisplay = "currentPrice" + k;
		
		//alert(timeRemaining);		
		
                if(statusHidden == "selling")
                    timeRemaining = updateTimeDisplay(timeRemainingDisplay, timeRemaining);
                else
                    timeRemaining = updateTimeDisplay(timeRemainingDisplay, 0);
		
		var portionComplete = 1 - (timeRemaining/(auctionPeriod*1000));
	  //alert(portionComplete);
	
		var currentPrice = startPrice - (priceRange*portionComplete);
		//alert(currentPrice);
		currentPrice = addTrailingZero(currentPrice);
		//alert($(currentPriceDisplay));
		//alert(statusHidden);
		if(statusHidden == "selling")
		{
			$(currentPriceDisplay).innerHTML = currency + CommaFormatted(currentPrice);
			if(timeRemaining > 0)
                            $(timeRemainingObj).innerHTML = timeRemaining;
                        else
                            $(timeRemainingObj).innerHTML = "";
		}
		else if (statusHidden == "expired")
		{
			//alert("Classified");
                        $(currentPriceDisplay).innerHTML = currency + CommaFormatted(currentPrice);
			$(timeRemainingObj).innerHTML = "";
		}
		else
		{
			//$(timeRemainingObj).innerHTML = "closed";	
			$(currentPriceDisplay).innerHTML = "Closed";
                        $(timeRemainingObj).innerHTML = "";
		}
		
		
		// if less than 30 seconds left in any auction check status of all before we update timers again
		if((timeRemaining < 30000) || ((currentPrice - .05 <= highBid) && (nrBids > 0)))
		{
			//alert(statusHidden);
			if(statusHidden == "selling")
			{
				//alert("highBid=" + highBid + " currentPrice = " + currentPrice + " timeRem=" + timeRemaining);
				//$(statusObj).innerHTML = "Auction Closing...";
				closingUrl = closingUrl + "itemID" + (k + 1) + "=" + itemID + "&";
				checkStatus = true;
			}
		}
		


	}
	
	//checkStatus = true;//test flag - remove - to turn this feature off set this flag to false.
	checkStatus = false;
	if(statusTicker > 9)
	{
		if(checkStatus == true)
		{
			checkAuctionStatus(closingUrl);
		}
		statusTicker = 0;
	}	
	
	statusTicker++;
	
	q=setTimeout('updateFields(nrOfItems)', 1000);	
	
}

/*
* Come back to this: can pass in nrItems to setTimeout, dunno why
*
*/


/*
inputs: startDate, endDate, startPrice, endPrice

secondRemaining = endDate-now

if startDate = 0, endDate = 1, then pos == (now - startDate)/(endDate - startDate)
currentPrice = startPrice + ((endPrice-startPrice) * pos)
*/

function getCurrentPrice(startPrice, endPrice, expired, currency, currentPriceDisplay)
{
	/*
		Start		End		Expired		CurrentPrice
		210			0					1				(0)   0 + (210-0)* (1-1) = 0
		210			0					0.5			(105) 0 + (210-0)*(1- 0.5 = 105
		210			0					0.25		(52.5) 0 + (210-0)*(1 - 0.25) = 147.5
		
		
	*/
	var currentPrice = endPrice + ((startPrice-endPrice) * (1-expired));
	//alert("currency = " + currency);
	//alert("startPrice = " + startPrice);
	//alert("endPrice = " + endPrice);

	currentPrice = addTrailingZero(currentPrice);
	$(currentPriceDisplay).innerHTML = "Current Price: " + currency + currentPrice;
}

function addTrailingZero(currentPrice)
{

	//1223.4 -> 1223.40
	var negNum = false;
	if(currentPrice < 0)
	{
		negNum = true;
		currentPrice = currentPrice * -1;
	}
	var integerPart = Math.floor(currentPrice);
	var decimalPart = Math.round(((currentPrice - integerPart) * 100));
	//alert(integerPart);
	
	
	if(decimalPart < 10)
		decimalPart += "0";
	if(decimalPart >=100 )
	{
	  decimalPart = "00";	
	  integerPart += 1;
	 }
	currentPrice = integerPart + "." + decimalPart;
	//alert(decimalPart);
	if(negNum == true)
	{
		currentPrice = "-" + currentPrice;
	}
	return currentPrice;
}


function updatePriceDisplay(currentPriceDisplay, currentPrice, endPrice, timeRemaining, currency)
{

	var currentPriceString = "";	
	if(timeRemaining <= 0)
		return currentPrice;
	var dropPerSecond = (currentPrice - endPrice)/(timeRemaining/1000);
	
	currentPrice = currentPrice - dropPerSecond;
	currentPrice = addTrailingZero(currentPrice);
	
	$(currentPriceDisplay).innerHTML = currency + currentPrice;
	
	return currentPrice;
}

function checkAuctionStatus(closingUrl)
{
	optionName = "closing";
	//alert(closingUrl);
	askWH(closingUrl);

}

function updateTimeDisplay(timeRemainingDisplay, timeRemaining)
{
	//alert(timeRemaining);
	if(timeRemaining < 1000)
        {
            if($(timeRemainingDisplay) != null)
                $(timeRemainingDisplay).innerHTML = " ";
            return 0;
        }
	var timeRemainingString = "";	
	
	timeRemaining = timeRemaining - 1000;
	var days = Math.floor(timeRemaining/1000/60/60/24);
	//alert(days);
	var hours = Math.floor(timeRemaining/1000/60/60 - (days * 24));
	//alert(hours);
	var minutes = Math.floor(timeRemaining/1000/60 -(hours * 60) - (days * 24 * 60));
	var seconds = Math.floor(timeRemaining/1000 - (minutes * 60) - (hours * 60 * 60) - (days * 24 * 60 * 60));
	
	//pad
	
	hours = padWithLeadingZeros(hours);	
	minutes = padWithLeadingZeros(minutes);	
	seconds = padWithLeadingZeros(seconds);	
		
	if(days > 0)
		timeRemainingString = days + " days, ";   
	timeRemainingString += hours + ":" + minutes + ":" + seconds;
	//alert(timeRemainingString);
	//alert(timeRemainingDisplay);
	$(timeRemainingDisplay).innerHTML = timeRemainingString;
	//alert(timeRemainingString);
	
	return timeRemaining;
}
function getTimeRemaining(startDate, endDate, currency, startPrice, endPrice, timeRemainingDisplay, currentPriceDisplay, now)
{
	
	//alert("now = " + now);
	//alert("startDate = " + startDate);
	//alert("endDate = " + endDate);
	var localNow = new Date();
	var delta = localNow.getTime() - now;
  
  startDate = startDate - delta;
  endDate = endDate - delta;
	var expired = 1;
	if(now < startDate){
		expired = 0;
	}
	else{
		if(endDate > startDate)
			expired = (now - startDate)/(endDate - startDate);
	}
	//alert("expired = " + expired);
	var duration = endDate - startDate;
	
	var timeExpired = duration * expired;
		
	var timeRemaining = duration - timeExpired;
	//alert(timeRemaining);
	//alert(duration);
	//alert(duration - timeRemaining);
	
	//alert(timeExpired);
	var timeRemainingString = "";
	var days = Math.floor(timeRemaining/1000/60/60/24);
	//alert(days);
	var hours = Math.floor(timeRemaining/1000/60/60 - (days * 24));
	//alert(hours);
	var minutes = Math.floor(timeRemaining/1000/60 -(hours * 60) - (days * 24 * 60));
	var seconds = Math.floor(timeRemaining/1000 - (minutes * 60) - (hours * 60 * 60) - (days * 24 * 60 * 60));
	
	//pad
	
	hours = padWithLeadingZeros(hours);	
	minutes = padWithLeadingZeros(minutes);	
	seconds = padWithLeadingZeros(seconds);	
		
	if(days > 0)
		timeRemainingString += days + " days, ";   
	timeRemainingString += hours + ":" + minutes + ":" + seconds;
	
	$(timeRemainingDisplay).innerHTML = timeRemainingString;
	
	getCurrentPrice(startPrice, endPrice, expired, currency, currentPriceDisplay);
	
}

function padWithLeadingZeros(i)
{
	if(i < 10)
		i = "0" + i;
	return i;	
}

function CommaFormatted(amount)
{
	var negNum = false;
	if(amount > 0)
	{
	var delimiter = ","; // replace comma if desired
	var a = amount.split('.',2)
	var d = a[1];
	var i = parseInt(a[0]);
	if(isNaN(i)) { return ''; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while(n.length > 3)
	{
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) { a.unshift(n); }
	n = a.join(delimiter);
	if(d.length < 1) { amount = n; }
	else { amount = n + '.' + d; }
	amount = minus + amount;
	}
	return amount;
}


//Helper functions to populate select boxes
var test = false;

function whsubmit()
{
   //if(!loading)  
   	document.forms.wh.submit();
}

function whCsubmit()
{
	//alert("loadingCs="+loadingCs);
   //if(!loadingCs)  
   	document.forms.wh.submit();
}


function updateResults()
{
///catogories/getItems?category=Baby&subCategory=High%20Chairs
	
	var category = document.forms.wh.category.value;
	category = category.replace(/ \(.*\)/g,"");
	var subCategory = document.forms.wh.subCategory.value;
	subCategory = subCategory.replace(/ \(.*\)/g,"");
	var country = document.forms.wh.country.value;
	country = country.replace(/ \(.*\)/g,"");
	var town = document.forms.wh.town.value;
	town = town.replace(/ \(.*\)/g,"");
	
	var params  = '/catogories/getItems?';
	
	params += "category=" + category;
	params += "&subCategory=" + subCategory;
	params += "&country=" + country;
	params += "&town=" + town;
	params += "&counts=true";	
	params += "&count=10";	
	//alert(params);
	document.forms.wh.submit();
}

/* AJAX cross browser calls
** 
** fn name:				askWH
** params:				url - the url to pass to the back end
** description:		This function take an url to pass to the back end.  
**								The function 'readyState4' processes the result.
*/

var xmlHttp;			//The one and only ajax object
var counts=true;  //true if your list has numbers i.e. Cars(33)
function askWH(url)
{  

  try
  {    // Firefox, Opera 8.0+, Safari    
			xmlHttp=new XMLHttpRequest();    
	}
	catch (e)
  {    // Internet Explorer    
		try
    {      
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");      
		}
    catch (e)
    {
			try
      {
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");        
			}
      catch (e)
      {
				alert("Your browser does not support AJAX!");        
				return false;        
			}      
		}    
	}
	if(xmlHttp)
	{
		xmlHttp.open("GET",url,true);
		xmlHttp.onreadystatechange=readyState4;
	  xmlHttp.send(null);
	}  
}

/* A recursive readyState == 4 function
** 
** fn name:				readyState4
** params:				(none)
** globals:				optionName - this is the name of the option list you need to populate
** description:		The function 'readyState4' processes the result of askWH(url).
*/



function readyState4()
{

		if(xmlHttp)
		{
			if(xmlHttp.readyState==4)
			{
				if(optionName == "closing")
				{
					//alert(xmlHttp.responseText);
					var status = eval("(" + xmlHttp.responseText + ")");
					var item = new Array();
					var end = 0;
					var start = 1;
					var k = 0;
					var j;
					
					for(j = 0; j < status.length; j++)
					{
							
							var pos = 0;
							var statusBoxID = "status" + k;
							var statusBox = $(statusBoxID);
							var bidderID = "bidder" + k;
							var bidderBox = $(bidderID);
							var bidAmountID = "bidAmount" + k;
							var bidAmountBox = $(bidAmountID);
							
							while (end != -1) 
							{
								pos++;
								var sold = "\"" + eval(status[j]) + "\"";
								
								end = sold.indexOf(",", start);
								if(end != -1)
									item[k] = sold.substring(start, end);
								else
								{
									var str = sold.substring(start);
									item[k] = str.replace("\"","");
								}
								start = end+1;
								//alert(item[k]);	
								if((pos == 2) && statusBox) //status
								{
									if(item[k] == "sold")
										statusBox.innerHTML = "Auction Status: Sold.";
									if(item[k] == "selling")
										statusBox.innerHTML = "Auction Status: Live Auction!.";
									if(item[k] == "expired")
										statusBox.innerHTML = "Auction Status: Classified Ad.";
									if(item[k] == "withdrawn")
										statusBox.innerHTML = "Auction Status: Withdrawn from Sale.";	
								}
								if((pos == 3) && bidderBox)  //status
								{
									if(item[k] != "")
										bidderBox.innerHTML = item[k];
								}
								if((pos == 4) && bidAmountBox) //status
								{
									if(item[k-1] != "")
										bidAmountBox.innerHTML = item[k];
								}
								k++;
							}
							
							end = 0;
							start = 1;
					}
					
					return;
				}
				var obj = $(optionName);
				if(obj)
				{
					if(obj.options)
					{
						while(obj.options.length)
							obj.remove(0);
					}
					var list = eval("(" + xmlHttp.responseText + ")");
					
					var i;
					var length = list.length;
								
					if(length > 0)
					{
						if(optionName == "county")
						{
							
								var addr = $("countyhidden");
								if(addr)
								{
									$("divcounty").style.display = 'none';
									$("divcountyhidden").style.display = 'inline';
									addr.className = "inputBox";
									obj = addr;
								}
						}
						if(optionName == "town")
						{
								
								var addr = $("townhidden");
								if(addr)
								{
									$("divtown").style.display = 'none';
									$("divtownhidden").style.display = 'inline';
									addr.className = "inputBox";
									obj = addr;
									while(obj.options.length)
										obj.remove(0);
	
								}
						}

					}
					else
					{
					
						if(optionName == "county")
							{
								
									var addr = $("countyhidden");
									if(addr)
									{
										$("divcounty").style.display = 'inline';
										$("divcountyhidden").style.display = 'none';
										addr.className = "hidden";
										obj = addr;
									}
							}
							if((optionName == "town") || (optionName == "county"))
							{
									
									var addr = $("townhidden");
									if(addr)
									{
										$("divtown").style.display = 'inline';
										$("divtownhidden").style.display = 'none';
										addr.className = "hidden";
										obj = addr;
									}
							}
						//$("divcounty").style.display = 'visible';
						//$("divcountyhidden").style.display = 'none';
						//$("divtown").style.display = 'visible';
						//$("divtownhidden").style.display = 'none';
					}
					var opt = document.createElement("option");
						  
						obj.options.add(opt);
						opt.innerHTML = "-- Please Select --";
						
						opt.value = "";
					for(i=0; i <length ; i++)
					{
						
						var opt = document.createElement("option");
						  
						obj.options.add(opt);
						opt.innerHTML = list[i];
						
						opt.value = list[i];
						if (optionValue == list[i]) obj.selectedIndex=obj.options.length-1;
    			}
    			//setfocus(optionName2);
    		}
    	}
 		}
}

/* Custom AJAX Calls */

/* Gets the main categories - sets vars showing this list, next list to fill and next fn to call */
function getcat(ov)
{
	optionName = "category";
	optionName2 = "subCategory";
	optionValue = (ov||null);
	//nextFn = (updateMinorCategories);
	askWH("/categories/getCats");
}

/* Gets the subcategories - sets vars showing this list, next list to fill (none) and next fn to call (none)*/
function updateMinorCategories()
{
		optionName = "subCategory";
		optionName2 = "";
		nextFn = (0);
	
   	var url = "/categories/getSubCats?";
   	url += "category=" + document.forms.sell.category.value;
			
  
   	askWH(url);
}

function getCountries()
{	
	optionName = "country";
	optionName2 = "county";
	askWH("/location/getCountries?");

}

var keyCount = 0;
function updateKeyCount()
{
	keyCount++;
	
}


var address = "";
function updateCounties()
{

		document.forms.register.county.value = "";
		document.forms.register.town.value = "";
		document.forms.register.countyhidden.value = "";
		document.forms.register.townhidden.value = "";
		
		address = escape(document.forms.register.country.value);
		showAddress(address, 5);
	
		optionName = "county";
		optionName2 = "town";
   	var url = "/location/getCounties?";
   	url += "country=" + escape(document.forms.register.country.value);
 
   	askWH(url);
   	
}

function updateTowns()
{
//alert("hello");
		if(document.forms.register.countyhidden.value != "")
			document.forms.register.county.value = document.forms.register.countyhidden.value;

		
		address = 
					escape(document.forms.register.county.value)
				+ ", "	
				+	escape(document.forms.register.country.value);
		
		showAddress(address, 8);
	
		optionName = "town";
		optionName2 = "address1";
   	var url = "/location/getTowns?";
   	url += "country=" + escape(document.forms.register.country.value) + "&";
   	url += "county=" + escape(document.forms.register.county.value);
		
   	askWH(url);
}

function updateTowns2()
{
		if(document.forms.register.countyhidden.value != "")
			document.forms.register.county.value = document.forms.register.countyhidden.value;
		
		if(document.forms.register.townhidden.value != "")
			document.forms.register.town.value = document.forms.register.townhidden.value;
		
		address = 
					escape(document.forms.register.county.value)
				+ ", "	
				+	escape(document.forms.register.country.value)
				+ ", "	
				+	escape(document.forms.register.town.value);
		showAddress(address, 13);
		
		var hh = $("hiddenhelp");
		if(hh)
		{
			hh.className="text1";
		}
}

function setUserCredentials()
{
	//alert("setUserCredentials");
	var userCredSignIn = $("signIn");
	
	var user = readCookie("activeUser");
	
	if(user && user.length)
	{
		userCredSignIn.innerHTML = "<a id=\"signIn\" href=\"/user/logout\">SIGN OUT</a>";
	}	
	else
	{ 
		userCredSignIn.innerHTML = "<a id=\"signIn\" href=\"/user/signin\">SIGN IN </a>";	
	}
}



function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(";");
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) 
				return c.substring(nameEQ.length,c.length);
	}
	return null;
}


	
function validateRegFields()
{


	var nrErrors = 0;
	
	nrErrors += doUserName(document.forms.register.user_name.value);
	nrErrors += doPassword(document.register.user_pass.value);
	nrErrors += doCPassword(document.register.user_pass.value, document.register.confirm_pass.value);
	nrErrors += doEmail(document.register.email.value);
	if(nrErrors != 0)
	{
		
		return false;
	}
	return true;
}

function doUserName(userName)
{
	
	if(userName.length < 6)
	{
          alert("The user name must be at least 6 characters long");
	  return 1;
	}
	return 0;
}

function doPassword(password)
{
	if(password.length < 6)
	{
	  alert("The password must be at least 6 characters long");
	  return 1;
	}
	return 0;
}

function doCPassword(password, cpassword)
{
	if(password != cpassword)
	{
	  alert("The passwords are not the same");
	  return 1;
	}
	
	return 0;
}

function doEmail(email)
{
	var tfld = trim(email);  
  var email1 = /^[^@]+@[^@.]+\.[^@]*\w\w$/  ;
  if (!email1.test(tfld))
  { 
    alert("Invalid Email Address");
		return 1;
	}
	return 0;
}

function trim(str)
{
  return str.replace(/^\s+|\s+$/g, '');
}


// Google Maps
    var map = null;
    var geocoder = null;
		var showFullAddr = false;
		var _lat = 0;
		var _long = 0;
		var _zoom = 0;
		function gmaps(lat, lng, zoom) {
			if (GBrowserIsCompatible()) {
        map = new GMap2($("map"));
			
				map.addControl(new GSmallMapControl());
				map.addControl(new GMapTypeControl());
				map.enableDoubleClickZoom();
				map.enableContinuousZoom();
        geocoder = new GClientGeocoder();
        _lat = lat;
        _long = lng;
        _zoom = zoom;
      
        
        if((_lat || _long || _zoom) != 0)
        {
        //alert(_lat + " " + _long + " " + _zoom);
      
        	//map.setCenter(new GLatLng(53.366819, -6.488998), 13);
					map.setCenter(new GLatLng(_lat, _long), _zoom);
					if(showFullAddr)
					{
						var point = new GLatLng(_lat,_long);  
						map.addOverlay(new GMarker(point));
					}
				}
				else
					showAddress("ireland", 1);
      		
      
        GEvent.addListener(map, "click", function(overlay, point) {
			    if (overlay) {
						map.clearOverlays();
            map.removeOverlay(overlay);
            showFullAddr = false;
            showAddress(address, 13);
            updateDA();
          } else {
						map.clearOverlays();
            map.addOverlay(new GMarker(point));
            $("geolong").value = point.x;
						$("geolat").value = point.y;
						$("zoom").value = map.getZoom();
							
            showFullAddr = true;
            updateDA();
            
          }
        });
        
      }
    }


function gmapsThumb(lat, lng, zoom, mapId, url) {
        //alert($(mapId));
            
	if (GBrowserIsCompatible()) {
            map = new GMap2($(mapId));
            map.disableDragging();
            map.disableDoubleClickZoom();
            map.disableContinuousZoom();
            _lat = lat;
            _long = lng;
            _zoom = zoom;
            map.setCenter(new GLatLng(_lat, _long), _zoom);
            GEvent.addListener(map, "click", function() {
                document.location.href = url;
            });
            
        }
    }


    function showAddress(address, zoom) {
      if (geocoder) {
      
        geocoder.getLatLng(
          address,
          function(point) {
            if (point) {
              map.setCenter(point, zoom);
              $("geolong").value = point.x;
							$("geolat").value = point.y;
							$("zoom").value = map.getZoom();
							
            }
          }
        );
      }
      
    }

function updateDA()
{

		if(document.forms.register.countyhidden.value != "")
			document.forms.register.county.value = document.forms.register.countyhidden.value;
		
		if(document.forms.register.townhidden.value != "")
			document.forms.register.town.value = document.forms.register.townhidden.value;
				
		$("da_country").innerHTML = document.forms.register.country.value;
		$("da_county").innerHTML = document.forms.register.county.value;
		$("da_town").innerHTML = document.forms.register.town.value;

		
		if(showFullAddr) 
		{
			$("da_address2").innerHTML = document.forms.register.address2.value;
			$("da_address1").innerHTML = document.forms.register.address1.value;
			document.forms.register.showFullAddr.value = "true";
		}
		else
		{
			$("da_address2").innerHTML = "";
			$("da_address1").innerHTML = "";
			document.forms.register.showFullAddr.value = "false";
		}
}
function registerNow()
{
	
	setZoomLevel();
	return validateRegFields();
}

function setZoomLevel()
{
	$("zoom").value = map.getZoom();
		
}

function zoomToAddress()
{

	showFullAddr = $("showFullAddr").value;
	//alert($("geolat").value);
	//alert($("zoom").value);	
	_long = parseFloat($("geolong").value);
	_lat = parseFloat($("geolat").value);
	_zoom = parseInt($("zoom").value);
	//alert(_long);
	//alert(_lat);
	//alert(_zoom);

	if( ($("geolong").value == undefined)
		|| ($("geolong").value == ""))
	{
		_long = 0;
		_lat = 0;
		_zoom = 0;
	}
	
	
	//alert(_lat + " " + _long + " " + _zoom);
	gmaps(_lat, _long, _zoom);
//	gmaps(53.366819, -6.488998, 13);
	/*alert($("showFullAddr").value);
	if($("showFullAddr").value == true)
	{
		
	}*/
}

function zoomToAddressDiv()
{
	showFullAddr = $("showFullAddr").innerHTML;
	//alert(showFullAddr);
	//alert($("geolong").innerHTML);
	//alert($("geolat").innerHTML);
	//alert($("zoom").innerHTML);	
	_long = parseFloat($("geolong").innerHTML);
	_lat = parseFloat($("geolat").innerHTML);
	_zoom = parseInt($("zoom").innerHTML);
	//alert(_long);
	//alert(_lat);
	//alert(_zoom);

	if( ($("geolong").innerHTML == undefined)
		|| ($("geolong").innerHTML == ""))
	{
		_long = 0;
		_lat = 0;
		_zoom = 0;
	}
	
	
	
	//alert(_lat + " " + _long + " " + _zoom);
	gmaps(_lat, _long, _zoom);
//	gmaps(53.366819, -6.488998, 13);
	/*alert($("showFullAddr").value);
	if($("showFullAddr").value == true)
	{
		
	}*/
}


/*
 * Nice function to relace borken images with the equivalent maps.  The trick is, when we test the 
 * image.src to see if it's there, the onerror is only called when the browser gives up.  By the time that 
 * happens, we're well into drawing the maps for genuine no image items.  So, we loop around until the number
 * of failed + successful images equals the number of images we expected.  Once that happens, we know we have reset 
 * the broken image links to be off screen and dragged their map thumbs back on screen 
 */

var imagesProcessed = 0;
var imagesToProcess = 1;
var waitTimeout = 0;
var nrItems1 = 0;
function checkImages(nrItems)
{
	nrItems1 = nrItems;
	imagesToProcess = nrItems;
    for(i = 0; i < nrItems; i++)
    {
    	var image = "image" + i;
		var imgThumb = "imgThumb" + i;
		var mapThumb = "mapThumb" + i;
		if(document.getElementById(imgThumb) == null) {
    		document.getElementById(mapThumb).className="mapThumb";
    		imagesToProcess--;
    	}
    	else{
    		// check img is loadable
    		var imgsrc = document.getElementById(image);
    		if(imgsrc != null)
    		{
    			var newimage = new Image();
    			newimage.imgThumb = imgThumb;
    			newimage.mapThumb = mapThumb;
    			newimage.onerror = function(evt){
    				imagesProcessed++;
    				//alert("error");
    				document.getElementById(this.imgThumb).className="hidden";
    				document.getElementById(this.mapThumb).className="mapThumb";
    			}
    			newimage.onload = function(evt){
    			//	alert("loaded")
    				imagesProcessed++;
    			}
    			newimage.onabort = function(evt){
    		//		alert("aborted")
    				imagesProcessed++;
    			}
    			newimage.src = imgsrc.src;
    		}
    	}
    }
    waitTimeout = setInterval ( "wait()", 250 );
    
    
}


function wait()
{
	//alert("imagesProcessed " + imagesProcessed +" imagesToProcess " + imagesToProcess + " nrItems = " + nrItems1);
	if(imagesProcessed == imagesToProcess){
		//alert("imagesProcessed " + imagesProcessed +" imagesToProcess " + imagesToProcess);
		clearInterval(waitTimeout);
		zoomToAddressDivList(nrItems1);
	}
}

function zoomToAddressDivList(nrItems)
{
		
		
        for(i = 0; i < nrItems; i++)
        {
            var _url = "#";
            var _geolong = "geolong" + i;
            var _geolat = "geolat" + i;
            var _geozoom = "zoom" + i;
            var _mapId = "mapThumb" + i;
            var _showFullAddr = "showFullAddr" + i;
            var _urltofollow = "url" + i;
            _long = _lat = _zoom = 0;
            if($(_showFullAddr) != undefined)
            {
                showFullAddr = $(_showFullAddr).innerHTML;
                if($(_geolong))
                    _long = parseFloat($(_geolong).innerHTML);
                if($(_geolat))
                    _lat = parseFloat($(_geolat).innerHTML);
                if($(_geozoom))
                    _zoom = parseInt($(_geozoom).innerHTML);
                if($(_urltofollow))
                    _url = $(_urltofollow).innerHTML;
                
                gmapsThumb(_lat, _long, _zoom, _mapId, _url);
            }
	}
        
	
}


var address1 = "";
var address2 = "";
var town = "";
var county = "";
var country = "";

function onUseMyAddress()
{
	if(country == "")
	{
		address1 = $("address1").value;
		address2 = $("address2").value;
		town = $("town").value;
		county = $("county").value;
		country = $("country").value;
	}
		
	var useAddr = $("useMyAddr").checked;
	if(useAddr)
	{
		$("address1").value = address1;
		$("address2").value = address2;
		$("town").value = town;
		$("county").value = county;
		$("country").value = country;
		
	}
	else
	{
		$("address1").value = "";
		$("address2").value = "";
		$("town").value = "";
		$("county").value = "";
		$("country").value = "";
	}
}

function fadeScreen()
{
	//remove IE6 fade effects as possibility of causing crashes
	document.body.style.opacity = 0.5;
	//document.body.style.filter = 'alpha(opacity=50)';
	var uploadTxt = $("uploadTxt");
	uploadTxt.className = "uploadTxt";
	uploadTxt.style.opacity = 1.0;
	//uploadTxt.style.filter = 'alpha(opacity=100)';
}

function clearDefault(el)
{

  if (el.defaultValue==el.value) el.value = "";
  el.style.color = '#000' ;
}

function testBulkUploadForm() 
{
	var cat = $("category").value;
	var subCat = $("subCategory").value;

	if(cat.length == 0)
	{
		alert("Please choose a major category");
		return false;
	}
	if(subCat.length == 0)
	{
		alert("Please choose a subcategory");
		return false;
	}
	
	fadeScreen();
	return true;
}

function testSellForm() 
{
	/* check the values of full and brief have changed */
	if(document.sell.summary.value == "(e.g. Baby High Chair)")
        {
            alert("Please change the brief 'Item Title' to reflect the item you are selling");
            return false;
        }
        if(document.sell.summary.value == "")
        {
            alert("The 'Item Title' must have text to reflect the item you are selling");
            return false;
        }
        
        if(document.sell.fullDesc.value == "Please give an accurate full description of the item you are selling.  Pay particular attention to spelling - if you spell a key word in your ad incorrectly, it may prevent your ad appearing in the search results for particular key words. Fully review the ad before clicking 'Save'.")
        {
            alert("Please change the 'Description' to accurately reflect the item you are trying to auction");
            return false;
        }
        if(document.sell.category.value == "")
	{
		alert("Please choose a major category");
 		return false;
	}
	if(document.sell.subCategory.value == "")
	{
		alert("Please choose a subcategory");
 		return false;
	}
//        if(document.sell.startPrice.value < document.sell.endPrice.value)
//        {
//            alert("In a warehog.com auction the price FALLS from start price to end price, while bidders can bid up to the falling price.  If you prefer, make the start price and end price the same and your asking price will not change, people can still bid on your item.");
//            return false;
//        }

	fadeScreen();
	return true;
}

function testEditAdForm() 
{
    	
	var cat = $("category").value;
	var subCat = $("subCategory").value;

	if(cat.length == 0)
	{
		alert("Please choose a major category");
		return false;
	}
	if(subCat.length == 0)
	{
		alert("Please choose a subcategory");
		return false;
	}
	
	fadeScreen();
	return true;
}

function alertFinalBid(currency)
{
	var briefDesc = $("summary").innerHTML;
	var bid = $("bidAmount").value;
	if(briefDesc && bid && currency)
	{
		return confirm("Please confirm you want to bid " + currency + " " + bid + " on the item '" + briefDesc + "'" );
		
	}
	return false;
	
}


function showMarkers(items)
{

	var _zoom = 13;
	var idlong = "geolong0";
	var idlat = "geolat0";
	var _long = parseFloat($(idlong).innerHTML);
	var _lat = parseFloat($(idlat).innerHTML);
	
	gmaps(_lat, _long, _zoom);
		
/*	for (var i = 1; i < items; i++)
	{
		idlong = "geolong" + i;
		idlat = "geolat" + i;
		_long = parseFloat($(idlong).innerHTML);
		_lat = parseFloat($(idlat).innerHTML);
		var point = new GLatLng(_lat,_long);  
		map.addOverlay(new GMarker(point));		
		
	}*/
}

function updateSellPage()
{
    var choice = $('adType');
    var currency = $('curr');
    var wh_auction = $('wh_auction');
    var reserve = $('reserve');
    var negativeTxt = $('negative');
    var canDeliver = $('myLocation');
    switch(choice.value)
    {
        case "1":
            reserve.className = "reserve hidden";
            wh_auction.className = "price";
            currency.className = "";
            negativeTxt.className = "";
            canDeliver.className = "";
        break;
        case "2":
            reserve.className = "reserve";
            wh_auction.className = "price hidden";
            currency.className = "";
            negativeTxt.className = "hidden";
            canDeliver.className = "";
        break;
        case "3":
            reserve.className = "reserve";
            wh_auction.className = "price hidden";
            currency.className = "";
            negativeTxt.className = "hidden";
            canDeliver.className = "";
        break;
        case "4":
            reserve.className = "reserve hidden";
            wh_auction.className = "hidden";
            currency.className = "hidden";
            negativeTxt.className = "hidden";
            canDeliver.className = "hidden";
        break;
        case "5":
            reserve.className = "reserve hidden";
            wh_auction.className = "hidden";
            currency.className = "hidden";
            negativeTxt.className = "hidden";
            canDeliver.className = "hidden";
        break;
        case "6":
            reserve.className = "reserve hidden";
            wh_auction.className = "hidden";
            currency.className = "hidden";
            negativeTxt.className = "hidden";
            canDeliver.className = "hidden";
        break;
    }
}

function deleteImage(fileName, imageID)
{
    var delImg = confirm("Are you sure u want to delete this image?");
    if(delImg)
    {
        var imgID = "image" + imageID;
        var imgsrc = "imagesrc" + imageID;
        var imgInput = $(imgID);
        imgInput.value = "delete:" + imgInput.value;
        alert("This image will be deleted when you save your changes. If you do not wish to delete this image then do not 'save' this form");
        //$(imgsrc).src = "";
        
        
        $(imgsrc).style.opacity = 0.3;
        //$(imgsrc).style.filter = 'alpha(opacity=30)';
	var spanId = "span" + i;
        var picId = "pic" + i;
        $(spanId).style = "hdrTxt";
        $(picId).style = "picInput";
    }
}

function deleteAd(href)
{
    
    if(confirm("By clicking 'OK' this ad will be permanently removed from this site. Are you sure you want to delete this ad?"))
        return href; 
    return "#";
}


function checkkey(e)
{
    var keynum; 
    if(window.event)
    {
        keynum = e.keyCode;
    } 
    else if(e.which)
    {
        keynum = e.which;
    }
    if(keynum != 9) //tab
    {
        if(document.sell.category.options.length == 1)
            getcat();
    }
}
