// JavaScript Document
function gotoStep(gotoStepNum)
{
	var gotoStepNum,catId;
	if(gotoStepNum == 1)
	{
		$('Step1').show();
		$('Step2').hide();
		$('Step3').hide();
	}
	if(gotoStepNum == 2)
	{
		catId = CheckCategorySelection();
		if (catId == 0)
		{
			$('errorStep1').show();
			setTimeout("$('errorStep1').hide()",5000);
		}
		else
		{
			$('Step1').hide();
			$('Step2').show();
			$('Step3').hide();
			$('errorStep2').hide();
			showSelectedCategoryInStep2(catId);
			goneToStep2 = true;
		}
	}
	if(gotoStepNum == 3)
	{
		$('Step1').hide();
		$('Step2').hide();
		$('Steps1to2RedHeading').hide();
		$('Step3').show();
		$('processingstatus').innerHTML = "Validating your listing..";
		isListingPosted = true;
		setTimeout("SubmitListing('"+USERID+"',"+listingid+")",1);
	}
}
function CheckCategorySelection()
{
	if ($('hdnselcatid').value != "")
		return $('hdnselcatid').value;	
	return 0;
}
function categoryselection(event)
{
	var element = Event.element(event);
	var aHrefs;
	if (element != undefined)
	{
		if (element.id.indexOf("sellcatid") != -1) {
			aHrefs = $("catlistingid").getElementsByTagName("a");
			for (i=0; i < aHrefs.length; i++)
				aHrefs[i].className = '';
			element.className = 'selectedsellcat';
			element.blur();
			$('hdnselcatid').value = element.id.replace("sellcatid","");			
		}
	}
	return false;
}
function showSelectedCategoryInStep2(selectedCatId)
{
	ShowProcessingTab(1,"Retrieving selected category..");
	var selectedCatId;
	var t_div = $('listingcategory');
	var s_div = $('catlistingid');
	new Ajax.Request(url, {
		method: 'post',
		parameters: 'from=GETCATEGORYTREE&selCatId=' + selectedCatId,
		onSuccess: function(transport) {
			if (transport.responseText.indexOf("Error:") != -1) {
				t_div.innerHTML = "Sorry! Cannot retrieve information at this time. Please go ahead with the posting, your listing will still be saved or try again later.";
			}
			else {
				t_div.innerHTML = transport.responseText + "  <a href='javascript:void(0)' onclick='gotoStep(1)'>[Change]</a>";
			}
			HideProcessingTab(1);
		}
	});
	
}
function getControlFromIFrame(imgNum, Err, imgName, imgDesc, imgStatus, imgSize)
{
	var imgNum, Err, imgName, imgDesc, imgSize;
	var imgStatus = imgStatus || '';
	if (Err == "")
	{
		var new_div = document.createElement('div');
		var new_div_id = "placeholderphotos"+imgNum;
		new_div.className = 'imageplaceholder';
		new_div.setAttribute("id",new_div_id);
		var new_img = document.createElement('img');
		new_img.src = '/uploads/' + imgName;
		new_img.className = '__imgClass';
		new_img.setAttribute("id",'upImagesId' + imgNum);
		new_div.appendChild(new_img);
		var inner_div = document.createElement('div');
		var chkbox = document.createElement('input');
		chkbox.type = 'checkbox';
		chkbox.setAttribute("id","chkboxdefault" + imgNum);
		chkbox.value = imgSize;
		Event.observe(chkbox,'mouseover',function(event){
			var ele = Event.element(event);
			$('chkboxflyout').style.left = ele.cumulativeOffset(ele)[0] + "px";
			$('chkboxflyout').style.top = (ele.cumulativeOffset(ele)[1] + 30) + "px";
			$('chkboxflyout').show();
		});	
		Event.observe(chkbox,'mouseout',function(){$('chkboxflyout').hide();});
		Event.observe(chkbox,'click',function(){makedefaultcoverimage(chkbox);});
		var new_a1 = document.createElement('a');
		new_a1.href = 'javascript:void(0)';
		new_a1.innerHTML = 'Delete';
		Event.observe(new_a1,'click',function(){deleteimage(imgName,imgNum);});
		var pipe = document.createTextNode(" | ");
		var new_a2 = document.createElement('a');
		var desc_div = createDescription(imgNum,imgName,imgDesc);
		new_a2.href = 'javascript:void(0)';
		new_a2.innerHTML = 'Add short description';
		Event.observe(new_a2,'click',function(){addImageDescription(imgNum);});
		inner_div.appendChild(chkbox);
		inner_div.appendChild(new_a1);
		inner_div.appendChild(pipe);
		inner_div.appendChild(new_a2);
		new_div.appendChild(inner_div);
		new_div.appendChild(desc_div);
		$('images_container').appendChild(new_div);
		if((imgNum == 1) && (!imgStatus)){
			$("chkboxdefault" + imgNum).checked = true;
		}
		if (imgStatus == "Default")
			$("chkboxdefault" + imgNum).checked = true;
	}
	else
	{		
		$('errorStepPhotos').innerHTML = Err;
		$('errorStepPhotos').show();
		setTimeout("$('errorStepPhotos').hide()",5000);
		imgSize = 0;
	}
	$('loadingstatus').hide();	
	var iframes = document.getElementsByTagName('iframe');
	var iframe = iframes[iframes.length - 1];
	iframe.className = 'imageiframe';
	$('hdntotalimagesize').value = parseFloat($('hdntotalimagesize').value) + parseFloat(imgSize);
	$('photolimitsizerem').innerHTML = "[ " + getAppropriateSize((MAXUPLOADSIZE_IN_MB * 1024 * 1024) - $('hdntotalimagesize').value) + " Remaining ]";
}
var reqDelImg = null;
function deleteimage(imgName,imgNum)
{
	var imgName,imgNum,imgSize;
	if (confirm("Are you sure you want to delete this image?"))
	{
		new Ajax.Request(url, {
			method: 'post',
			parameters: 'from=DELETEIMAGE&imgName=' + imgName + '&listingid=' + listingid,
			onSuccess: function(transport) {
				if (transport.responseText.indexOf("Error:") != -1) {
					$('errorStepPhotos').innerHTML = transport.responseText;
					$('errorStepPhotos').show();
					setTimeout("$('errorStepPhotos').hide()",5000);
				}
				else {
					var setChk = 0;
					if ($("chkboxdefault" + imgNum).checked)
						setChk = 1;
					imgSize = $("chkboxdefault" + imgNum).value;
					$('hdntotalimagesize').value = parseFloat($('hdntotalimagesize').value) - parseFloat(imgSize);
					$('photolimitsizerem').innerHTML = "[ " + getAppropriateSize((MAXUPLOADSIZE_IN_MB * 1024 * 1024) - $('hdntotalimagesize').value) + " Remaining ]";
					$('images_container').removeChild($("placeholderphotos"+imgNum));
					if(setChk == 1) makedefaultcoverimage();
					decrementImageCount();
				}
			}
		});
	}	
}
function makedefaultcoverimage(chkbox)
{
	var chkbox = chkbox || '';
	var firstcheckbox;
	var elements = $('images_container').getElementsByTagName("input");
	var i;
	if(chkbox) {
		for(i = 0;i<elements.length;i++)
		{
			if (elements[i].type == "checkbox") {
				elements[i].checked = false;
			}
		}
		chkbox.checked = true;
	}
	else {
		for(i = 0;i<elements.length;i++)
		{
			if (elements[i].type == "checkbox") {
				if(!firstcheckbox) firstcheckbox = elements[i];
				elements[i].checked = false;
			}
		}
		if(firstcheckbox) firstcheckbox.checked = true;
	}
}
function createDescription(imgNum,imgName,imgDesc)
{
	var imgNum,imgName,imgDesc,div_id,text_div,text_inp;
	text_div = document.createElement('div');
	div_id = "description_div_" + imgNum;
	text_div.setAttribute("id",div_id);
	text_inp = document.createElement('textarea');
	text_inp.setAttribute("id","caption" + imgNum);
	text_inp.className = 'textareacontrol';
	text_inp.value = imgDesc;
	var char_div = document.createElement('div');
	char_div.setAttribute("id","char_div" + imgNum);
	char_div.innerHTML = "200 Character(s) left";
	char_div.className = "chardiv";
	Event.observe(text_inp,"keyup",function(){setRemainingChars(imgNum)});
	Event.observe(text_inp,"blur",function(){setRemainingChars(imgNum)});
	var img = document.createElement('img');
	img.src = 'http://www.heyev.com/images/close.gif';
	img.alt = 'Close';
	Event.observe(img,'click',function(){closeImageDescription(imgNum);});
	text_div.appendChild(char_div);
	text_div.appendChild(text_inp);
	text_div.appendChild(img);
	if (imgDesc == "")
		text_div.style.display = 'none';
	return text_div;
}
function setRemainingChars(imgNum)
{
	var imgNum,txtlen;
	txtlen = $("caption" + imgNum).value.length;
	if (txtlen > 200)
		$("caption" + imgNum).value = $("caption" + imgNum).value.substring(0,200);
	$("char_div" + imgNum).innerHTML = (200 - $("caption" + imgNum).value.length).toString() + " Character(s) left";
}
function addImageDescription(imgNum)
{
	var imgNum;
	$('description_div_'+imgNum).show();
}
function closeImageDescription(imgNum)
{
	var imgNum;
	$('description_div_' + imgNum).hide();
}
function sendUP2Email()
{
	if (Trim($('emailup').value) == "") {
		$('emailup').value = "";
		return;
	}	
	$('fup').hide();
	ShowProcessingTab(2,"Sending Username and Password to " + $('emailup').value);
	new Ajax.Request(url, {
		method: 'post',
		parameters: 'from=SENDUP2EMAIL&EmailId=' + $('emailup').value,
		onSuccess: function(transport) {
			if (transport.responseText.indexOf("Error:") != -1) {
				ShowErrorTab(2, transport.responseText);
				$('fup').show();
			}
			else {
				ShowSuccessTab(2, transport.responseText);
			}
			//HideProcessingTab(2);
		}
	});
}
function SubmitListing(USERID, listingid)
{
	var catid, title, price, nego, listingtype, desc, stradr, city, state, emailid, usrname, pwd, imgSrc, imgText, params;
	catId = CheckCategorySelection();
	if (catId == 0)
	{
		$('errorStep2').innerHTML = "You have not selected a category. Please click on [Change] link above and then choose a category.";
		$('errorStep2').show();
		$('Step1').hide();
		$('Step2').show();
		$('Step3').hide();
		return false;
	}
	title = $('txttitle').value;
	price = $('txtprice').value;
	nego = $('nego').value;
	listingtype = $('listingtype').value;
	desc = $('txtdescription').value;
	stradr = $('txtstreetaddr').value;
	city = $('txtcity').value;
	state = $('state').value;
	emailid = $('txtemailid').value;
	$('divtitle').innerHTML = title;
	$('divdescgrey').innerHTML = desc.substring(0,200) + " ... ";
	desc = escape(encode(desc));
	title = escape(encode(title));
	if (USERID == "") {
		usrname = $('txtuserid').value;
		pwd = $('txtpwd').value;
	}
	else
		usrname = USERID;
	var imgElements = document.getElementsByClassName('__imgClass', $('images_container'));
	var i,id, imgNum;
	imgSrc = ""; imgText = ""; imgDef = "";
	for (i = 0;i<imgElements.length;i++) {
		imgSrc += imgElements[i].src + "^~^";
		imgNum = imgElements[i].id.replace("upImagesId","");
		imgText += $('caption' + imgNum).value + "^~^";
		imgDef += $('chkboxdefault' + imgNum).checked + "^~^";
	}
	params = "listingid="+listingid+"&cid="+catId+"&t="+title+"&p="+price+"&n="+nego+"&ltype="+listingtype+"&d="+desc+"&sa="+stradr+"&c="+city+"&st="+state+"&e="+emailid+"&u="+usrname+"&pw="+pwd+"&ims="+imgSrc+"&imt="+imgText+"&imd="+imgDef;
	new Ajax.Request(url, {
		method: 'post',
		parameters: 'from=CHECKUSERLISTING&' + params,
		onSuccess: function(transport) {
			if (transport.responseText.indexOf("Error:") != -1) {
				gotoStep(2);
				$('errorStep2').innerHTML = transport.responseText;
				$('errorStep2').show();
			}
			else {
				$('processingstatus').innerHTML = transport.responseText;
				$('errorStep2').hide();
				SaveListing(params);
			}
			//HideProcessingTab(2);
		}
	});
}
function SaveListing(params)
{
	var params;
	new Ajax.Request(url, {
		method: 'post',
		parameters: 'from=POSTUSERLISTING&' + params,
		onSuccess: function(transport) {
			if (transport.responseText.indexOf("Error:") != -1) {
				gotoStep(2);
				$('errorStep2').innerHTML = transport.responseText;
				$('errorStep2').show();
			}
			else {
				if (Trim(transport.responseText) != "") 
					listingid = transport.responseText.split("|")[0];
				$('imgProcessing').hide();
				$('listingfunctions').show();
				$('processingstatus').innerHTML = "Your Listing has been saved. It will be ONLINE only after you click on Submit.";
				$('onoffline').show();
			}
		}
	});
	$('onoffimgid').src = 'http://www.heyev.com/images/offline.gif';
	$('divtitle').className = 'offlinetitle';
	$('submitlistingid').show();
}
function SendEmailConfirmation(listid,Id)
{
	listingid = listid || listingid;
	id = Id || '';
	new Ajax.Request(url, {
		method: 'post',
		parameters: 'from=SENDEMAILCONFIRMATION&listingid=' + listingid,
		onSuccess: function(transport) {
			$('imgProcessing' + id).hide();
			$('listingfunctions' + id).show();
			$('processingstatus' + id).innerHTML = transport.responseText;
			$('onoffline' + id).show();
		}
	});
}
function LoadListingImages(listingid)
{
	var listingid, i, j;
	j = 0;
	$('loadingstatus').style.display = "block";
	new Ajax.Request(url, {
			method: 'post',
			parameters: 'from=GETLISTINGIMAGES&listingid=' + listingid,
			onSuccess: function(transport) {
				if (transport.responseText != "" ) {
					var imagesArr = transport.responseText.split("[^~^]");
					for (i=0 ; i < imagesArr.length - 1 ; i++)
					{
						j++;
						imgName = imagesArr[i++];
						imgDesc = imagesArr[i++];
						imgSize = imagesArr[i++];
						imgStatus = imagesArr[i];
						getControlFromIFrame(j, "", imgName, imgDesc, imgStatus,imgSize);
						$('loadingstatus').style.display = "block";
					}	
					setTimeout("setImageCount("+j+")",1000);
				}
				$('loadingstatus').style.display = "none";
			}
		});
		
}
function setImageCount(cnt)
{
	var cnt;
	var ifrm = window.frames['imgiframe'];
	var inputs = ifrm.document.getElementsByTagName('input');
	var i;
	for (i=0;i<inputs.length;i++)
	{
		if (inputs[i].name == "imgnum")
			inputs[i].value = cnt;
	}	
}
function decrementImageCount()
{
	var ifrm = window.frames['imgiframe'];
	var inputs = ifrm.document.getElementsByTagName('input');
	var i;
	for (i=0;i<inputs.length;i++)
	{
		if (inputs[i].name == "imgnum")
			inputs[i].value = inputs[i].value - 1;
	}
}
function ShowPreview(listid,Id)
{
	setTimeout('showldg()',0);
	listingid = listid || listingid;
	id = Id || '';
	var wid = document.viewport.getWidth() - 100;
	var hit = document.viewport.getHeight() - 100;
	new Ajax.Request(url, {
		method: 'post',
		parameters: 'from=GETPREVIEWHTML&listingid=' + listingid,
		onSuccess: function(transport) {
			if (transport.responseText.indexOf("Error:") == 0) {
				$('errorPreview').innerHTML = transport.responseText;
				$('errorPreview').show();
				setTimeout("$('DlgBoxImg').hide()",1);
				setTimeout("$('errorPreview').hide()",5000);
			}
			else {
				var dbox = new al_DialogBox(wid,hit,transport.responseText);
				dbox.ShowDialog();
			}
		}
	});
}
function showldg()
{
	$('DlgBoxImg').show();
}
EditSelected = function () {
	gotoStep(2);
}
function DeleteListing(listid,Id)
{
	listingid = listid || listingid;
	id = Id || '';
	if(confirm("Are you sure you want to delete this listing?"))
	{
		$('imgProcessing' + id).show();
		$('listingfunctions' + id).hide();
		$('processingstatus' + id).innerHTML = "Deleting this listing from the system..";
		new Ajax.Request(url, {
			method: 'post',
			parameters: 'from=DELETELISTING&listingid=' + listingid,
			onSuccess: function(transport) {
				if (transport.responseText.indexOf("Error:") != -1) {
					$('imgProcessing' + id).hide();
					$('listingfunctions' + id).show();
					$('processingstatus' + id).innerHTML = "Listing could not be deleted.";
				}
				else {
					$('deldiv' + id).hide();
					$('spacer' + id).show();
					ShowSuccessTab(3, "Your listing has been Deleted");
				}
			}
		});
	}	
}
function MakeitOnline(listid,Id)
{
	listingid = listid || listingid;
	id = Id || '';
	$('imgProcessing' + id).show();
	$('listingfunctions' + id).hide();
	$('processingstatus' + id).innerHTML = "Submitting your listing..";
	$('processingstatus' + id).show();
	new Ajax.Request(url, {
		method: 'post',
		parameters: 'from=SUBMITLISTING&listingid=' + listingid,
		onSuccess: function(transport) {
			if (transport.responseText.indexOf("Error:") != -1) {
				$('processingstatus' + id).innerHTML = transport.responseText;
				$('imgProcessing' + id).hide();
				$('listingfunctions' + id).show();
			}
			else {
				$('processingstatus' + id).innerHTML = transport.responseText;
				SendEmailConfirmation(listingid,id);
				$('onoffimgid' + id).src = 'http://www.heyev.com/images/online.gif';
				$('divtitle' + id).className = 'onlinetitle';
				$('submitlistingid' + id).hide();
				if($('submitteddt' + id)) {
					var today = new Date();
					$('submitteddt' + id).innerHTML = formatDate(today);
				}
			}			
		}
	});
}

function ShowPreviewForMyListings(listid,Id)
{
	setTimeout('showldg()',0);
	listingid = listid || listingid;
	id = Id || '';
	var wid = document.viewport.getWidth() - 100;
	var hit = document.viewport.getHeight() - 100;
	new Ajax.Request(url, {
		method: 'post',
		parameters: 'from=GETPREVIEWHTML&listingid=' + listingid,
		onSuccess: function(transport) {
			if (transport.responseText.indexOf("Error:") == 0) {
				$('errorPreview').innerHTML = transport.responseText;
				$('errorPreview').show();
				setTimeout("$('DlgBoxImg').hide()",1);
				setTimeout("$('errorPreview').hide()",5000);
			}
			else {
				var dbox = new al_DialogBox(wid,hit,transport.responseText);
				dbox.ShowDialog();
			}
		}
	});
}
function DeleteListingFromMyListings(listid,Id)
{
	listingid = listid || listingid;
	id = Id || '';
	if(confirm("Are you sure you want to delete this listing?"))
	{
		$('imgProcessing' + id).show();
		$('listingfunctions' + id).hide();
		$('processingstatus' + id).innerHTML = "Deleting this listing from the system..";
		new Ajax.Request(url, {
			method: 'post',
			parameters: 'from=DELETELISTING&listingid=' + listingid,
			onSuccess: function(transport) {
				if (transport.responseText.indexOf("Error:") != -1) {
					$('imgProcessing' + id).hide();
					$('listingfunctions' + id).show();
					$('processingstatus' + id).innerHTML = "Listing could not be deleted.";
				}
				else {
					ToggleVert('userlistingsbox' + id, 0, $('userlistingsbox' + id).getHeight());
					ShowSuccessTab(id, "Your listing has been Deleted");
				}
			}
		});
	}	
}
function EditForMyListings(listid)
{
	var listid;
	location.href = '/editlisting/'+listid+'/';
}
function getMyListings(orderby)
{
	orderby = orderby || '';
	ShowProcessingTab(-1,"Retrieving your listings...");
	new Ajax.Request(url, {
		method: 'post',
		parameters: 'from=GETMYLISTINGSHTML&orderby='+orderby,
		onSuccess: function(transport) {
			if (transport.responseText.indexOf("Error:") != -1) {
			}
			else {
				$('mylistingsdiv').innerHTML = transport.responseText;
			}
			HideProcessingTab(-1);
		}
	});
}