var showPhotos = false;
var showAvailability = false;

window.addEvent('domready', function(){
									 
if($('editListingID')){
	var listingID = $('editListingID').value;
	
	// Edit Listing MooCalendar
	var checkOutCal1 = new Calendar({ editAvailabilityCloseDate: 'Y-m-d' }, { classes: ['mooCalendar'], direction: 1 });
	var checkOutCal2 = new Calendar({ editAvailabilityStartDate: 'Y-m-d' }, { classes: ['mooCalendar'], direction: 1 });
	var checkOutCal3 = new Calendar({ editAvailabilityEndDate: 'Y-m-d' }, { classes: ['mooCalendar'], direction: 1 });
	
									 
	//add three functions to element that allows the manipulation of options
	Element.implement({  
	    removeAllOptions: function(){  
	        if(this.get('tag')!='select') return this;  
	        for(var i=this.options.length-1;i>=0;i--) this.remove(i);  
	        return this;  
	    },
		
	    addOption: function(text,value,selected){  
	        if(this.get('tag')!='select') return this;  
	        var optn = new Element('option');
	        if(text) optn.text = text;  
	        if(value) optn.value = value; 
			if(selected) optn.selected = 'selected';
	        this.options.add(optn);  
	        return this;
	    },
		
	    removeOption: function(prop,value){  
	        if(this.get('tag')!='select') return this;  
	        for(var i=this.options.length-1;i>=0;i--) {  
	            if (prop=='selected' && this.options[i].selected) this.remove(i);  
	            if (prop=='value' && this.options[i].value==value) this.remove(i);  
	            if (prop=='text' && this.options[i].text==value) this.remove(i);  
	            if (prop=='index' && i==value) this.remove(i);  
	        }
	        return this;
	    }
	});
	
	
	// Initialise districts if one is selected
	if($('editListingArea')){
		if($('editListingArea').value != 0){
			var selected = $('editListingDistrict').value;
			$('editListingDistrict').removeAllOptions();
			$('editListingDistrict').addOption('Select District...','0');
			
			var area = listingDistricts[$('editListingArea').value];
			if(area){
				area.each(function(district, districtID){
					if(district != undefined){
						if(districtID == selected){
							$('editListingDistrict').addOption(district,districtID,true);
						}else{
							$('editListingDistrict').addOption(district,districtID);
						}
					}
				});
			}			
		}
	}
	
	//when a user selects a area, reset the districts and then inject the related ones
	$('editListingArea').addEvent('change',function(){
		$('editListingDistrict').removeAllOptions();
		$('editListingDistrict').addOption('Select District...','0');
		
		var area = listingDistricts[this.value];
		if(area){
			area.each(function(district, districtID){
				if(district != undefined){
					$('editListingDistrict').addOption(district,districtID);
				}
			});
		}
	});
	
	//when a user selects an auction type, show/hide the minimum bid field
	if($('editAvailabilityType')){
		$('editAvailabilityType').addEvent('change',function(){
			if($('editAvailabilityType').value == 'Auction'){
				$('editListingReserve').set('html','Reserve ($)');
				$('editListingMinimumBid').setStyle('display','block');
				$('editAvailabilityMinimumBid').setStyle('display','block');
				$('editAvailabilityPriceModifier').setStyle('display','none');
				$('editAvailabilityCloseDateOuter').setStyle('display','block');
				$('editAvailabilityMinimumNoticeOuter').setStyle('display','none');
			}else{
				$('editListingReserve').set('html','Price ($)');
				$('editListingMinimumBid').setStyle('display','none');
				$('editAvailabilityMinimumBid').setStyle('display','none');
				$('editAvailabilityPriceModifier').setStyle('display','block');
				$('editAvailabilityMinimumNoticeOuter').setStyle('display','block');
				$('editAvailabilityCloseDateOuter').setStyle('display','none');
			}
		});
	}
	
	// Adding an auction. Checks inputs and send ajax
	if($('editAvailabilitySubmit')){
		$('editAvailabilitySubmit').addEvent('click',function(){
			var addAuction = new Request({
				method: 'get', 
				url: 'components/com_room4rent_listings/ajax/edit_listing.php',
				data: {
					'action':'addAuction',
					'listingID':listingID,
					'type':$('editAvailabilityType').value,
					'closeDate':$('editAvailabilityCloseDate').value,
					'minimumNotice':$('editAvailabilityMinimumNotice').value,
					'startDate':$('editAvailabilityStartDate').value,
					'endDate':$('editAvailabilityEndDate').value,
					'reserve':$('editAvailabilityReserve').value,
					'minimumBid':$('editAvailabilityMinimumBid').value,
					'singleDays':$('editAvailabilitySingleDays').checked,
					'perNight':$('editPricePerNight').checked
				},
				
				onSuccess: function(response){
					if(response.length){
						// Error - display errors
						$('editAvailabilityError').set('html',response);
					}else{
						// Success
						
						// Show publish button and remove note if applicable
						if($('publishNote')){
							$('publishNote').destroy();
							$('publishButtonOuter').set('html',"<a href='javascript:;' id='editListingPublish' onclick=\"publishListing('"+listingID+"');\" class='editPublishButton' style='float:right; margin-left:10px;'>Publish</a>");
						}
						
						var dateArray = $('editAvailabilityStartDate').value.split('-');
						eventsCalendarChangeMonthEditListing(dateArray[1]+'/1/'+dateArray[0], listingID);
						$('editAvailabilityError').set('html','');
						$('editAvailabilitySubmit').set('html','Added.');
						
						$('editAvailabilityStartDate').value = '';
						$('editAvailabilityEndDate').value = '';
						
						setTimeout(resetAddAuctionButton,2000);
					}
				}
			}).send();
		});
	}
	
	// Show/hide Fixed total radio when checking Add each day seperately
	if($('editAvailabilitySingleDays')){
		$('editAvailabilitySingleDays').addEvent('click',function(){
			if($('editAvailabilitySingleDays').get('checked')){
				$('editPricePerNight').set('checked','checked');
				$('editAvailabilityFixedTotal').setStyle('display','none');
			}else{
				$('editAvailabilityFixedTotal').setStyle('display','block');
			}
		});	
	}
	
	
	// display the homeowner's cut when changing a listing price
	if($('editAvailabilityReserve')){
		$('editAvailabilityReserve').addEvent('keyup',function(){
			$('editAvailabilityOwnerCut').set('html','$'+($('editAvailabilityReserve').value - ($('editAvailabilityReserve').value * $('editAvailabilityCutPercentage').value)).toFixed(2));		
		});
	}
}
	
});

window.addEvent('load', function(){
	// Show the relevant tab
	if(showPhotos){
		showTab('Photos');	
	}else if(showAvailability){
		showTab('Availability');
	}

});

// Publish / Unpublish Listing
function publishListing(listingID){
	executeAjax('components/com_room4rent_listings/ajax/edit_listing.php?action=publishListing&listingID='+listingID, 'editListingPublish');
	if($('detailTitleUnpublished').get('html').length){
		$('detailTitleUnpublished').set('html','');
		$('editListingViewLink').setStyle('display','block');
	}else{
		$('detailTitleUnpublished').set('html','(Unpublished)');
		$('editListingViewLink').setStyle('display','none');
	}
}


function resetAddAuctionButton(){
	$('editAvailabilitySubmit').set('html','Add');
}


function deleteAuction(listingID, auctionID, date){
	//executeAjax('components/com_room4rent_listings/ajax/edit_listing.php?action=deleteAuction&listingID='+listingID+'&auctionID='+auctionID, '');
	var deleteAuction = new Request({
		method: 'get', 
		url: 'components/com_room4rent_listings/ajax/edit_listing.php',
		data: {
			'action':'deleteAuction',
			'auctionID':auctionID,
			'listingID':listingID
		},
		
		onSuccess: function(response){
			if(response == '0'){
				// Show publish button and remove note if applicable
				if($('publishButtonOuter')){
					$('publishButtonOuter').set('html',"");
					$('publishNoteOuter').set('html',"<span style='font-size:11px;' id='publishNote'>Note: You must list availability before you can publish your listing.</span>");
				}	
			}
		}
	}).send();
	closeEvent();
	eventsCalendarChangeMonthEditListing(date, listingID);
}



function selectAllAuctions(){
	var checkAuctions = $$('.checkAuction');
	checkAuctions.each(function(checkAuction){
		checkAuction.set('checked','checked');
	});
}

// Edit all selected auctions on the calendar	
function editAuctions(listingID, date){
	var auctionIDs = '';
	var checkAuctions = $$('.checkAuction');
	checkAuctions.each(function(checkAuction){		
		if(checkAuction.checked){
			auctionIDs += checkAuction.value+",";
		}
	});
	
	var overlay = $('eventsOverlay');
	var card = $('eventsCard');
	var info = $('eventsInfo');
	
	overlay.setStyle('display','block');
	card.setStyle('display','block');
	
	if(overlay.getStyle('opacity') != .3){
		overlay.setStyle('opacity',0);
		var fade = new Fx.Morph(overlay, {duration: 200, transition: Fx.Transitions.Sine.easeOut}).start({'opacity':.3});
	}
	
	info.set('text','Getting Details...');
	
	centerEventDialog();

	var changeCalendar = new Request({
		method: 'get', 
		url: 'components/com_room4rent_listings/ajax/edit_listing.php',
		data: {
			'action':'editAuctions',
			'auctionIDs':auctionIDs,
			'listingID':listingID,
			'date':date
		},
		
		onSuccess: function(response){	
			info.set('html',response);
			centerEventDialog();
			setTimeout(centerEventDialog,100);
			setTimeout(centerEventDialog,200);
			setTimeout(centerEventDialog,500);
			setTimeout(centerEventDialog,1000);
			setTimeout(centerEventDialog,1500);
			setTimeout(centerEventDialog,2000);
			setTimeout(centerEventDialog,2500);
			setTimeout(centerEventDialog,5000);
		}
	}).send();
}

// Delete all selected auctions on the calendar	
function deleteAuctions(listingID, date){
	var checkAuctions = $$('.checkAuction');
	var deleteAuction;
	checkAuctions.each(function(checkAuction){
		if(checkAuction.checked){
			//executeAjax('components/com_room4rent_listings/ajax/edit_listing.php?action=deleteAuction&listingID='+listingID+'&auctionID='+checkAuction.value, '');
			deleteAuction = new Request({
				method: 'get', 
				url: 'components/com_room4rent_listings/ajax/edit_listing.php',
				data: {
					'action':'deleteAuction',
					'auctionID':checkAuction.value,
					'listingID':listingID
				},
				
				onSuccess: function(response){	
					if(response == 0){
						// Show publish button and remove note if applicable
						if($('publishButtonOuter')){
							$('publishButtonOuter').set('html',"");
							$('publishNoteOuter').set('html',"<span style='font-size:11px;' id='publishNote'>Note: You must list availability before you can publish your listing.</span>");
						}	
					}
				}
			}).send();
		}
	});
	eventsCalendarChangeMonthEditListing(date, listingID);
}



function editPrices(auctionIDs, listingID, date){
	var newPrice = $('editAuctionPrice').get('value');
	executeAjax('components/com_room4rent_listings/ajax/edit_listing.php?action=editAuctionPrices&auctionIDs='+auctionIDs+'&listingID='+listingID+'&newPrice='+newPrice, 'availabilityCalendarTitle');
	eventsCalendarChangeMonthEditListing(date, listingID);
	closeEvent();
}

function editCloseDate(auctionID){
	var newCloseDate = $('editAuctionCloseDate').value;
	executeAjax('components/com_room4rent_listings/ajax/edit_listing.php?action=editAuctionCloseDate&auctionID='+auctionID+'&newCloseDate='+newCloseDate, '');
	showAuctionEditListing(auctionID);
}

// When a user clicks on the event calendar it sets the date in the Auction options
/*function changeAuctionDate(newDate){
	if($('editAvailabilityStartDate').value.length){
		$('editAvailabilityEndDate').value = newDate;
	}else{
		$('editAvailabilityStartDate').value = newDate;
	}	
}*/


// switch the current month we are viewing
function eventsCalendarChangeMonthEditListing(date, listingID){
	
	var calendar = $("eventsCalendar_"+listingID);
	var overlay = $("eventsCalendarOverlay_"+listingID);
	
	overlay.set('style','display:block');
	
	var changeCalendar = new Request({
		method: 'get', 
		url: 'components/com_room4rent_listings/ajax/edit_listing.php',
		data: {
			'action':'changeDate',
			'listingID':listingID,
			'date':date
		},
		
		onSuccess: function(response){	
			calendar.set('html',response);
			overlay.set('style','display:none');
			
			/*var eventTips = new Tips('.eventLink', {
				className: 'eventTip',
				text: 'title'
			});*/
			
		}
	}).send();
}

// show the current event card
function showAuctionEditListing(auctionID){
	var overlay = $('eventsOverlay');
	var card = $('eventsCard');
	var info = $('eventsInfo');
	
	overlay.setStyle('display','block');
	card.setStyle('display','block');
	
	if(overlay.getStyle('opacity') != .3){
		overlay.setStyle('opacity',0);
		var fade = new Fx.Morph(overlay, {duration: 200, transition: Fx.Transitions.Sine.easeOut}).start({'opacity':.3});
	}
	
	info.set('text','Getting Details...');
	
	centerEventDialog();

	var changeCalendar = new Request({
		method: 'get', 
		url: 'components/com_room4rent_listings/ajax/edit_listing.php',
		data: {
			'action':'getAuctionDetails',
			'auctionID':auctionID
		},
		
		onSuccess: function(response){	
			info.set('html',response);
			centerEventDialog();
			setTimeout(centerEventDialog,100);
			setTimeout(centerEventDialog,200);
			setTimeout(centerEventDialog,500);
			setTimeout(centerEventDialog,1000);
			setTimeout(centerEventDialog,1500);
			setTimeout(centerEventDialog,2000);
			setTimeout(centerEventDialog,2500);
			setTimeout(centerEventDialog,5000);
		}
	}).send();
	
}


function showTab(tab){
	$('detail'+$$('.detailTabCurrent').get('html')).setStyle('display','none');
	$$('.detailTabCurrent').set('class','detailTab');
	$('detail'+$('tab'+tab).get('html')).setStyle('display','block');
	$('tab'+tab).set('class','detailTabCurrent');
	// Show/hide the fancy uploader
	if($('editImageUpload')){
		if(tab == 'Photos'){
			$('editImageUpload').setStyle('visibility','visible');
		}else{
			$('editImageUpload').setStyle('visibility','hidden');
		}
	}
}


function deleteConfirm(listingID){
	var overlay = $('eventsOverlay');
	var card = $('eventsCard');
	var info = $('eventsInfo');
	
	overlay.setStyle('display','block');
	card.setStyle('display','block');
	
	if(overlay.getStyle('opacity') != .3){
		overlay.setStyle('opacity',0);
		var fade = new Fx.Morph(overlay, {duration: 200, transition: Fx.Transitions.Sine.easeOut}).start({'opacity':.3});
	}
	
	var content = "<h1>Delete Listing</h1><br />";
		content += "<p>Are you sure you want to delete this listing?</p>";
		content += "<a href='javascript:;' onclick=\"deleteListing('"+listingID+"');\" class='editDeleteButton' style='float:right; margin-left:10px;'>Delete it!</a>";
		content += "<div class='clear'></div>";
	
	info.set('html',content);
	centerEventDialog();
}

function deleteListing(listingID){
	$('editListingViewLink').setStyle('display','none');
	if($('editListingPublish')){
		$('editListingPublish').setStyle('display','none');
	}
	$('editListingDelete').setStyle('display','none');
	executeAjax('components/com_room4rent_listings/ajax/edit_listing.php?action=deleteListing&listingID='+listingID,'editDetailContentOuter');
	$('editDetailContentOuter').setStyle('background-image','none');
	closeEvent();
}