var timerId = 0;
function showPasswordResetForm(containerid){
	new SimpleRequest(containerid, "/login.htm", "get", "showPasswordResetForm");
}
function showActivationLinkForm(containerid){
	new SimpleRequest(containerid, "/login.htm", "get", "showAjaxActivationLinkForm");
}

function doLogout(){
	window.location = "/myclassifieds.htm?doLogout";
}
function switchCityPanel(on, off){
	var tabon = on + '_tab';
	var taboff = off + '_tab';
	var panelon = on + '_panel';
	var paneloff = off + '_panel';
	$(tabon).className = 'tabon';
	$(taboff).className = 'taboff';
	$(panelon).style.display = 'table-row';
	$(paneloff).style.display = 'none';
}
function showCities(ctype, containerid){
		var params = 'ctype='+ctype+'&getAjaxCities=1';
		new SimpleRequest(containerid, '/citylist.htm', 'get', params);
}
function invokeTool(formname, ajax_method, anchorid){
		if($(anchorid).style.display != 'none')
			return;
		var theform = document.forms[formname];
		var url = theform.action;
		var params = Form.serialize(theform) + "&containerid=" + anchorid + "&" + ajax_method;
		if($('toolform')){
			$('toolform').parentNode.style.display = 'none';
			$('toolform').parentNode.innerHTML = '';
		}
		new SimpleRequest(anchorid, url, 'post', params);				
}
function getLoginForm(containerid){
		var params = 'getLoginForm=1&containerid=' + containerid;
		new SimpleRequest(containerid, '/showtools.htm', 'get', params);
}
function popupLogin(){
		if($('toolform')){
			$('toolform').parentNode.style.display = 'none';
			$('toolform').parentNode.innerHTML = '';
		}
		getLoginForm('hua_signin');
}
function getUploadDlg(containerid, imageholderid, postingkey){
		var closeImg = "<img src='/images/close.gif' border='0'/>";
		var params = 'getUploadDlg=1&containerid=' + containerid + '&imageholderid=' + imageholderid + "&postingkey=" + postingkey;
		var codes = new Array("web.dialog.close", "web.dialog.upload_image.title");
		Modalbox.show('/upload.htm?' + params, {height:480, title: 'Upload Image',closeString:'Close', closeValue:closeImg, aspnet: false, inactiveFade:false, overlayClose:false});
		
}
function getAjaxSearchOption(containerid, cat){
		var params = 'getAjaxSearchOption=1&cat=' + cat;
		new SimpleRequest(containerid, '/showlisting.htm', 'get', params);
}
function deletePostingImage(containerid, imageid, postingkey){
		var params = 'deletePostingImage=1&containerid='+ containerid + '&imageid=' + imageid + '&postingkey=' + postingkey;
		new SimpleRequest(containerid, '/upload.htm', 'post', params);

}

function getListing(containerid, theform){
	/*
	var sortings = new Object();
	sortings['web.sortbox.date1']="sortingtype=createdate&ordertype=desc";
	sortings['web.sortbox.date2']= "sortingtype=createdate&ordertype=asc";
	sortings['web.sortbox.price1']= "sortingtype=price&ordertype=desc";
	sortings['web.sortbox.price2']= "sortingtype=price&ordertype=asc";
	sortings['web.sortbox.subcategory']= "sortingtype=subtype&ordertype=asc";
	var sorting = theform.sorting.value;
	var sort_order=sortings[sorting];
	*/
	var params = Form.serialize(theform);
	new SimpleRequest(containerid, '/showlisting.htm', 'post', params);
}
function getNextListing(containerid, formname){
	var theform = document.forms[formname];
	theform.startrs.value = parseInt(theform.startrs.value) + parseInt(theform.maxrs.value);
	getListing(containerid, theform);
}
function getPreviousListing(containerid, formname){
	var theform = document.forms[formname];
	theform.startrs.value = parseInt(theform.startrs.value) - parseInt(theform.maxrs.value);
	getListing(containerid, theform);

}

function getNextPage(containerid, formname){
	var theform = document.forms[formname];
	theform.startrs.value = parseInt(theform.startrs.value) + parseInt(theform.maxrs.value);
	getListingPage(containerid, theform);
}
function getPreviousPage(containerid, formname){
	var theform = document.forms[formname];
	theform.startrs.value = parseInt(theform.startrs.value) - parseInt(theform.maxrs.value);
	getListingPage(containerid, theform);

}
function gotoPage(pageindex, containerid, formname){
	var theform = document.forms[formname];
	theform.startrs.value = pageindex * theform.maxrs.value;
	getListingPage(containerid, theform);
}
function getListingPage(containerid, theform){
	var url = theform.action;
	var params = Form.serialize(theform);
	new SimpleRequest(containerid, url, 'get', params);

}
function emptyListing(listingid, containerid, formname){
	dwr.engine.beginBatch();
	var theform = document.forms[formname];
	ListingBean.removeListing(listingid, function(status){
		getListingPage(containerid, theform);
	});
	dwr.engine.endBatch( {
		errorHandler : function(errorString, exception) {
			alert(exception.message);
		}
	});

}
function getCaptcha(elementid){
	var time = new Date().valueOf();
	$(elementid).src = '/Captcha.jpg?t=' + time;

}
function showChangePasswordForm(containerid){
		var params = 'showAjaxPasswordChangedForm=1';
		new SimpleRequest(containerid, '/myclassifieds.htm', 'get', params);
}
function addFile(file_el, containerid){
		var formel = file_el.form;
		var newfile = new Element("INPUT");
		newfile.type="file";
		newfile.value=file_el.value;
		var files = $(containerid);
		var row = new Element("TR");
		var td = new Element("TD").update(basename(file_el.value));
		row.update(td);
		formel.appendChild(newfile);
		file_el.value = '';
		files.appendChild(row);
}
/** closewindow will be replaced by closeDlg */
function closewindow(containerid){
	$(containerid).parentNode.style.display = 'none';
}
function closeDlg(containerid){
	// $(containerid).style.display = 'none';
	$(containerid).hide();
}
function jMoveToAnchor(anchorObj, theObj){
   var popupLocation = getAbsoPos(anchorObj);
   theObj.setStyle( { position: 'absolute', top: Math.floor(popupLocation.top) + 'px', left: Math.floor(popupLocation.left) + 'px' } );
   // theObj.style.left =popupLocation.x + 'px';
   // theObj.style.top = popupLocation.y  + 'px';
}
function getAbsoPos(obj){
	var element = $(obj);
	var vpoffset = element.cumulativeOffset();
	return vpoffset;
}
function showSubcategories(){
	jMoveToAnchor($('subcat_anchor'), $('subcat_pnl'));
	$('subcat_pnl').show();
}
function jMoveToCenter(el){
	var element = $(el);
	var el_w = element.getWidth();
	var el_h = element.getHeight();
	var viewPort = document.viewport.getDimensions();
	var offsets = document.viewport.getScrollOffsets();
	var centerX = viewPort.width / 2 + offsets.left - el_w / 2;
	var centerY = viewPort.height / 2 + offsets.top - el_h / 2;
	
	element.setStyle( { position: 'absolute', top: Math.floor(centerY) + 'px', left: Math.floor(centerX) + 'px' } );

	return el;
}

function basename(path, suffix) {
    var b = path.replace(/^.*[\/\\]/g, '');
    if (typeof(suffix) == 'string' && b.substr(b.length-suffix.length) == suffix) {
        b = b.substr(0, b.length-suffix.length);
    }
    return b;
}
function startCallback() {
	CustomProgressListener.reset();
	queryStatus();
	Modalbox.deactivate();
	return true;
}

function completeCallback(imagelist_el, upload_err) {
	if(imagelist_el)
		$('imageholder').innerHTML += imagelist_el.innerHTML;
	clearTimeout(timerId);
	if(upload_err){
		addMultiUpload('${alloweduploads}');
		$('upload_btn').enable();
		$('error').innerHTML = upload_err.innerHTML;
		Modalbox.activate();
	}else{
		$("percentage").update('100%');
		$("progressBarBoxContent").style.width = "100%";
		Modalbox.hide();
	}
			
}
function queryStatus() {
	CustomProgressListener.getStatus(showStatus);
	return true;
}
function showStatus(status) {
	if (status.percentage == "100"){
			$("percentage").update(' ' + status.percentage + '%');
			$("progressBarBoxContent").style.width = status.percentage + "%";
			clearTimeout(timerId);
	} else {
		$("progressBar").style.display = "block";
		$("percentage").update(' ' + status.percentage + '%');
		$("progressBarBoxContent").style.width = status.percentage + "%";
		timerId = setTimeout(queryStatus, 100);
	}
	return true;
}

function getNextUserListing(containerid, startrs, maxrs, method_param){
		var params = "" + method_param + "=1&startrs=" + startrs + "&maxrs=" + maxrs ;
		var successCallback = function(){
			toogleTab(method_param);
		}
		new AjaxRequest(containerid, '/myclassifieds.htm', 'post', params, successCallback, null);		
}
function toogleTab(method_param){
  
  var tabs = new Array("myclsActive","myclsInactive","myclsDeleted","myclsDisabled","myclsExpired","myclsSaved");
  var stab = method_param.replace("getAjax","");
  stab = stab.replace("UserListing","");
  stab = "mycls"+stab;
  
  var ontab;
  $(stab).className = "on"; 
  for(i=0;i<tabs.length;i++){
    if(tabs[i] == stab){
        ontab = i;
    } 
    else{
      if(i == 0)
       $(tabs[i]).className = "first";
      else if(i != 0)
       $(tabs[i]).className = "mnu";
      if(i == ontab + 1)
       $(tabs[i]).className = "";
     
    }
  } 
}
function SearchOption(){
	if($('searchoption').style.display == 'none'){
		$('searchoption').style.display = 'block';
	}else{
		$('searchoption').style.display = 'none';
	}
}
function getHelp(containerid){
	var el = $(containerid);
	var heading = el.readAttribute("htitle");
	var message = '';
	var messagecode = el.readAttribute("hcontent");
	var hpage = el.readAttribute("hpage");
	if(hpage){
		var successCallback = function(node){
			var content = node.responseText;
			new Tooltip(el, {content:content, opacity:2.0,backgroundColor: "#FC9", borderColor: "#C96", textColor: "#000", textShadowColor: "#FFF", useClose:true});
		};
		new AjaxRequest(null, '/help.htm', 'get', "showInfo=1&page=" + hpage, successCallback, null);	
	}
	else{
		MessageBean.getMessage(heading, 
			function(ret){ 
				heading = ret;
				MessageBean.getMessage(messagecode, function(ret){
				 message = ret;
				new Tooltip(el, {heading:heading, content:message, opacity:2.0, backgroundColor: "#FC9", borderColor: "#C96", textColor: "#000", textShadowColor: "#FFF"});
				 
				});
			});
	}
	

}

function getRecommendLocations(containerid){
	var params = 'getAjaxLocationsByCity=1&containerid=' + containerid;
	new AjaxRequest(containerid, '/citylist.htm', 'get', params, null, null);	
}
function selectLocation(name, containerid){
		document.postingform.location.value = name;
		$(containerid).style.display = 'none';
}	
function addMultiUpload(alloweduploads){
	//Remove hidden input
	var parentnode = $('fileinputs').parentNode;
	$('fileinputs').remove();
	var fis = new Element('span', {id: 'fileinputs'});
	fis.innerHTML = '<input type="file" id="first_file_element" size="60" class="inputfield" maxlength="60" />';
	parentnode.appendChild(fis);
	
	$('files_list').innerHTML = '';
	var uploader = new MultiSelector( document.getElementById( 'files_list' ), alloweduploads );
	uploader.addElement( document.getElementById( 'first_file_element' ) );

}
function toggleVisibility(thelink, label, form){
	thelink.style.display = 'none';
	$(label).style.display = 'inline';
	if($(form).style.display == 'none')
		$(form).style.display = 'block';
	else
		$(form).style.display = 'none';
}
function SetColor(colorcode){
	var hex = "0123456789ABCDEFabcdef";
	if(colorcode.length != 6){
		alert("color code must be 6 digit hex number");
		return;
	}
	for(i=0; i<colorcode.length; i++){
		c = colorcode.charAt(i);
		if(hex.indexOf(c) == -1){
			alert("color code must be 6 digit hex number");
			return;
		}
	}

	
	var colordiv = $('imgcolor');
	colordiv.style.backgroundColor ="#" + colorcode;	
	document.postingform.titlecolor.value = "#" + colorcode;
}
function addClass(obj, classname){
	obj.addClassName(classname);
}
function removeClass(obj, classname){
	obj.removeClassName(classname);
}
function goToPayment(){
	window.location.href = 'http://account.hereuare.com/account.htm?showProfile&payment=1';
}

/*** DWR get local news **/
var localnews = null;
var curnews_idx = 0;
var slider2 = null;

function newsFormatter(headline){
	return "<a href=\"" + headline.link + "\" target=\"_new\" >" + headline.title + "</a>";
}
/*** DWR get local events **/
var localevents = null;
var curevent_idx = 0;
var slider1 = null;

function getEvents(obj, category, clsname){
	var headlines;
	if(category == 'news'){
		ListingBean.getLocalHeadLines(0, 4, function(listwrapper){
			dwr.util.removeAllOptions("evt_headlines");
			headlines = listwrapper.result;
			var html = getNewsPanel(headlines)
			$("evt_headlines").innerHTML = html;
			setScroller('scrollable1');
		});
		highlight(obj, clsname);
	}else{
		ListingBean.getEventHeadLines(category, 0, 100, function(listwrapper){
			dwr.util.removeAllOptions("evt_headlines");
			headlines = listwrapper.result;
			if(headlines.length == 0){
				$("evt_headlines").innerHTML = "<li style='list-style:none;padding-top:50px;text-align:center'>These listings are coming soon!</li>";		
			}else{
				if(category == 'food'){
					var ad1 = [
					'<a href="http://www.opentable.com/home.aspx?ref=5689" target="_new">Dining Around Town <img src="/images/opentable.gif" align="top"/><br/><span style="color:black;font-size:11px">Planning to eat out soon? Reserve a table.</span></a>'
					]
				}
				dwr.util.addOptions("evt_headlines", ad1, regularFormatter, {escapeHtml:false});				
				dwr.util.addOptions("evt_headlines", headlines, listingHeadLineFormatter, {escapeHtml:false});
			}
			setScroller('scrollable1');
		});
		highlight(obj, clsname);
	}
}
function regularFormatter(data){ return data;}
function getNewsPanel(headlines){
	var html = "";
		html += "<li class=\"news_li\"><a style=\"font-size:13px;color:#000\" target=\"_new\" href=\"http://local.hereuare.com/forward.jsp\">5-Day Forecast</a></li>";
		html += "<li class=\"news_li\"><a style=\"font-size:13px;color:#000\" target=\"_new\" href=\"http://local.hereuare.com/forward.jsp\">Local News</a>";
		html += "<ul style=\"list-style:square;margin-left:10px;\">";
		for(i=0; i<headlines.length; i++){
			var headline = headlines[i];
			html += "<li><a target=\"_new\" href=\"" + headline.url + "\">" + headline.title + "</a></li>";
		}
		if(headlines.length > 0){
		}else{
			html += "<li class=\"news_li\">Currently there is no news for this region</li>";
		}
		html += "</ul>";
		html += "</li>";
		html += "<li class=\"news_li\"><a style=\"font-size:13px;color:#000\" target=\"_new\" href=\"http://local.hereuare.com/forward.jsp\">More News</a></li>";
		if(headlines.length > 0){
			html += '<li style="padding-top:10px;list-style:none;color:#999;font-weight:normal;font-size:11px"><i>News provided by Topix.com</i></li>';
		}
		return html;
}
function getFeaturings(containerid, category){
	ListingBean.getPostingHeadLines(category, 0, 15, function(headlines){
			if(headlines == null || headlines.length == 0){
				$(containerid).innerHTML = '<li style="list-style:none;color:black;text-align:center">There is no listing</li>';		
			}else{
				dwr.util.addOptions(containerid, headlines, listingHeadLineFormatter, {escapeHtml:false});
			}
	});
		
}

function getFeatured(category){
	var el = $("featured_" + category);
	getFeaturings(el, category, 'featured_btn');
}
function getLocalEvents(category){
	var el = $("event_" + category);
	getEvents(el, category, 'event_btn');
}
function highlight(obj, clsname){
	$$('a.' + clsname).each(function(el){
		el.removeClassName('darkbl_lnk');
	});
	obj.addClassName('darkbl_lnk');
}
function initScrollables(){
	setScroller('scrollable1');
	setScroller('scrollable2');
}
function eventHeadLineFormatter(headline){
	return "<a href=\"" + headline.link + "\" target=\"_new\">" + headline.title + "</a>";
}
function listingHeadLineFormatter(headline){
	var link = "/" + headline.category + "/" + headline.subcategory + "/" + headline.postingkey + ".htm"; 
	return "<a href=\"" + link + "\" target=\"_new\">" + headline.title + "</a>";
}

function setScroller(element){
	$(element).scrollTop = 0;
	if($(element).scrollHeight <= $(element).offsetHeight){
		$("handle_" + element).setStyle({visibility: 'hidden'});
	}else{
		$("handle_" + element).setStyle({visibility: 'visible'});
	}
}
function sortlist(sortfield){
	var theform = document.forms['listingform'];
	var list_sortfield = theform.sortfield.value;
	if(list_sortfield != sortfield){ //change the sortfield
		theform.sortfield.value = sortfield;
		theform.startrs.value = 0;
		theform.sortorder.value = 0;
	}else{ //change the order
		theform.sortorder.value = 1 - theform.sortorder.value;
	}
	getListing('rstlist', 'listingform');
	
}
function getPicListing(){
	var theform = document.forms['listingform'];
	theform.startrs.value = 0;
	getListing('rstlist', 'listingform');
}
var intervals = {
	scrollable2 : 0,
	scrollable1 : 0
};
function _scroll(direction, scrollableid){
	var scrollable = $(scrollableid);
	if(direction == 1){
		scrollable.scrollTop += 1;
	}else{
		scrollable.scrollTop = scrollable.scrollTop - 1;
	}	
}
function scroll(direction, scrollableid){
		var scrollable = $(scrollableid);
		var expr = "_scroll(" + direction + ",'" + scrollableid + "')";
		_scroll(direction, scrollableid);
		intervals[scrollableid] = setInterval(expr, 10);
}
function stopScroll(scrollableid){
	var interval = intervals[scrollableid];
	if(interval)
		clearInterval(interval);
}

var cur_imgid = -1;
var total_img = 0;
var thumbnails = new Array();
var vCarousel = null;
var cur_index = 0;
function addThumb(index, imgid){
	var img = new Image();
	img.src = "/showlargeimg.htm?imageid=" + imgid + "&showImage=1";
	thumbnails[index] = imgid;
	total_img ++;
}
function enlargePic(){
	if(cur_index >= 0){
		var imgid = thumbnails[cur_index];
		viewImage(imgid);
	}
}
function viewImage(id){
	var url = "http://classifieds.hereuare.com/showimgdlg.htm" ;
	var params = "viewImage=1&id=" + id;
	new AjaxRequest('dlgBox', '/showimgdlg.htm', 'post', params, openDialogBox, null);	
	// new AjaxUpdater('dlgBox', null, url, 'post', params, openDialogBox, null);
}
function openDialogBox(){
	jMoveToCenter('waitingBox');
	$('waitingBox').setStyle({display:'block'});
	setTimeout(_openDialogBox, 1000);
}

function _openDialogBox(){
	$('waitingBox').setStyle({display:'none'});
	jMoveToCenter('dlgBox');
	$('dlgBox').setStyle({display:'block'});
}
function closeDialogBox(){
	$('dlgBox').setStyle({display:'none'});	
}

function showImageFrame(id){
	$("listingdetail").setStyle({opacity:0.1});
	$("closebtn").setStyle({display:'inline'});
	$("navbtn").setStyle({display:'block'});
	$("imageview").setStyle({display:'block'});
	var img = thumbnails[id];
	var changeImage = function(){$("largeimg").src="/showlargeimg.htm?imageid=" + img + "&showImage=1";}
	
	if(id != cur_imgid){
		if(cur_imgid != -1){
			Effect.SlideUp("imageframe", {afterFinish:changeImage});
			$("thumbnail_" + cur_imgid + "_" + thumbnails[cur_imgid]).setStyle({border: '2px solid black'});
		}
		else{
			changeImage();
		}
		$("thumbnail_" + id + "_" + thumbnails[id]).setStyle({border: '2px solid blue'});
		Effect.SlideDown("imageframe", {queue:'end'});
		cur_imgid = id;
	}		
}
function adjustCarousel(){
	if(vCarousel){
		var curIndex = vCarousel.currentIndex();
		if(cur_imgid < curIndex || cur_imgid >= (curIndex + 4)){
			vCarousel.scrollTo(cur_imgid);
		}
	}
}
function closeImageFrame(){
	var showListingFrame = function(){
		cur_imgid = -1;
		$("listingdetail").setStyle({opacity:1.0});
	}
	if(cur_imgid != -1){
		$("thumbnail_" + cur_imgid + "_" + thumbnails[cur_imgid]).setStyle({border: '2px solid black'});
		Effect.SlideUp("imageframe", {afterFinish:showListingFrame});
	}
	$("closebtn").setStyle({display:'none'});
	$("navbtn").setStyle({display:'none'});
	$("imageview").setStyle({display:'none'});
}
function gotoPreviousFrame(){
	if(cur_imgid != 0){
		showImageFrame(cur_imgid - 1);
		adjustCarousel();
	}
}
function gotoNextFrame(){
	if(cur_imgid + 1 < total_img){
		showImageFrame(cur_imgid + 1);
		adjustCarousel();
	}
}
function showCityList(theform){
	var countrycode = $F('countrycode');
	var statecode = $F('statecode');
	var params = "ajaxGetCityList=1&countrycode=" + countrycode + "&statecode=" + statecode;
	new SimpleRequest('citylist', '/citylist.htm', 'get', params);	
}
function showSubCityList(letter){
	var countrycode = $F('countrycode');
	var statecode = $F('statecode');
	var params = "ajaxGetCityList=1&countrycode=" + countrycode + "&statecode=" + statecode + "&letter=" + letter;
	new SimpleRequest('citylist', '/citylist.htm', 'get', params);	

}
function removeSavedListing(listingid, containerid, formname){
	dwr.engine.beginBatch();
	var theform = document.forms[formname];
	ListingBean.removeSavedListing(listingid, function(status){
		getListingPage(containerid, theform);
	});
	dwr.engine.endBatch( {
		errorHandler : function(errorString, exception) {
			alert(exception.message);
		}
	});

}

function acceptTerm(fromUrl){
	ListingBean.acceptTerm(function(status){
		window.location = fromUrl;
	});
}
function setHomepage()
{
	if (document.all)
    {
        document.body.style.behavior='url(#default#homepage)';
        document.body.setHomePage('http://www.hereuare.com');
 
    }
    else if (window.sidebar)
    {
    if(window.netscape)
    {
         try
   {  
            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");  
         }  
         catch(e)  
         {  
        	 alert("cannot set the homepage");  
         }
    } 
    var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components. interfaces.nsIPrefBranch);
    prefs.setCharPref('browser.startup.homepage','http://www.hereuare.com');
 }
}
function showPayment(containerid){
	var params = 'showAjaxPayment';
	new SimpleRequest(containerid, '/myaccount.htm', 'get', params);
}
function showPaymentRecharge(containerid){
	var params = 'showAjaxPaymentRecharge';
	new SimpleRequest(containerid, '/payment.htm', 'get', params);
}