// JavaScript Document

// Variables
var search_id = false;
var search_string = "";
var search_original = "";

var acc_id = "";

var realestate_photos = [];
var classifieds_photos = [];

//window.debug = false;

// Once the page has loaded... start everything up
Event.observe(window, 'load', function() {	
	$$('div.small_ad_none').each(function(ad) {
		Event.observe(ad, 'click', function() { window.location = 'withus.php'; });
	});
	
	$$('div.large_ad_none').each(function(ad) {
		Event.observe(ad, 'click', function() { window.location = 'withus.php'; });
	});
	
	if ($('login')) {
		Event.observe('login', 'submit', function(e) {
			Event.stop(e);
			
//			if (window.debug) {
//				doLogin($F('login_username'), $F('login_password'), $F('login_remember'));
//			} else {
//				alert('This site is currently disabled while we make some updates. Please check back soon.');
//			}
			
			if (validateLogin()) {
				doLogin($F('login_username'), $F('login_password'), $F('login_remember'));
			}
		});
	} 
	
	if ($('logout')) {
		Event.observe('logout', 'click', doLogout);
	}
	
	if ($('properties_container')) {
		$$('div.property').each(function(ele) {
			Event.observe(ele, 'click', function(e) { window.location = 'realestate_detail.php?id=' + ele.getAttribute('name').substr(9); });
		});
	}
	
	if ($('classifieds_container')) {
		$$('div.classified').each(function(ele) {
			Event.observe(ele, 'click', function(e) { window.location = 'classifieds_detail.php?id=' + ele.getAttribute('name').substr(11); });
		});
	}
	
	if ($('businesses_container')) {
		$$('div.business').each(function(ele) {
			Event.observe(ele, 'click', function(e) { window.open(ele.getAttribute('name')); });
		});
	}
	
	if ($('property_images')) {
		$$('div#property_images .small_image_container .small_image').each(function(ele) {
			Event.observe(ele, 'click', function() { changeImage(ele.getAttribute('name').substr(6), 'realestate', 'large_property_image') });
		});
	}
	
	if ($('classified_images')) {
		$$('div#classified_images .small_image_container .small_image').each(function(ele) {
			Event.observe(ele, 'click', function() { changeImage(ele.getAttribute('name').substr(6), 'classifieds', 'large_classified_image') });
		});
	}
	
	if ($('classifieds_mini_container')) {
		acc_id = $$('div#classifieds_mini_container .classified')[0].getAttribute('name').substr(2);
		
		$$('div#classifieds_mini_container .classified .title').each(function(ele) {
			Event.observe(ele, 'click', function() {
				if (acc_id != ele.getAttribute('name').substr(6)) {
					Effect.BlindUp('desc_' + acc_id, { duration: .5 });
					Effect.BlindDown('desc_' + ele.getAttribute('name').substr(6), { duration: .5 });
					acc_id = ele.getAttribute('name').substr(6);
				}
			});
		});
		
		$$('div#classifieds_mini_container .classified .description').each(function(ele) {
			Event.observe(ele, 'click', function() {
				window.location = 'classifieds_detail.php?id=' + ele.up().getAttribute('name').substr(2);
			});
		});
//		var verticalAccordion = new accordion('classifieds_mini_container');								
//		verticalAccordion.activate($$('#classifieds_mini_container .classified .title')[0]);
	}
	
	if ($('keyword_search')) {
		search_original = $('keyword_container').innerHTML;
		
		Event.observe('keyword_search', 'keyup', function(e) {
			if (e.keyCode == Event.KEY_ESC) {
				$('keyword_search').update(search_original);
			} else {
				startSearch(Event.element(e).value);
			}
		});
	}
	
	if ($('realestate_upload')) {
		Event.observe('realestate_upload', 'click', openRealEstateUpload);
	}
	
	if ($('classifieds_upload')) {
		Event.observe('classifieds_upload', 'click', openClassifiedsUpload);
	}
	
	if ($('basic_upload')) {
		Event.observe('basic_upload', 'click', openBasicUpload);
	}
	
	if ($('banner_upload')) {
		Event.observe('banner_upload', 'click', openBannerUpload);
	}
	
	if ($('duration_form')) {
		$$('input[name=account]').each(function(ele) {
			ele.observe('click', function(e) { setDuration(ele.value); });
		});
	}
	
	if ($('edit_listing')) {
		Event.observe('edit_listing', 'click', openListingMessage);		
	}
	
	if ($('edit_limits')) {
		Event.observe('edit_limits', 'click', openLimits);		
	}
	
	$$('a').each(function(ele) {
		if (ele.getAttribute('name') == 'comingsoon') {
			Event.observe(ele, 'click', function(e) {
				Event.stop(e);
				
				alert('This feature is coming soon! Please check back often for more updates.'); 				
			});
		} else if (ele.getAttribute('name') == 'locked') {
			Event.observe(ele, 'click', function(e) {
				if (!window.debug) {
					Event.stop(e);
				
					alert('This site is currently disabled while we make some updates. Please check back soon.');
				}
			});
		}
	});
});

var openBasicUpload = function(e) {
	Event.stop(e);
	window.open('upload/basic_upload.html', '', 'width=350,height=200');
};

var openBannerUpload = function(e) {
	Event.stop(e);
	window.open('upload/banner_upload.html', '', 'width=250,height=125');
};

var openListingMessage = function(e) {
	Event.stop(e);
	alert('To edit or delete a specific classified or real estate listing please visit the listing on the website. On the listing details page you will find "Edit this listing" and "Delete this listing" buttons at the bottom of the screen.');
};

var openLimits = function(e) {
	Event.stop(e);
	window.open('admin.banner_count.php', '', 'width=250,height=100');
};

// Register Functions
var setDuration = function(type) {
	$('duration').update();
	
	switch (type) {
		case '4':
			$('item_name').value = 'Poster Account';
			
			var one = new Element('option', { 'value': '1 Month' }).update('1 Month - $' + (20 * discount).toFixed(2));
			var six = new Element('option', { 'value': '6 Months' }).update('6 Months - $' + (120 * discount).toFixed(2));
			var twelve = new Element('option', { 'value': '12 Months' }).update('12 Months - $' + (240 * discount).toFixed(2));
			
			$('duration').insert(one).insert(six).insert(twelve);
			
			$('one_value').value = (20 * discount).toFixed(2);
			$('six_value').value = (20 * discount).toFixed(2);
			$('twelve_value').value = (20 * discount).toFixed(2);
			break;
		
		case '3':
			$('item_name').value = 'Business Account';
			
			var one = new Element('option', { 'value': '1 Month' }).update('1 Month - $' + (50 * discount).toFixed(2));
			var six = new Element('option', { 'value': '6 Months' }).update('6 Months - $' + (300 * discount).toFixed(2));
			var twelve = new Element('option', { 'value': '12 Months' }).update('12 Months - $' + (600 * discount).toFixed(2));
			
			$('duration').insert(one).insert(six).insert(twelve);
			
			$('one_value').value = (50 * discount).toFixed(2);
			$('six_value').value = (300 * discount).toFixed(2);
			$('twelve_value').value = (600 * discount).toFixed(2);
			break;
		
		case '2':
			$('item_name').value = 'Banner Account';
			
			var one = new Element('option', { 'value': '1 Month' }).update('1 Month - $' + (75 * discount).toFixed(2));
			var six = new Element('option', { 'value': '6 Months' }).update('6 Months - $' + (450 * discount).toFixed(2));
			var twelve = new Element('option', { 'value': '12 Months' }).update('12 Months - $' + (900 * discount).toFixed(2));
			
			$('duration').insert(one).insert(six).insert(twelve);
			
			$('one_value').value = (75 * discount).toFixed(2);
			$('six_value').value = (450 * discount).toFixed(2);
			$('twelve_value').value = (900 * discount).toFixed(2);
			break;
	}
};

// Login Functions
var hideLoginLoad = function() {
	$('login_throb').hide();
};

var showLoginLoad = function() {
	$('login_throb').show();
};

var validateLogin = function() {
	if ($('login_username').present() && $('login_password').present()) {
		return true;
	} else {
		alert('Login incorrect. Update this with validation later...');
	}
};

var doLogin = function(username, password, remember) {
	var params = 'username=' + username + '&password=' + password + '&remember=' + remember;
	
	new Ajax.Request('login.php', {
		parameters: params,
		onLoading: showLoginLoad,
		onComplete: function(r) {
			r = r.responseText.evalJSON();
			
			if (r.success) {
				$('user_links').update();
				
				if (r.type == 1) {
					$('user_links').insert(new Element('li').update(new Element('a', { href: 'admin.users_list.php' }).update('View/Edit Users')));
					$('user_links').insert(new Element('li').update(new Element('a', { href: 'admin.banner_list.php' }).update('Manage Site Advertisements')));
					$('user_links').insert(new Element('li').update(new Element('a', { href: 'admin.sponsor_list.php' }).update('Manage Site Sponsors')));
					$('user_links').insert(new Element('li').update(new Element('a', { href: '', id: 'edit_limits' }).update('Manage Advertisement Limits').observe('click', openLimits)));
					$('user_links').insert(new Element('li').update(new Element('a', { href: 'admin.promo_list.php' }).update('Manage Promotional Codes')));
					$('user_links').insert(new Element('li').update(new Element('a', { href: 'admin.cat_list.php' }).update('Manage Classifieds Categories')));
					$('user_links').insert(new Element('li', { 'class' : 'spacer' }));
					$('user_links').insert(new Element('li').update(new Element('a', { href: 'admin.page_list.php' }).update('Manage Site Content')));
					$('user_links').insert(new Element('li').update(new Element('a', { href: '', id: 'basic_upload' }).update('Upload a File').observe('click', function(e) { Event.stop(e); openBasicUpload(); })));
					$('user_links').insert(new Element('li', { 'class' : 'spacer' }));
				}
				
				$('user_links').insert(new Element('li').update(new Element('a', { href: 'post.realestate.php' }).update('Add a real estate listing')));
				$('user_links').insert(new Element('li').update(new Element('a', { href: 'post.classifieds.php' }).update('Add a classifieds listing')));
				
				if (r.type > 1 && r.type < 3) {
					$('user_links').insert(new Element('li', { 'class' : 'spacer' }));
					//$('user_links').insert(new Element('li').update(new Element('a', { href: 'post.banner.php' }).update('Manage your site advertisement')));
				}
				
				$('user_links').insert(new Element('li', { 'class' : 'spacer' }));
				$('user_links').insert(new Element('li').update(new Element('a', { href: 'profile.view.php?id=' + r.id }).update('View/Edit Profile')));
				$('user_links').insert(new Element('li').update(new Element('a', { href: '' }).update('Logout').observe('click', doLogout)));
				
				$('login_container').hide();
				$('user_title').update('Welcome, ' + r.name);
				$('profile_container').show();
			} else {
				if (r.reason == 'unapproved') {
					alert('There was a problem with your login. Your payment method has yet to be approved. Please allow up to one business day from your registration for your payment to be processed. If you are still getting this message after one business day, please visit PayPal (http://www.paypal.com) for more information.');
				} else if (r.reason == 'failed') {
					alert('There was a problem with your login. Either your username or password was incorrect. If you feel this is error, please contact the webmaster.');
				}
			}
			
			hideLoginLoad();
		}
	});
};

var doLogout = function(e) {
	Event.stop(e);
	
	var addr = String(window.location);
	var page = addr.substr(addr.lastIndexOf("/") + 1);
	
	new Ajax.Request('logout.php', {
		onLoading: showLoginLoad,
		onComplete: function(r) {
			r = r.responseText.evalJSON();
			
			if (page.substr(0, 5) == 'admin' || page.substr(0, 7) == 'profile') {
				window.location = 'index.php';			
			} else {
				$('profile_container').hide();
				$('login_container').show();
			}
			
			hideLoginLoad();
		}
	});
};

// Real Estate and Classified Images
var changeImage = function(image, folder, con) {
	var img = new Element('img', { width: '364', height: '274', src: 'images/' + folder + '/large_' + image });
	$(con).update(img);
};

// Classifieds Keyword Search
var startSearch = function(val) {
	if (search_id) clearTimeout(search_id);
	search_id = setTimeout("sendSearch()", 500);
	search_string = val;
};

var sendSearch = function() {
	if (search_string.length > 1) {
		new Ajax.Updater('keyword_container', 'includes/search.keyword.php', { parameters: 'search=' + search_string });
	} else {
		$('keyword_container').update(search_original);
	}
	
	clearTimeout(search_id);
};

// Listing Postings
var loadClassifiedsFields = function(id) {
	new Ajax.Request('includes/post.classifieds_list.php', {
		parameters: 'id=' + id,
		onSuccess: function(r) {
			fields = r.responseText.split(',');
			
			var table = new Element('table', { cellpadding: 0, cellspacing: 0, border: 0 });
			
			fields.each(function(f) {
				var tr = new Element('tr').insert(new Element('td', { width: 125 }).update(f)).insert(new Element('td', { width: 300 }).update(new Element('input', { id: f.toLowerCase(), name: f.toLowerCase(), 'class': 'fields_info' })));
				table.insert(tr);
			});
			
			$('fields_cell').innerHTML = '<table cellpadding="0" cellspacing="0" border="0">' + table.innerHTML + '</table>';
		}
	});
};

var openRealEstateUpload = function(e) {
	if (realestate_photos.length == 6) { alert('You have exceeded the maximum number of photos for this listing. If you wish to post a photo, please delete one from the list.'); return false; }
	
	Event.stop(e);
	window.open('upload/realestate_upload.html', '', 'width=250,height=125');	
};

var addRealEstatePhoto = function(file) {
	if (realestate_photos.indexOf(file) != '-1') { alert('This image is already included.'); return false; }
	
	realestate_photos.push(file);
	var index = realestate_photos.length - 1;
	
	var img = new Element('img', { src: 'images/realestate/thumb_' + file, width: 118, height: 89 });
	var opt = new Element('p', {}).update(new Element('a', { href: ''}).update('Delete').observe('click', function(e) { Event.stop(e); removeRealEstatePhoto(file); }));
	var con = new Element('div', {}).insert(img).insert(opt);
	
	$('post_picture_container').insert(con);
};

var removeRealEstatePhoto = function(file) {
	if (!confirm('Are you sure you want to delete this photo?')) return false;
	
	// Open a window to a delete script that outputs a window.close()
	realestate_photos = realestate_photos.without(realestate_photos[realestate_photos.indexOf(file)]);
	
	$('post_picture_container').update();
	
	realestate_photos.each(function (image) {
		var img = new Element('img', { src: 'images/realestate/thumb_' + image, width: 118, height: 89 });
		var opt = new Element('p', {}).update(new Element('a', { href: ''}).update('Delete').observe('click', function(e) { Event.stop(e); removeRealEstatePhoto(image); }));
		var con = new Element('div', {}).insert(img).insert(opt);
		
		$('post_picture_container').insert(con);
	});
};

var openClassifiedsUpload = function(e) {
	if (classifieds_photos.length == 6) { alert('You have exceeded the maximum number of photos for this listing. If you wish to post a photo, please delete one from the list.'); return false; }
	
	Event.stop(e);
	window.open('upload/classifieds_upload.html', '', 'width=250,height=125');	
};

var addClassifiedsPhoto = function(file) {
	if (classifieds_photos.indexOf(file) != '-1') { alert('This image is already included.'); return false; }
	
	classifieds_photos.push(file);
	var index = classifieds_photos.length - 1;
	
	var img = new Element('img', { src: 'images/classifieds/thumb_' + file, width: 118, height: 89 });
	var opt = new Element('p', {}).update(new Element('a', { href: ''}).update('Delete').observe('click', function(e) { Event.stop(e); removeClassifiedsPhoto(file); }));
	var con = new Element('div', {}).insert(img).insert(opt);
	
	$('post_picture_container').insert(con);
};

var removeClassifiedsPhoto = function(file) {
	if (!confirm('Are you sure you want to delete this photo?')) return false;
	
	// Open a window to a delete script that outputs a window.close()
	classifieds_photos = classifieds_photos.without(classifieds_photos[classifieds_photos.indexOf(file)]);
	
	$('post_picture_container').update();
	
	classifieds_photos.each(function (image) {
		var img = new Element('img', { src: 'images/classifieds/thumb_' + image, width: 118, height: 89 });
		var opt = new Element('p', {}).update(new Element('a', { href: ''}).update('Delete').observe('click', function(e) { Event.stop(e); removeClassifiedsPhoto(image); }));
		var con = new Element('div', {}).insert(img).insert(opt);
		
		$('post_picture_container').insert(con);
	});
};