var state = 'none';

// FUNCTION TO SIGN OUT USER
function signOut() {
	var url = 'ajax/sign-out.php';
	
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			location.reload(true);
		}
	});	
}

// AJAX CALL TO DELETE LISTING
function signup(){

	fullName = $('full-name').value;
	username = $('user').value;
	password = $('pwd').value;
	cpassword = $('confirm-pwd').value;
	email = $('email').value;
	captcha = $('captcha').value;

	// VALIDATE FIELDS
	if (validateSignUp() == false) {
		return false;
	}
	
	var url = 'ajax/save-user.php?full-name=' + fullName + '&username=' + username + '&password=' + password + '&email=' + email + '&captcha=' + captcha;
		
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			if (transport.responseText == "The Username or Email Already Exist") {
				$('errorUser').innerHTML = "<img src='static/images/error.png' style='margin-bottom:-1px' title='Username Already Exists'/>";
				$('errorEmail').innerHTML = "<img src='static/images/error.png' style='margin-bottom:-1px' title='Email Already Exists'/>";
				$('errorUser').style.display = "block";
				$('errorEmail').style.display = "block";
				return false;	
			}
			if (transport.responseText == "The Username Already Exists") {
				
				$('errorUser').innerHTML = "<img src='static/images/error.png' style='margin-bottom:-1px' title='Username Already Exists'/>";
				$('errorUser').style.display = "block";
				$('errorEmail').style.display = "none";
				return false;	
			}
			if (transport.responseText == "The Email Address Already Exists") {
				$('errorEmail').innerHTML = "<img src='static/images/error.png' style='margin-bottom:-1px' title='Email Already Exists'/>";
				$('errorUser').style.display = "none";
				$('errorEmail').style.display = "block";
				return false;	
			}
			if (transport.responseText == "Word Identification Failed") {
				$('errorCaptcha').innerHTML = "<img src='static/images/error.png' style='margin-bottom:-1px' title='Word Identification Failed'/>";
				$('errorCaptcha').style.display = "block";
				return false;	
			}
			
			$('msg-box').innerHTML = transport.responseText;	
			$('msg-box').style.display = 'block';
			$('msg-box').fade({ duration: 8.0 });
			$('background').style.display = 'none';
			$('outter').style.display = 'none';
			$('inner').style.display = 'none';
		}
	});	
}

	
// FUNCTION TO SHOW LOGIN FORM
function showLogin() {
	$('login-link-holder').style.display = 'none';
	$('forgot-pwd-form-holder').style.display = 'none';
	$('login-form-holder').appear();
	setTimeout("$('username').focus()", 50);
}

// FUNCTION TO SHOW FORGOT PASSWORD FORM
function forgotPwd() {
	$('login-form-holder').style.display = 'none';
	$('forgot-pwd-form-holder').appear();
	setTimeout("$('email-address').focus()", 50);
}

// AJAX CALL TO LOGIN USER
function getLogin() {
	var username = $('username').value;
	var password = $('password').value;
		
	// VALIDATE FIELDS
	if (validateLogin() == false) {
		return false;
	}
			
	// SHOW SPINNER WHILE DATA IS FETCHED
	$('spinner-top').style.display = "block";
	$('login-form-holder').style.display = 'none';
	$('login-action-holder').style.display = 'none';
	var url = 'ajax/login.php?username=' + username + '&password=' + password;

	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {

			// IF THERE WAS A LOGIN ERROR THEN SHOW MESSAGE AS WELL AS FORM
			if (transport.responseText=="Incorrect username or password"){
				$('login-form-holder').style.display = 'block';
				$('error-box').innerHTML = transport.responseText;	
				$('error-box').style.display = 'block';
				$('error-box').fade({ duration: 5.0 }); 
				$('username').focus();
			}
			else if(transport.responseText=="Please activate your account first") {
				$('login-form-holder').style.display = 'block';
				$('error-box').innerHTML = transport.responseText;	
				$('error-box').style.display = 'block';
				$('error-box').fade({ duration: 5.0 }); 
				$('username').focus();
			}
			else {
				$('login-form-holder').style.display = 'none';
				$('login-action-holder').innerHTML = transport.responseText;
				$('login-action-holder').style.display = 'block';
				
				// IF USER SIGNED IN FROM LISTINGS PAGE THEN REFRESH LISTINGS PAGE
				var pageName = window.location.pathname;
				var pageName = pageName.substring(pageName.lastIndexOf('/') + 1);
				if (pageName == 'listings.php') {
					refreshListings();
				}
			}
			
			$('spinner-top').style.display = "none";
		}
	});
}

// AJAX CALL TO RESET PASSWORD
function resetPassword() {
	var email = $('email-address').value;
		
	// VALIDATE FIELDS
	if (validateForgotPwd() == false) {
		return false;
	}
	
	// SHOW SPINNER WHILE DATA IS FETCHED
	$('spinner-top').style.display = "block";
	$('forgot-pwd-form-holder').style.display = 'none';
	$('login-action-holder').style.display = 'none';
		
	var url = 'ajax/reset-password.php?email=' + email;
	
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			
			// IF THERE WAS A LOGIN ERROR THEN SHOW MESSAGE AS WELL AS FORM
			if (transport.responseText=="Invalid Email Address"){
				$('error-box').innerHTML = transport.responseText;	
				$('error-box').style.display = 'block';
				$('error-box').fade({ duration: 7.0 }); 
				$('forgot-pwd-form-holder').style.display = 'block';
				$('email-address').focus();
			}
			else {
				$('msg-box').innerHTML = transport.responseText;	
				$('msg-box').style.display = 'block';
				$('msg-box').fade({ duration: 7.0 }); 
				$('forgot-pwd-form-holder').style.display = 'none';
				$('login-form-holder').appear();
			}
			
			$('spinner-top').style.display = "none";
		}
	});
}

// FUNCTION TO CHANGE TABS
function changeTab(parentId, categoryId){

	$('tab-holder').style.opacity ='0.20';
	$('cbo-cities').value = 0;
	$('desc').value = "";
	
	var url = 'ajax/get-tabs.php?parent-id=' + parentId + '&category-id=' + categoryId;

	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {

		$('tabs').innerHTML = "<div class='tabs'>" + transport.responseText + "</div>";
		$('tab-holder').style.opacity ='1';
		getListings(parentId, categoryId, 1, 'Date DESC');
		}
	});
}


// FUNCTION TO POP UP HIDDEN DIVS
function popup(focusControl, formName, impId, height, page) {

	// HIDE/UNHIDE CHECKS
	if (state == 'block') {
		state = 'none';
	}
	else {
		state = 'block';
	}
	
	if(state == 'block') {
		var url = 'ajax/' + formName + '?id=' + impId;
	
		new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			$('holder').innerHTML = transport.responseText;
			// IF CALLED FROM INBOX THEN CHANGE MESSAGE STATUS TO READ 		
			if (formName == 'messages-form.php') {
				$('send').style.display ="none";
				getMessages(page, impId);
				updateNewMessageCount();				
			}
			// IF CALLED FROM LISTINGS PAGE THEN HIDE TOP MESSAGE DIV
			if (formName == 'contact-form.php') {
				$('reply').style.display ="none";
				$('delete').style.display ="none";
				$('message-holder').style.display = "none";
			}	
			$(focusControl).focus();
			addMarkupControls();
			
		}
		});
	}
	
	if (state == 'none') {
		$('holder').innerHTML = "";
	}
	
	$('background').style.display = state;
	$('outter').style.display = state;
	$('inner').style.display = state;
}

// JS TO ADD NICEEDIT CONTROLS TO TEXT AREA
function addMarkupControls() {
	new nicEditor({maxHeight : 75}).panelInstance('description');
    var area2 = new nicEditor({fullPanel : true}).panelInstance('description');
}
	
// AJAX CALL TO GET PROPERTY LISTINGS
function getListings(parentId, categoryId, page, sorting) {	

	var cityId = $('cbo-cities').value;
	var description = $('desc').value;
		
	// PASS VALUES TO HIDDEN FIELDS
	$('page-hidden').value = page;
	$('sort-hidden').value = sorting;
	$('parentId-hidden').value = parentId;
	if (categoryId != 0 ) {
		$('categoryId-hidden').value = categoryId;
	}
	else {
		 categoryId = $('categoryId-hidden').value;
	}
	
	$('content-holder').style.opacity ='0.20';
	
	var url = 'ajax/get-listings.php?parent-id=' + parentId + '&category-id=' + categoryId + '&city-id=' + cityId + '&description=' + description + '&page=' + page + '&sorting=' + sorting;
	
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {

			$('content-holder').innerHTML =  "<table style='width:100%; font-size:10pt' cellspacing='0' cellpadding='3px'>" + transport.responseText;	
			$('content-holder').style.opacity ='1';
		}
	});
}

// AJAX CALL TO GET MY PROPERTY LISTINGS
function getMyListings(page) {	
		
	var url = 'ajax/get-my-listings.php?page=' + page;

	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {

			$('content-holder').innerHTML =  "<table style='width:100%; font-size:10pt' cellspacing='0' cellpadding='3px'>" + transport.responseText;	
		}
	});
}

// AJAX CALL TO GET INFORMATION ABOUT USER
function getInfo() {

	var url = 'ajax/get-info.php';
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			$('info-holder').innerHTML = transport.responseText;	
			$('info-holder').style.display = 'block';
		}
	});
}

// AJAX CALL TO SAVE USER INFORMATION
function saveInfo(userId) {
	var fullname = $('fullname').value;
	var email = $('email').value;
	
	// VALIDATE FIELDS
	if (validateSaveInfo() == false) {
		return false;
	}
	
	var url = 'ajax/save-user-info.php?user-id=' + userId + '&name=' + fullname + '&email=' + email;

	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			$('msg-box').innerHTML = transport.responseText;	
			$('msg-box').style.display = 'block';
			$('msg-box').fade({ duration: 5.0 }); return false;
		}
	});	
}

// AJAX CALL TO RESET USER PASSWORD
function savePassword(userId) {
	var oldPwd = $('old-password').value;
	var newPwd = $('new-password').value;
	
	// VALIDATE FIELDS
	if (validateSavePassword() == false) {
		return false;
	}
	
	var url = 'ajax/save-user-pwd.php?user-id=' + userId + '&old-password=' + oldPwd + '&new-password=' + newPwd;
	
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			if (transport.responseText=='Your Old Password is Incorrect'){
				$('errorOld-Pwd').innerHTML = "<img src='static/images/error.png' style='margin-bottom:-1px' title='Your Old Password is Incorrect'/>";
				$('errorOld-Pwd').style.display = 'block';
			}
			else {
				$('msg-box').innerHTML = transport.responseText;	
				$('msg-box').style.display = 'block';
				$('msg-box').fade({ duration: 5.0 }); return false;
			}
		}
	});	
}

// AJAX CALL TO SAVE LISTING
function saveListing(userId) {
	var categoryId = $('cbo-categories').value;
	var cityId = $('cbo-cities').value;
	var headline = $('headline').value;
	var description = nicEditors.findEditor('description').getContent();
	description = description.replace(/&nbsp;/g, " ");
	var price = $('price').value;
	var image = $('userfile').value;
	
	// VALIDATE IMAGE FILE
	if (image != "") {
		var fileType = image.substr(-3, 3);
		if (fileType != 'jpg' && fileType != 'gif' && fileType != 'png') {
			$('errorFile').innerHTML = "<img src='static/images/error.png' style='margin-bottom:-1px' title='Select a Valid Image File'";
			$('errorFile').style.display = 'block';
		}
	}
	
	// VALIDATE FIELDS
	if (validateListing() == false) {
		return false;
	}
	
	// IF IMAGE IS UPLOADED THEN SUBMIT FORM
	if (image != "") {
		$('add').submit();
		return false;
	}
		
	var url = 'ajax/save-listing.php?category-id=' + categoryId + '&headline=' + headline + '&city-id=' + cityId + '&description=' + description + '&price=' + price + '&user-id=' + userId;

	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			$('msg-box').innerHTML = transport.responseText;	
			$('msg-box').style.display = 'block';
			$('msg-box').fade({ duration: 5.0 });
			$('background').style.display = 'none';
			$('outter').style.display = 'none';
			$('inner').style.display = 'none';
			getMyListings(1);
		}
	});	
}

// AJAX CALL TO DELETE LISTING
function deleteListing(listId, imageId, currentPage){
	var result = confirm("Are you sure you wish to delete this listing?");
	
	if (result == true) {
		var url = 'ajax/delete-listing.php?list-id=' + listId + '&image-id=' + imageId;
		
		new Ajax.Request(url, {
			method: 'get',
			onSuccess: function(transport) {
				$('msg-box').innerHTML = transport.responseText;	
				$('msg-box').style.display = 'block';
				$('msg-box').fade({ duration: 5.0 });
				getMyListings(currentPage);
				getInfo();
			}
		});	
	}
}

// AJAX CALL TO REPORT LISTING
function reportListing(listId){

	var url = 'ajax/report-listing.php?list-id=' + listId;
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			$('msg-box').innerHTML = transport.responseText;	
			$('msg-box').style.display = 'block';
			$('msg-box').fade({ duration: 7.0 });
		}
	});	
}

// REFRESH LISTINGS 
function refreshListings() {
	var parentId = $('parentId-hidden').value;
	var categoryId = $('categoryId-hidden').value;
	var page = $('page-hidden').value;
	var sorting = $('sort-hidden').value;
	
	getListings(parentId, categoryId, page, sorting);
}

//AJAX TO GET NEW RANDOM AD
function showImage() {
	var theImages = new Array() ;
	
	theImages[0] = "<a href='http://www.datafocal.com' title='DataFocal Systems' target='_blank'><img src='static/images/ads/datafocal.png' alt='DataFocal Systems' border='none'/></a>";
	theImages[1] = "<a href='http://www.iigs.edu.pk' title='International Islamic Grammar School Islamabad' target='_blank'><img src='static/images/ads/iigs.png' alt='International Islamic Grammar School Islamabad' border='none'/></a>";
	theImages[2] = "<a href='http://www.iriswll.com' title='IRIS Bahrain Real Estate' target='_blank'><img src='static/images/ads/iris.png' alt='IRIS Real Estate in Bahrain' border='none'/></a>";
		
	var j = 0;
	var p = theImages.length;
	var preBuffer = new Array();
	for (i = 0; i < p; i++){
	   preBuffer[i] = new Image();
	   preBuffer[i].src = theImages[i];
	}
	var whichImage = Math.round(Math.random()*(p-1));
	
	$('ad-holder').innerHTML = "<h2 style='margin-bottom:5px; text-align:left'>Advertisment</h2>" + theImages[whichImage];
}

// FUNCTION TO SEND MESSAGE 
function sendMessage(toId) {
	
	var messageText = nicEditors.findEditor('description').getContent();
	messageText = messageText.replace(/&nbsp;/g, " ");
	
	// VALIDATE FIELDS
	if (validateMessage() == false) {
		return false;
	}
	
	var url = 'ajax/send-message.php?to-id=' + toId + '&message=' + messageText;
	
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			$('msg-box').innerHTML = transport.responseText;	
			$('msg-box').style.display = 'block';
			$('msg-box').fade({ duration: 5.0 });
			$('background').style.display = 'none';
			$('outter').style.display = 'none';
			$('inner').style.display = 'none';
		}
	});	
}

// AJAX CALL TO GET MY MESSAGES
function getMessages(page, messageId) {	
	
	// PASS VALUES TO HIDDEN FIELDS
	$('page-hidden').value = page;
	
	var url = 'ajax/get-messages.php?page=' + page + '&message-id=' + messageId;

	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			$('content-holder').innerHTML =  transport.responseText;	
		}
	});
}

// AJAX REQUEST TO UPDATE NEW MESSAGE COUNT
function updateNewMessageCount() {
	var url = 'ajax/check-new-messages.php';
	
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			$('login-action-holder').innerHTML = transport.responseText;
		}
	});
}

// REFRESH INBOX COUNT AT THE TOP AND MESSAGES PAGE
function refreshMessages() {
	var page = $('page-hidden').value;
	getMessages(page, 0);
	updateNewMessageCount();
}

// FUNCTION TO DELETE MESSAGES
function deleteMessage(messageId){
	var result = confirm("Are you sure you wish to delete this message?");
	
	if (result == true) {
		var url = 'ajax/delete-message.php?message-id=' + messageId;
		
		new Ajax.Request(url, {
			method: 'get',
			onSuccess: function(transport) {
				$('msg-box').innerHTML = transport.responseText;	
				$('msg-box').style.display = 'block';
				$('msg-box').fade({ duration: 5.0 });
				$('background').style.display = 'none';
				$('outter').style.display = 'none';
				$('inner').style.display = 'none';
				refreshMessages();
			}
		});	
	}
}

// AJAX CALL TO SAVE USER INFORMATION
function contactEmail() {
	var email = $('email').value;
	var msg = nicEditors.findEditor('message').getContent();

	// VALIDATE FIELDS
	if (validateContactInfo() == false) {
		return false;
	}

	var url = 'ajax/contact-us.php?email=' + email + '&msg=' + msg;
	
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(transport) {
			$('msg-box').innerHTML = transport.responseText;	
			$('msg-box').style.display = 'block';
			$('msg-box').fade({ duration: 5.0 }); return false;
		}
	});	
}
	