/**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;/*
 * Precondition:
 * listings WILL have the following attributes: imgURL, elapsed, linkURL, title, shortTitle, price
 */
function OodleSlideShow(parentElement, listings)
{
	if (parentElement==null || !listings || listings.length == 0)
		return;
	
	var numSlides = listings.length;
	var divElements = parentElement.getElementsByTagName('div');
	var imageElem = divElements[0];
	var priceElem = divElements[1];
	var titleElem = divElements[2];
	var freshnessElem = divElements[3];

	var index = 1;
	
	var image = document.createElement('img');
	image.src = listings[0].imgURL;
	image.title = listings[0].title;
	image.alt = listings[0].title;

	var link = document.createElement("a");
	link.appendChild(image);
	link.setAttribute("href", listings[0].linkURL);
	imageElem.appendChild(link);
	priceElem.innerHTML = listings[0].price;
	titleElem.innerHTML = listings[0].shortTitle;
	freshnessElem.innerHTML = listings[0].elapsed;

	this.showSlides = showSlides;
	
	function showSlides()
	{
		var num = index % numSlides;
		index++;

		setTimeout(function() { parentElement.style.opacity = 0.9; }, 50);
		setTimeout(function() { parentElement.style.opacity = 0.8; image.style.filter = "alpha(opacity=80)"; }, 200);
		setTimeout(function() { parentElement.style.opacity = 0.7; }, 350);
		setTimeout(function() { parentElement.style.opacity = 0.6; image.style.filter = "alpha(opacity=60)"; }, 500);
		setTimeout(function() { parentElement.style.opacity = 0.5; }, 650);
		setTimeout(function() { parentElement.style.opacity = 0.4; image.style.filter = "alpha(opacity=40)"; }, 800);
		setTimeout(function() { parentElement.style.opacity = 0.3; }, 950);
		setTimeout(function() { parentElement.style.opacity = 0.2; image.style.filter = "alpha(opacity=20)"; }, 1100);
		setTimeout(function() { parentElement.style.opacity = 0.1; }, 1250);
		
		setTimeout(function() { link.setAttribute("href", listings[num].linkURL); }, 1250);
		setTimeout(function() { image.src = listings[num].imgURL; }, 1250);
		setTimeout(function() { image.title = listings[num].title; }, 1250);
		setTimeout(function() { image.alt = listings[num].title; }, 1250);
		setTimeout(function() { priceElem.innerHTML = listings[num].price; }, 1250);
		setTimeout(function() { titleElem.innerHTML = listings[num].shortTitle; }, 1250);
		setTimeout(function() { freshnessElem.innerHTML = listings[num].elapsed; }, 1250);

		setTimeout(function() { parentElement.style.opacity = 0.1; }, 1300);
		setTimeout(function() { parentElement.style.opacity = 0.2; image.style.filter = "alpha(opacity=20)"; }, 1450);
		setTimeout(function() { parentElement.style.opacity = 0.3; }, 1600);
		setTimeout(function() { parentElement.style.opacity = 0.4; image.style.filter = "alpha(opacity=40)"; }, 1850);
		setTimeout(function() { parentElement.style.opacity = 0.5; }, 2000);
		setTimeout(function() { parentElement.style.opacity = 0.6; image.style.filter = "alpha(opacity=60)"; }, 2150);
		setTimeout(function() { parentElement.style.opacity = 0.7; }, 2300);
		setTimeout(function() { parentElement.style.opacity = 0.8; image.style.filter = "alpha(opacity=80)"; }, 2450);
		setTimeout(function() { parentElement.style.opacity = 0.9; }, 2600);
		setTimeout(function() { parentElement.style.opacity = 1.0; image.style.filter = "alpha(opacity=100)"; }, 2750);
	}

	this.startShow = function(interval)
	{
		showSlides();
		setInterval(showSlides, interval);
	}
}

function startShowForElement(slideShow, timeStart, interval)			
{
	if(slideShow && slideShow.startShow)
	{
		setTimeout(
			function() 
				{
					slideShow.startShow(interval);
				}
			, timeStart);
	}
}


/*
 * Fisher-Yates shuffle from:
 * @http://jsfromhell.com/array/shuffle [v1.0]
 * Jonas Raoni Soares Silva
 */ 
shuffle = function(v){
	for(var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
	return v;
};
function listingAction(action, listing, child, userAction) {
	var afterCallback = function () {
		switch (action) {
		   case 'spam':
				setTimeout(function() { $(child).innerHTML = 'Marked as spam.'; }, 100);
				break;
			case 'scam':
			case 'fraud':
				setTimeout(function() { $(child).innerHTML = 'Thank you for reporting this item as spam/fraud - we will investigate it. (If you clicked the link by mistake, please don\'t worry. It takes more than one complaint to get the item removed.)'; }, 100);
				break;
			case 'abuse':
				setTimeout(function() { $(child).innerHTML = 'Thank you for reporting this item as abusive - we will investigate it. (If you clicked the link by mistake, please don\'t worry. It takes more than one complaint to get the item removed.)'; }, 100);
				break;	
			case 'inappropriate':
				setTimeout(function() { $(child).innerHTML = 'Thank you for reporting this item as inappropriate - we will investigate it.'; }, 100);
				break;
			case 'unavailable':
				setTimeout(function() { $(child).innerHTML = 'Thank you. We will remove the listing after verifying it is unavailable.'; }, 100);
				break;
			case 'suspicious':
				setTimeout(function() { $(child).innerHTML = 'Marked as suspicious. Refresh this page to see the change.'; }, 100);
				break;
			case 'unmarkspam':
			case 'unmarksusp':
				setTimeout(function() { $(child).innerHTML = 'Listing has been unmarked.'; }, 100);
				break;
			case 'adminremove':
				setTimeout(function() { $(child).innerHTML = 'Listing has been administratively removed.'; }, 100);
				break;
		}
	};
	var ajaxRequest = new XMLHttpRequestObject(null, afterCallback, null);
	ajaxRequest.send('/ajax/actions/?action=' + userAction + '&listing=' + listing);
	$(child).innerHTML = 'Marking as ' + action + '...';
}

// Render a listing using an AJAX callback.
function fillListing(divid, listingid) {
	var expandedListing = document.getElementById(divid);
	var fullbody = getElementsByClass('sbody', expandedListing, 'span');
	var vin = getElementsByClass('vin', expandedListing, 'span');
	var frequency = getElementsByClass('listing-frequency', expandedListing, 'strong');
	var map = getElementsByClass('map', expandedListing, 'div'); 
	new XMLHttpRequestObject(
		function () {},
		function () {},
		function (xml) {
			fullbody = fullbody[0];
			if (fullbody) {
				if (fullbody.innerHTML == '') {
					body = null;
					tags = xml.getElementsByTagName('body');
					if (tags.length > 0) {
						body = tags[0];
					}
					if (body &&
					    body.childNodes &&
					    body.childNodes.length > 0 &&
					    body.childNodes[0].nodeValue !=  "") {
						fullbody.innerHTML = body.childNodes[0].nodeValue;
					} else {
						fullbody.innerHTML = "No description available";
					}
				}
			}
			
			vin = vin[0] ? vin[0] : null;
			if (vin) {
				if (vin.innerHTML == '') {
					body = null;
					tags = xml.getElementsByTagName('vin');
					if (tags.length > 0) {
						body = tags[0];
					}
					if (body &&
					    body.childNodes &&
					    body.childNodes.length > 0 &&
					    body.childNodes[0].nodeValue !=  "") {
						vin.innerHTML = body.childNodes[0].nodeValue;
					} else {
						vin.innerHTML = "No VIN available";
					}
				}
			}
			
			if (frequency.length > 0) {
				frequency = frequency[0];
				if (frequency.innerHTML == '' || frequency.innerHTML == 'very rarely') {
					similar = null;
					tags = xml.getElementsByTagName('num_similar');
					var headerText = "Listing Frequency";
					if (tags.length > 0) {
						similar = tags[0];
					}
					if (similar &&
					    similar.childNodes &&
					    similar.childNodes.length > 0 &&
					    similar.childNodes[0].nodeValue !=  "0") {
						var days = parseInt(180/similar.childNodes[0].nodeValue);
						if (days == 0) {
							frequency.innerHTML = "every few hours";
						} else if (days == 1) {
							frequency.innerHTML = 'every day';
						} else {
							frequency.innerHTML = "every " + days + " days";
						}
					} else if (similar &&
					           similar.childNodes &&
					           similar.childNodes.length > 0 &&
					           similar.childNodes[0].nodeValue ==  "0") {
						frequency.innerHTML = "very rarely";
					} else {
						frequency.innerHTML = "very rarely";
					}
				}
			}

			var loadMapFunc = function() {
			
				if (!window.GBrowserIsCompatible ||
				    !window.GControl ||
				    !window.GMap2)
				{
					setTimeout(loadMapFunc, 200);
					return;
				}

				if (map.length > 0 && GBrowserIsCompatible()) {
					map = map[0];
					var lat = xml.getElementsByTagName('latitude');
					if (lat) lat = lat[0];
					if (lat && lat.childNodes && lat.childNodes.length > 0) {
						lat = lat.childNodes[0].nodeValue;
					} else {
						lat = null;
					}
					var lng = xml.getElementsByTagName('longitude');
					if (lng) lng = lng[0];
					if (lng && lng.childNodes && lng.childNodes.length > 0) {
						lng = lng.childNodes[0].nodeValue;
					} else {
						lng = null;
					}

					var loc = xml.getElementsByTagName('location_code');
					if (loc) loc = loc[0];
					if (loc && loc.childNodes && loc.childNodes.length > 0)
					{
						loc = loc.childNodes[0].nodeValue;
					}
					else
					{
						loc = null;
					}
					
					if (lat && lng && loc && loc.substr(0, 5) === 'addr:')
					{
						map.style.width = "150px";
						map.style.height = "150px";
						// map.style.styleFloat = "right";
						// map.style.floatStyle = "right";
						// map.style.cssFloat = "right";
						map.style.overflow = "hidden";
						map.style.marginLeft = "2em";
	
						var gmap = new GMap2(map);
						gmap.setCenter(new GLatLng(lat, lng), 13);
						GEvent.addListener(gmap, "moveend", function() {
							gmap.panTo(new GLatLng(lat, lng));	
						});					
	
						var pin = new GIcon();
						pin.shadow = "http://i.oodleimg.com/a/maps/shadow.png";
						pin.shadowSize = new GSize(22, 24);
						pin.iconSize = new GSize(14, 24);
						pin.iconAnchor = new GPoint(7, 22);
						pin.infoWindowAnchor = new GPoint(7, 5);
						pin.image =  "http://i.oodleimg.com/a/maps/icon.png";
						var marker = new GMarker(new GLatLng(lat, lng), pin);
						gmap.addOverlay(marker);
					}
				}
			};
			
			LazyLoad.loadOnce(['http://img.oodle.com/jaml/lazyloadmap/1216934470'], loadMapFunc, null, null, true);
		},
		"/ajax/listing/?listing_id=" + listingid
	);
}

function toggleListing(id) {
	var element = document.getElementById(id);
	if (element) {
		if (hasClass(element, "normal-listing")) {	
			fillListing(id, id);	
			swapToggleLink(id, "show");
			removeClass(element, "normal-listing");
			addClass(element, "expanded-listing");
		} else if (hasClass(element, "expanded-listing")) {
			swapToggleLink( id, "hide" );
			removeClass(element, "expanded-listing");
			addClass(element, "normal-listing");
		}
	}
}

function swapToggleLink(id, event) {
	var toggleBtn = document.getElementById(id + "_toggleBtn");
	if (toggleBtn) {
		var seeDetails = getElementsByClass('see-details-link', toggleBtn)[0];
		var hideDetails = getElementsByClass('hide-details-link', toggleBtn)[0];
		
		if (event == 'hide') {
			seeDetails.style.display = "inline";
			hideDetails.style.display = "none";
		} 
		else if(event == 'show') 
		{
			seeDetails.style.display = "none";
			hideDetails.style.display = "inline";
		}
	}
}

function doToggle(id, event) {
	//var now = new Date().getTime();
	if (typeof _cs != 'undefined' && _cs && _cs != id) {
		// preserve scroll state
		var curElement = document.getElementById(id);
		var oldOffset = getElementTop(curElement);
		toggleListing(_cs); 
		var newOffset = getElementTop(curElement);
		if (oldOffset - newOffset != 0) {
			// scroll by offset
			window.scrollBy(0, newOffset - oldOffset)
		}
	}
	if (typeof _cs == 'undefined' || _cs == null || _cs != id) {
		_cs = id;
	} else {
		_cs = null;
	}
	toggleListing(id);
	//var later = new Date().getTime();

	//alert(later - now);
}
function toggleNarrow(controlObj, toggleObj) {
	toggle(toggleObj);
	if (toggleObj.style.display == 'none') {
		removeClass(controlObj, 'expanded');
	} else {
		addClass(controlObj, 'expanded');
	}
}

// @param CheckBox childObj
// @param UL parentObj
// Check childObj and and uncheck all of
// the CheckBox objects in parentObj.
// Args can be undefined.
function clickAll(childObj, parentObj) {
	//if (childObj.checked)
	//	return;
	if (!childObj || !parentObj)
		return;
	var elems = getElementsByTagNames('input', parentObj);
	for (var i = 1; i < elems.length; i++)
		elems[i].checked = false;
	childObj.checked = true;
}

// @param UL parentObj
// iterate through the CheckBox objects in parentObj
// and check the first object if there are no
// "on" object, otherwise uncheck the first object.
// Args can be undefined.
function fixAll(parentObj) {
	if (!parentObj)
		return;
	var elems = getElementsByTagNames('input', parentObj);
	var on = 0;
	for (var i = 1; i < elems.length; i++) {
		if (elems[i].checked == true) {
			on++;
			break;
		}
	}
	elems[0].checked = !on;
}

// @param CheckBox childObj
// @param UL parentObj
// toggle the state of childObj, then iterate
// through the CheckBox objects in parentObj
// and check the first object if there are no
// "on" object, otherwise uncheck the first object.
// Args can be undefined.
function clickAndFixAll(childObj, parentObj) {
	if (!childObj || !parentObj)
		return;
	childObj.checked = !childObj.checked;
	fixAll(parentObj);
}
function doAjaxRequest(parameters, loadingCallback, errorCallback, successCallback) {
	loadingCallback();
	var error = '';
	var responseCallback = function(response) {
		error =
			response.getElementsByTagName('error')[0] ?
				response.getElementsByTagName('error')[0].firstChild.nodeValue.toString() :
				'';
		if (error) {
			errorCallback(error);
		} else {
			successCallback();
		}
	}
	var ajaxRequest = new XMLHttpRequestObject(null, null, responseCallback);
	ajaxRequest.send('/ajax/my/?' + parameters);
}

function updateAlertFrequency(alertID, frequency) {
	var errorDiv = 'alert-error';
	var pauseDiv = 'pause-' + alertID;
	var loadingCallback = function() {
		toggleClass(errorDiv, 'success', 'error');
		$(errorDiv).innerHTML = 'loading...';
	}
	var errorCallback = function(error) {
		toggleClass(errorDiv, 'success', 'error');
		$(errorDiv).innerHTML = error;
	}
	var successCallback = function() {
		toggleClass(errorDiv, 'error', 'success');
		$(errorDiv).innerHTML = 'your alert frequency was changed!';
	}
	doAjaxRequest('change=alert&action=frequency&frequency=' + frequency + '&id=' + alertID, loadingCallback, errorCallback, successCallback);
	return false;
}

function resumeAlert(alertID) {
	var errorDiv = 'error-alert';
	var pauseDiv = 'pause-' + alertID;
	var resumeDiv = 'resume-' + alertID;
	var statusDiv = 'status-' + alertID;
	var loadingCallback = function() {
		toggleClass(errorDiv, 'success', 'error');
		$(errorDiv).innerHTML = 'loading...';
	}
	var errorCallback = function(error) {
		toggleClass(errorDiv, 'success', 'error');
		$(errorDiv).innerHTML = error;
	}
	var successCallback = function() {
		toggleClass(errorDiv, 'error', 'success');
		$(errorDiv).innerHTML = 'We have resumed your alert.';
		$(resumeDiv).style.display = 'none';
		$(pauseDiv).style.display = 'block';
		$(statusDiv).innerHTML = 'active';
	}
	doAjaxRequest('change=alert&action=resume&id=' + alertID, loadingCallback, errorCallback, successCallback);
	return false;
}

function pauseAlert(alertID) {
	var errorDiv = 'error-alert';
	var pauseDiv = 'pause-' + alertID;
	var resumeDiv = 'resume-' + alertID;
	var statusDiv = 'status-' + alertID;
	var loadingCallback = function() {
		toggleClass(errorDiv, 'success', 'error');
		$(errorDiv).innerHTML = 'loading...';
	}
	var errorCallback = function(error) {
		toggleClass(errorDiv, 'success', 'error');
		$(errorDiv).innerHTML = error;
	}
	var successCallback = function() {
		toggleClass(errorDiv, 'error', 'success');
		$(errorDiv).innerHTML = 'We have paused your alert.';
		$(resumeDiv).style.display = 'block';
		$(pauseDiv).style.display = 'none';
		$(statusDiv).innerHTML = 'paused';
	}
	doAjaxRequest('change=alert&action=pause&id=' + alertID, loadingCallback, errorCallback, successCallback);
	return false;
}

function deleteAlert(alertID) {
	var errorDiv = 'error-alert';
	var alertDiv = 'alert-' + alertID;
	var loadingCallback = function() {
		toggleClass(errorDiv, 'success', 'error');
		$(errorDiv).innerHTML = 'loading...';
	}
	var errorCallback = function(error) {
		toggleClass(errorDiv, 'success', 'error');
		$(errorDiv).innerHTML = error;
	}
	var successCallback = function() {
		toggleClass(errorDiv, 'error', 'success');
		$(errorDiv).innerHTML = 'your alert was deleted!';
		$(alertDiv).style.display = 'none';
	}
	doAjaxRequest('change=alert&action=delete&id=' + alertID, loadingCallback, errorCallback, successCallback);
	return false;
}

function changeEmail() {
	var email = $('email').value;
	saveData('email', email, 'change=email&email=' + urlencode(email));
}

function changePassword() {
	var oldpw = $('old-passwd').value;
	var newpw = $('new-passwd').value;
	var newpw2 = $('new-passwd2').value;
	saveData('passwd', '(not shown)', 'change=passwd&oldp=' + oldpw + '&newp=' + newpw + '&newp2=' + newpw2);
}

function changeDisplayName() {
	var displayName = $('display-name').value;
	saveData('displayName', displayName, 'change=displayName&displayName=' + displayName);
}

function changeZip() {
	var zip = $('zip').value;
	saveData('zip', zip, 'change=zip&zip=' + zip);
}

function changePref(flag) {
	var pref = flag ? 1 : 0;
	saveData('emailpref', pref, 'change=emailpref&pref=' + pref);
}

function changeOptin(flag) {
	var pref = flag ? 1 : 0;
	saveData('optin', pref, 'change=optinpref&pref=' + pref);
}

function saveData(changeField, value, contentString) {
	showError(changeField, 'loading...');
	var error = '';
	var parseResponse = function(response) {
		error =
			response.getElementsByTagName('error')[0] ?
				response.getElementsByTagName('error')[0].firstChild.nodeValue.toString() :
				'';
		if (error) {
			showError(changeField, error);
		} else {
			showSaved(changeField, value);
		}
	}
	var ajaxRequest = new XMLHttpRequestObject(null, null, parseResponse);
	ajaxRequest.send('/ajax/my/?' + contentString);
}

function showError(changeField, error) {
	switch (changeField) {
		case 'email':
			toggleClass('email-error', 'success', 'error');
			$('email-error').innerHTML = error;
			break;
		case 'passwd':
			toggleClass('passwd-error', 'success', 'error');
			$('passwd-error').innerHTML = error;
			break;
		case 'zip':
			toggleClass('zip-error', 'success', 'error');
			$('zip-error').innerHTML = error;
			break;
		case 'emailpref':
			toggleClass('pref-error', 'success', 'error');
			$('pref-error').innerHTML = error;
			break;
		case 'optin':
			toggleClass('optin-error', 'success', 'error');
			$('optin-error').innerHTML = error;
			break;
		case 'displayName':
			toggleClass('display-name-error', 'success', 'error');
			$('display-name-error').innerHTML = error;
			break;
		default:
			break;
	}
}

function showSaved(changeField, value) {
	switch (changeField) {
		case 'email':
			toggleClass('email-change', 'enabled', 'disabled');
			toggleClass('email-error', 'error', 'success');
			$('email-value').innerHTML = value;
			$('email-error').innerHTML = 'your email was successfully changed';
			break;
		case 'zip':
			toggleClass('zip-change', 'enabled', 'disabled');
			toggleClass('zip-error', 'error', 'success');
			$('zip-value').innerHTML = value;
			$('zip-error').innerHTML = 'your zip or postal code was successfully changed';
			break;
		case 'passwd':
			toggleClass('passwd-change', 'enabled', 'disabled');
			toggleClass('passwd-error', 'error', 'success');
			$('passwd-error').innerHTML = 'your password was successfully changed';
			break;
		case 'emailpref':
			toggleClass('pref-error', 'error', 'success');
			$('pref-error').innerHTML = 'your email delivery option was successfully changed';
			break;
		case 'optin':
			toggleClass('optin-error', 'error', 'success');
			$('optin-error').innerHTML = 'your receive email option was successfully changed';
			break;
		case 'displayName':
			toggleClass('display-name-change', 'enabled', 'disabled');
			toggleClass('display-name-error', 'error', 'success');
			$('display-name-value').innerHTML = value;
			$('display-name-error').innerHTML = 'your display name was successfully changed';
			break;
		default:
			break;
	}
}
function focus()
{
	var focusElement;
	if (document.getElementById('home-what'))
	{
		focusElement = document.getElementById('home-what');
	}
	else if (document.getElementById('search-what'))
	{
		focusElement = document.getElementById('search-what');
	}
	else if (document.getElementById('email')) 
	{ 
		focusElement = document.getElementById('email');
	}
	else if (document.getElementById('sender'))
	{
		focusElement = document.getElementById('sender');
	}
	
	if (focusElement)
	{
		focusElement.focus();
	}
}

addDOMLoadEvent(focus);
