/// <reference path="jquery-1.3.2.js" />
///===================================
///=========  Globalistics :)   ======
///===================================
var myDays = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday");
var myMonths = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var PROFILE = "prof";
var pageIsLoaded = false;
var IDENTIFIER = "id";
var PRESISTANCEINDAYS = 7;
var GUID;
var USERNAME = '';
var ID = 0; // logged in user id
var POWER = 0;
var ActionAfterLogin = ""; //Track the last user action before showing Access Card
var ActionAfterLogOut = "";
var SomeOneElseOpenAccessCard;
var AJAXRequests = new Array();
var isIE = false;
var searchType = 0;
var isDetailPage = false;



//Login labels
var TypeName = "type your spot name here";
var TypeEmail = "type your email here";
var TypePassword = "type your password here";
var ConfirmPassword = "confirm password here";


var DetailPageType = 0; // 0 = normal, 1 = classifieds detail page.

var newCalendarDotjsIncluded = false;

function checkIE() {
	if (document.all) {
		isIE = true;
	} else {
		isIE = false;
	}
}
checkIE();

function dhtmlLoadScript(url) {
	var e = document.createElement("script");
	e.src = url;
	e.type = "text/javascript";
	document.getElementsByTagName("head")[0].appendChild(e);
}


function newAjaxRequest(requestRef, cancel) {
	if (cancel)
		cancelRequests();
	AJAXRequests = AJAXRequests.concat(requestRef);
}

function cancelRequests() {
	for (var requestCounter = 0; requestCounter < AJAXRequests.length; requestCounter++) {
		if (AJAXRequests[requestCounter] != null) {
			AJAXRequests[requestCounter].get_executor().abort();
		}
	}
	AJAXRequests = new Array();
}


function days_in_month(year, month) {
	var m = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
	if (month != 2)
		return m[month - 1];
	if (year % 4 != 0)
		return m[1];
	if (year % 100 == 0 && year % 400 != 0)
		return m[1];
	return m[1] + 1;
}

function addDays(DateToAdd, amountInDays) {
	return new Date(DateToAdd.valueOf() + 1000 * 60 * 60 * 24 * amountInDays);
}

function subtractDates(endDate, startDate) {
	var m = startDate.getMonth();
	var d = startDate.getDate();
	var y = startDate.getYear();

	var start = new Date(y, m, d);

	m = endDate.getMonth();
	d = endDate.getDate();
	y = endDate.getYear();

	var end = new Date(y, m, d);

	var date = new Date((end.valueOf() - (1000 * 60 * 60 * 24)) - start.valueOf());
	return date.getDate() + date.getMonth() * 30;
}



/// generic Show Hide Method
function showHide(targetName) {
	var elem = getItem(targetName);
	if (elem != null) {
		if (elem.style.display == 'block')
			elem.style.display = 'none';
		else
			elem.style.display = 'block';
	}
}
function show(targetName) {
	var elem = getItem(targetName);
	if (elem)
		elem.style.display = 'block';
}
function hide(targetName) {
	var elem = getItem(targetName);
	if (elem)
		elem.style.display = 'none';

}

/// generic create element
function createElement(tagName, id, styles, className) {
	var elem = document.createElement(tagName);
	elem.id = id;
	if (style != '')
		elem.setAttribute("style", styles);
	if (className != '')
		elem.className = className;
	return elem;
}

/// generic getItemBy ID
function getItem(targetName) {
	return document.getElementById(targetName);
}

/// generic change ClassName
function replaceStyle(targetName, newStyle) {
	var elem = getItem(targetName);
	if (elem)
		elem.className = newStyle;
}

// max length
function checkTextLength(textBoxName, maxLength) {
	elem = getItem(textBoxName);
	if (getItem(textBoxName).value.length > maxLength)
		getItem(textBoxName).value = getItem('feedBackBody').value.substring(0, maxLength - 1);
}


// cookie creation
function createCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		var expires = "; expires=" + date.toGMTString();
	}
	else var expires = "";
	document.cookie = name + "=" + value + expires + "; path=/";
}
// cookie read
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for (var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ')
			c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0)
			return c.substring(nameEQ.length, c.length);
	}
	return "";
}
// cookie destruction
function clearCookie(name) {
	createCookie(name, "", -1);
}

function CenterDiv(divToCenter, width) {
	var winH;
	var winW;
	var divToCenter = getItem(divToCenter);
	if (parseInt(navigator.appVersion) > 3) {
		if (navigator.appName == "Netscape") {
			winW = window.innerWidth;
			winH = window.innerHeight;
		}
		if (navigator.appName.indexOf("Microsoft") != -1) {
			winW = document.body.offsetWidth;
			winH = document.body.offsetHeight;
		}
	}
	if (divToCenter)
		divToCenter.style.left = winW / 2 - width / 2 + 'px';
}

function findFirstItemInArray(array, val) {
	for (ss = 0; ss < array.length; ss++) {
		if (array[ss] == val)
			return ss;
	}
	return -1;
}
function dimBackground(color) {
	if (color == 'White')
		replaceStyle('blocking', 'modalWg');
	else
		replaceStyle('blocking', 'modalBg');
	if (parseInt(navigator.appVersion) > 3) {
		winW = document.body.scrollWidth;
		winH = document.body.scrollHeight;
		//        if (navigator.appName == "Netscape") {
		//            winW = '100%';
		//            winH = document.height + 50;
		//        }
		if (navigator.appName.indexOf("Microsoft") != -1) {
			getItem('blocking').style.position = 'absolute';
			winW = document.body.scrollWidth;
			winH = document.body.scrollHeight;
		}
	}
	getItem('blocking').style.display = 'block';
	getItem('blocking').style.height = winH;
}

function unDimBackground() {
	replaceStyle('blocking', '');
	getItem('blocking').style.display = 'none';
}
///===================================
///===================================
//------------------------------------------------------//
// Classes which used in Requests (Maps Server classes) //
//------------------------------------------------------//

function Request() {
	this.RoomConfigs = new Array();
	this.SpecialRequest = "";
	this.StartDate = addDays(new Date(), 3);
	this.Duration = 7;
	this.OptionCode = new OptionCodeClass("");
	this.ItemId = -1;
	this.LocationId = -1;
	this.Price = new PriceRange(-1, -1);
	this.Stars = -1;
	this.InfoCode = "G";
	this.refiningOptions = new Array(); // array will be filled of refining option objects
	this.Type = "DB";
	this.subCategoryId = -1;
	this.Rand = Math.random();
	this.Extras = new Array();
	this.SearchKeyword = "";
}

//Added By Hassan
function formatStandardDate(sDate) // return date dd/mm/yyyy
{
	return sDate.getDate() + "/" + (sDate.getMonth() + 1) + "/" + sDate.getFullYear();
}

//Booking Classes Start
function Booking() {
	this.OnRequest = "B";
	this.Services = new Array();
	this.BookingId;
	this.Ref;
	this.Name;
	this.QB = "B";
	this.ServiceLineUpdateCount;
	this.CurrentService = new BookingService;
	this.AddService = _AddBookingService;
}
function _AddBookingService(_Service) {
	this.Services[this.Services.length] = _Service;
}
function BookingService() {
	this.DefaultRequest = new Request();
	this.ServiceLineId;
	this.SequenceNumber;
	this.Status;
	this.OptionId;
	this.DateFrom = new Date();
	this.RoomConfigs = new Array();
	this.Duration;
	this.OnRequest;
	this.ExtraQuantities = new Array();

}
function ExtraQuantityItem(_SequenceNumber, _ExtraQuantity) {
	this.SequenceNumber = _SequenceNumber;
	this.ExtraQuantity = _ExtraQuantity;
}

//Booking Classes End 

function roomConfig() {
	this.Adults = 0;
	this.RoomType; //TW,SG
	this.ChildAge1 = 0;
	this.ChildAge2 = 0;
	this.ChildAge3 = 0;
	this.PaxList = new Array();
	this.PaxCount = this.Adults + this.ChildAge1 + this.ChildAge2 + this.ChildAge3;
	this.Childrens = 0;
	this.Infants = 0;
}
function PaxDetails() {
	this.Title;
	this.Forename;
	this.Surname;
	this.DateOfBirth;
	this.PaxType;
}


function RefiningOption() {
	this.selectType = "SG"; // this can either be SG for single select of ML for multiselect
	this.singleValue = -1;
	this.allValues = new Array();
}

//updated by hassan on 30-1-2008
function Extra(sequence, mandatory, desc) {
	this.Sequance = sequence;
	this.IsPricePerson;
	this.IsMandatory = mandatory;
	if (desc != undefined)
		this.Description = desc;
}

function PriceRange(_From, _To) {
	this.From = _From;
	this.To = _To;
}
///===================================
///== Authentication & Access Card  ==
///===================================

/// this function requires access to Auth.asmx javascript proxy
function Authenticate() {
	var username = getItem('loginName').value;
	var pass = getItem('loginPassword').value;
	Auth.Authenticate(username, pass, GUID, OnAuthenticateComplete);
}

function resetPassword() {
	var username = getItem('loginName').value;
	Auth.ResetPassword(username, onResetPasswordComplete, OnResetPasswordError)
}

function OnResetPasswordError(result) {
	getItem("CardErrors").innerHTML = "Wrong email or email not exist."
}

function getCartName() {
	return "SpotCart";
}

function hoverTopRightButton() {
	getItem("iconSet").style.height = 'auto';
}

function collapseTopRightButton() {
	getItem("iconSet").style.height = '90px';
}

function onResetPasswordComplete(result) {
	if (result) {
		getItem("CardErrors").innerHTML = 'Please check your mail to reset your password';
		//alert('Your password has been changed, check your email inbox for the new password');
	}
	else {
		getItem("CardErrors").innerHTML = "This email doesn't exist.";
		//alert("This username doesn't exist.");
	}
}

function OnAuthenticateComplete(result, eventArgs) {
	if (result == 'error' || result == 'userNameUsed') {
		if (result == 'error')
		//showMessage("Sorry,wrong username or password.",1);
			getItem("CardErrors").innerHTML = "Sorry,wrong email or password.";
		if (result == 'userNameUsed')
		//showMessage("Sorry,userName Already in use.",1);
			getItem("CardErrors").innerHTML = "Sorry,email already in use.";
	} else {
		// cookies & bizkits
		USERNAME = result.split('|')[0];
		getItem('AccessCardLink').innerHTML = 'My Profile';
		if (result.split('|')[4].length > 0)
			getItem('imgHeaderUserLogo').src = '/images/Users/original/' + result.split('|')[4];
		else
			getItem('imgHeaderUserLogo').src = 'http://img.spotlocal.net/img/common/SignOut.gif';
		getItem('aHeaderMailLink').href = "/messaging.aspx";

		ID = result.split('|')[1];
		GUID = result.split('|')[2];
		POWER = result.split('|')[3];

		if (getItem('savePassword').checked) {
			createCookie(IDENTIFIER, result, PRESISTANCEINDAYS);
		}
		else {
			createCookie(IDENTIFIER, result);
		}

		//left for backward compatibiity
		clearCookie(PROFILE);

		// update UI
		replaceStyle('ulHeaderRightCol', 'SignIn');
		clearPane('login');
		clearPane('new');

		getItem('savePassword').checked = false;

		closeAccessCard();

		// post login event

		if (ActionAfterLogin != "") {
			eval(ActionAfterLogin);
			ActionAfterLogin = "";
		}
		getItem("CardErrors").innerHTML = "";

		Messaging.getMessageCounts(ID, GUID, false, false, true, OnUserGetMessageCountsComplete);
	}
}

function OnUserGetMessageCountsComplete(result, eventArgs) {
	var arriMessageCounts = result;
	if (arriMessageCounts[2] != -1) {// inbox new count
		newMessagesCount = arriMessageCounts[2];
		if (newMessagesCount != 0) {
			getItem("spanHeaderMailBox").innerHTML = newMessagesCount + ' Message(s)';
			getItem('imgHeaderMessage').src = 'http://img.spotlocal.net/img/common/NewMessage.gif';
		}
		else {
			getItem("spanHeaderMailBox").innerHTML = 'MailBox';
			getItem('imgHeaderMessage').src = 'http://img.spotlocal.net/img/common/loggedMessage.gif';
		}
	}
}



function newUser() {
	Auth.createUser(GUID, getItem('newemail').value, getItem('newname').value, getItem('newpassword1').value, OnAuthenticateComplete);
}

function logOut() {
	GUID = '';
	USERNAME = '';
	ID = 0;
	clearCookie(IDENTIFIER);

	//left for backward compatibility
	clearCookie(PROFILE);

	checkProfile();
	getItem('AccessCardLink').innerHTML = 'Login/Register';
	getItem('imgHeaderUserLogo').src = 'http://img.spotlocal.net/img/common/SignOut.gif';
	getItem("spanHeaderMailBox").innerHTML = 'MailBox';
	getItem('imgHeaderMessage').src = 'http://img.spotlocal.net/img/common/MailBox2.gif';
	getItem('aHeaderMailLink').href = "javascript:ShowAccessCardAndGotoMessaging();";
	closeAccessCardLoggedIn();
	ActionAfterLogOut = "validateUserLogout()";
	eval(ActionAfterLogOut);
	ActionAfterLogOut = "";
	replaceStyle('ulHeaderRightCol', '');
}

//This function will lead to home page incase the user logged out and he was in his profile page.
function validateUserLogout() {
	if (document.URL.indexOf('userprofile.aspx') > 0)
		location.href = 'default.aspx';
}
/// this is the first function in profiling the user
/// it should be woking as soon as the page completes loading
function checkProfile() {
	var userInCookie = readCookie(IDENTIFIER);
	if (userInCookie == null || userInCookie == '') {
		openTab('bsfinder');
		Auth.getNewProfileGuid(newProfileCookieComplete);
	} else {
		GUID = userInCookie.split('|')[2];
		Auth.refreshProfileGuid(GUID);
		if (userInCookie.split("|")[0] != '') {
			USERNAME = userInCookie.split('|')[0];
			getItem('AccessCardLink').innerHTML = USERNAME;
			replaceStyle('ulHeaderRightCol', 'SignIn');
			ID = userInCookie.split('|')[1];
			POWER = userInCookie.split('|')[3];
		}
	}

}

function newProfileCookieComplete(result, eventArgs) {
	//left for backward compatibility 
	clearCookie(PROFILE);
	createCookie(IDENTIFIER, "||" + result, PRESISTANCEINDAYS);
	createCookie()
	GUID = result;
}



function showAccessCard() {
	if (ID == 0) {
		var accessCard = getItem('accesscard');
		if (accessCard == null)
			return;
		//CenterDiv('accesscard', 407);
	} else {
		var accessCard = getItem('accesscardLoggedIn');
		if (accessCard == null)
			return;
		getBasicInfo(ID);
		//CenterDiv('accesscardLoggedIn', 407);
	}
	dimBackground();
	accessCard.style.display = 'block';
	accessCard.style.zIndex = 20001;
	accessCard.style.top = '150px';
	//accessCard.style.position='fixed';
}



function closeAccessCard() {
	unDimBackground();
	getItem('accesscard').style.display = 'none';
}

function closeAccessCardLoggedIn() {
	unDimBackground();
	getItem('accesscardLoggedIn').style.display = 'none';

}

function pressEnterAccessCardOut(key) {
	if (key.keyCode == 13) {
		loginRegister();
		return false;
	} else {
		return true;
	}
}



/// all you have to do is to hook the event change to it

//added by Ramy to validate text fields
var isValid = true;
function ShowError(img, prop) {
	var errImg = getItem(img);
	errImg.style.display = prop;
}

function ValidateEmpty(elmId) {
	var txt = getItem(elmId).value;
	if (txt.length == 0) {
		ShowError("err" + elmId, "block");
		isValid = false;
	} else {
		ShowError("err" + elmId, "none");
	}
	return txt;
}

function GetValidNumber(elmId) {
	var txt = getItem(elmId).value;
	if (ValidateNumberUI(elmId, "err" + elmId))
		isValid = false;
	return txt;
}

function ValidateNumberUI(textBoxToValidate, imgToshow) {
	if (ValidateNumber(textBoxToValidate)) {
		ShowError(imgToshow, "none");
		return true;
	} else {
		ShowError(imgToshow, "block");
		return false;
	}
}

function ValidateNumber(elmId) {
	var txt = getItem(elmId).value;
	if (txt.length == 0 || isNaN(txt)) {
		return false;
	} else {
		return true;
	}
}

function ValidateLength(elmId, len) {
	var txt = getItem(elmId).value;
	if (txt.length > 0 && txt.length <= len) {
		ShowError("err" + elmId, "none");
	} else {
		isValid = false;
		ShowError("err" + elmId, "block");
	}
	return txt;
}

function GetValidEmail(elmId) {
	if (!validateEmail(elmId)) {
		ShowError("err" + elmId, "block");
		isValid = false;
	} else {
		ShowError("err" + elmId, "none");
	}
	return getItem(elmId).value;
}

function validateEmptyUI(textBoxToValidate, imgToshow) {
	if (validateEmpty(textBoxToValidate)) {
		getItem(imgToshow).style.display = 'none';
		return true;
	} else {
		getItem(imgToshow).style.display = 'block';
		return false;
	}
}
function validateEmpty(textBoxToValidate) {
	if (getItem(textBoxToValidate).value == '') {
		return false;

	} else {
		return true;
	}
}

function validateCompareUI(textBoxToValidate, textBoxToCompare, imgToShow) {
	if (validateCompare(textBoxToCompare, textBoxToValidate)) {
		getItem(imgToShow).style.display = 'none';
		return true;
	} else {
		getItem(imgToShow).style.display = 'block';
		return false;
	}
}

function validateCompare(textBoxToValidate, textBoxToCompare) {
	if (getItem(textBoxToValidate).value == getItem(textBoxToCompare).value) {
		return true;
	} else {
		return false;
	}
}

function validateEmailUI(textBoxToValidate, imgToShow) {
	if (validateEmail(textBoxToValidate)) {
		getItem(imgToshow).style.display = 'none';
		return true;
	} else {
		getItem(imgToshow).style.display = 'block';
		return false;
	}
}

function validateEmail(textBoxToValidate) {
	var emailValue = document.getElementById(textBoxToValidate).value;
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z]{2,4})+$/;
	if (filter.test(emailValue)) {
		return true;
	}
	else {
		return false;
	}
}
function validateDate(textBoxToValidate) {
	var strValue = document.getElementById(textBoxToValidate).value;
	var objRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
	//check to see if in correct format
	if (!objRegExp.test(strValue))
		return false; //doesn't match pattern, bad date
	else {
		var strSeparator = strValue.substring(2, 3);
		var arrayDate = strValue.split(strSeparator);
		//create a lookup for months not equal to Feb.
		var arrayLookup = { '01': 31, '03': 31, '04': 30, '05': 31, '06': 30, '07': 31,
			'08': 31, '09': 30, '10': 31, '11': 30, '12': 31
		}
		var intDay = parseInt(arrayDate[0], 10);

		//check if month value and day value agree
		if (arrayLookup[arrayDate[1]] != null) {
			if (intDay <= arrayLookup[arrayDate[1]] && intDay != 0)
				return true; //found in lookup table, good date
		}

		//check for February (bugfix 20050322)
		var intMonth = parseInt(arrayDate[1], 10);
		if (intMonth == 2) {
			var intYear = parseInt(arrayDate[2]);
			if (intDay > 0 && intDay < 29)
				return true;
			else if (intDay == 29) {
				if ((intYear % 4 == 0) && (intYear % 100 != 0) || (intYear % 400 == 0)) {// year div by 4 and ((not div by 100) or div by 400) ->ok
					return true;
				}
			}
		}
	}
	return false; //any other values, bad date
}

function validatePhone(textBoxToValidate) {
	var txt = getItem(textBoxToValidate).value;
	if (txt.length == 0 || isNaN(txt))
		return false;
	else
		return true;
}

//updated by hassan
// which is new or login 
function clearPane(which, caller) {
	if (which == 'new') {

		if (getItem('newname').value != TypeName)
			getItem('newname').value = TypeName;

		if (getItem('newemail').value != TypeEmail)
			getItem('newemail').value = TypeEmail;


		if (getItem('newpassword1').value != TypePassword) {
			changeInputType(getItem('newpassword1'), 'text');
			//getItem('newpassword1').type = "text";
			getItem('newpassword1').value = TypePassword;
		}


		if (getItem('newpassword2').value != ConfirmPassword) {
			changeInputType(getItem('newpassword2'), 'text');
			//getItem('newpassword2').type = "text";
			getItem('newpassword2').value = ConfirmPassword;
		}

	} else {

		if (getItem('loginName').value != TypeEmail)
			getItem('loginName').value = TypeEmail;


		if (getItem('loginPassword').value != TypePassword) {
			changeInputType(getItem('loginPassword'), 'text');
			//getItem('loginPassword').type = "text";
			getItem('loginPassword').value = TypePassword;
		}
	}

	if (caller != null)
		prepareControlForWriting(caller);
}
//added by hassan
function prepareControlForWriting(caller) {
	if (caller.id == 'loginName' && caller.value == TypeEmail)
	{ caller.value = ""; return }

	if (caller.id == 'loginPassword' && caller.value == TypePassword)
	{ caller.value = ""; changeInputType(caller, 'password'); return }

	if (caller.id == 'loginName' && caller.value == TypeEmail)
	{ caller.value = ""; changeInputType(caller, 'password'); return }

	if (caller.id == 'newname' && caller.value == TypeName)
	{ caller.value = ""; return }

	if (caller.id == 'newemail' && caller.value == TypeEmail)
	{ caller.value = ""; return }

	if (caller.id == 'newpassword1' && caller.value == TypePassword) {
		caller.value = "";
		changeInputType(caller, 'password');
		return
	}

	if (caller.id == 'newpassword2' && caller.value == ConfirmPassword) {
		caller.value = "";
		changeInputType(caller, 'password');
		return
	}

}
//added by hassan
function setDefaultValue(caller, value) {
	if (caller.value == "") {
		caller.value = value;
		if (caller.type == "password")
			changeInputType(caller, 'text');
	}
}

//Added By Amr ElGarhy 29 Jan 2008.
function changeInputType(oldObject, oType) {
	try {
		//For all browsers.
		oldObject.type = oType;
	}
	catch (error) {
		//alert(error.message);
		//For IE.
		var newObject = document.createElement('input');
		newObject.type = oType;
		if (oldObject.size) newObject.size = oldObject.size;
		if (oldObject.value) newObject.value = oldObject.value;
		if (oldObject.name) newObject.name = oldObject.name;
		if (oldObject.id) newObject.id = oldObject.id;
		if (oldObject.className) newObject.className = oldObject.className;
		newObject.onfocus = oldObject.onfocus;
		newObject.onblur = oldObject.onblur;
		newObject.onkeydown = oldObject.onkeydown;
		oldObject.parentNode.replaceChild(newObject, oldObject);
		return newObject;
	}
}
//added by hassan
//login card (or) new user card
function validateCardData(which) {
	if (which == 'login')//validate member login
	{
		if (!EmptyField('loginName', TypeEmail) && !EmptyField('loginPassword', TypePassword)) {
			getItem("CardErrors").innerHTML = "";
			return true;
		}

		else if (!EmptyField('loginName', TypeEmail) && EmptyField('loginPassword', TypePassword)) {
			getItem("CardErrors").innerHTML = "Please Type your password.";
			return false;
		}
		else if (EmptyField('loginName', TypeEmail) && !EmptyField('loginPassword', TypePassword)) {
			getItem("CardErrors").innerHTML = "please type your email.";
			return false;
		}
	}

	else {
		if (!EmptyField('newname', TypeName) && ExactValue('newpassword1', 'newpassword2') && validateEmail('newemail')) //Validate new user
		{
			getItem("CardErrors").innerHTML = "";
			return true;
		}
		else if (EmptyField('newname', TypeName)) {
			getItem("CardErrors").innerHTML = "please type your username.";
			return false;
		}
		else if (EmptyField('newemail', TypeEmail)) {
			getItem("CardErrors").innerHTML = "please type your email.";
			return false;
		}
		else if (!validateEmail('newemail')) {
			getItem("CardErrors").innerHTML = "Error in your email.";
			return false;
		}
		else if (EmptyField('newpassword1', TypePassword)) {
			getItem("CardErrors").innerHTML = "Please Type your password.";
			return false;
		}
		else if (EmptyField('newpassword2', ConfirmPassword)) {
			getItem("CardErrors").innerHTML = "Please confirm your password.";
			return false;
		}
		else if (!ExactValue('newpassword1', 'newpassword2')) {
			getItem("CardErrors").innerHTML = "Your password is not matched.";
			return false;
		}
	}
}
//added by hassan
function EmptyField(FieldName, ExtraCompare) {
	if (getItem(FieldName).value == "")
		return true;
	if (ExtraCompare != "" && getItem(FieldName).value == ExtraCompare)
		return true;

	return false;
}
//added by hassan
function ExactValue(Field1, Field2) {
	if (getItem(Field1).value == getItem(Field2).value)
		return true;

	return false;
}
//updated by hassan
function loginRegister() {

	if (validateCardData('new')) {
		newUser();
	}
	else if (validateCardData('login')) {
		Authenticate();
	}
}

var BasicInformationUserIds = new Array();
var BasicInformationData = new Array();
function getBasicInfo(userId) {
	window.scroll(0, 0);

	if (findFirstItemInArray(BasicInformationUserIds, userId) == -1)
		Auth.getBasicUserInfo(userId, getBasicInfoComplete);
	else {

		updateAccessCardwithInfo(BasicInformationData[findFirstItemInArray(BasicInformationUserIds, userId)]);
	}
	//if(SomeOneElseOpenAccessCard)
	Auth.GetUserImage(userId, onGetSomeOneElseImageComplete, onGetImageError);
}


function getBasicInfoComplete(result, eventArgs) {
	if (result != "error") {
		BasicInformationUserIds = BasicInformationUserIds.concat(result.split("|")[0]);
		BasicInformationData = BasicInformationData.concat(result);
		updateAccessCardwithInfo(result);
		if (ID > 0)
			Auth.GetUserImage(ID, onGetImageComplete, onGetImageError);

	}
}

function showSomeoneElsesAccessCard() {
	var accessCard = getItem('accessCardSomeoneElse');
	//CenterDiv('accessCardSomeoneElse',408);
	dimBackground();
	accessCard.style.display = 'block';
	//accessCard.style.zIndex=20002;
	//accessCard.style.top='100px';
}

function hideSomeoneElsesAccessCard() {
	unDimBackground();
	getItem('accessCardSomeoneElse').style.display = 'none';
}

var prefix;
function updateAccessCardwithInfo(dataToUptdate) {

	if (dataToUptdate.split("|")[0] == ID) {
		prefix = "L";
	} else {
		showSomeoneElsesAccessCard();
		prefix = "E";
		getItem("MessageToReadOnly").innerHTML = dataToUptdate.split('|')[1];
	}
	getItem(prefix + "name").innerHTML = dataToUptdate.split('|')[1];
	//<!--	getItem(prefix + "img").src="Images/Users/small/" + dataToUptdate.split('|')[0] + ".jpg" -->
	//getItem(prefix + "img").src="http://img.spotlocal.net/img/accesscard/photo_bg.gif";
	//Auth.GetUserImage(ID, onGetImageComplete,onGetImageError);
	if (getItem(prefix + "visit") != null)
		getItem(prefix + "visit").innerHTML = dataToUptdate.split('|')[2];
	getItem(prefix + "who").innerHTML = dataToUptdate.split('|')[3];
	getItem(prefix + "nation").innerHTML = dataToUptdate.split('|')[4];
	replaceStyle(prefix + "power", "power" + dataToUptdate.split('|')[5]);
	getItem(prefix + "age").innerHTML = dataToUptdate.split('|')[6];
	getItem(prefix + "gender").innerHTML = dataToUptdate.split('|')[7];
	SomeOneElseOpenAccessCard = dataToUptdate.split('|')[0];
	if (getItem('SomeOneElseProfileLink'))
		getItem('SomeOneElseProfileLink').href = '/userprofilepreview.aspx?id=' + SomeOneElseOpenAccessCard;
}

function onGetSomeOneElseImageComplete(result) {
	if (getItem("Eimg"))
	//if(getItem("Eimg").src.indexOf(".jpg")==-1)
		getItem("Eimg").src = result;
}

function onGetImageComplete(result) {
	if (getItem("Limg"))
		if (getItem("Limg").src.indexOf(".jpg") == -1)
		getItem("Limg").src = result;
	//    if(getItem('UserProfileImageEdit'))
	//        getItem('UserProfileImageEdit').src = result;

}

function onGetImageError(result) {
	getItem(prefix + "img").src = 'http://img.spotlocal.net/img/accesscard/photo_bg.gif';
}

///===================================
///===================================

///===================================
///============ Messaging ============  
///===================================

function openAMessage() {
	getItem('WriteMeLink').style.display = 'none';
	getItem('messageLine').style.display = 'block';
	getItem('messageWindow').style.display = 'block';
}

function closeMessageReplyWindow() {
	getItem('WriteMeLink').style.display = '';
	getItem('messageLine').style.display = 'none';
	getItem('messageWindow').style.display = 'none';
}

//updated by mhassan 27-1-2008
function sendMessage() {
	if (getItem('MessageBody').value.length > 0) {
		Messaging.SendMessage(ID, SomeOneElseOpenAccessCard, getItem('MessageSubject').value, getItem('MessageBody').value, GUID);
		//Messaging.SendMessage(ID,SomeOneElseOpenAccessCard,"",getItem('MessageBody').value,GUID);
		closeMessageReplyWindow();
		hideSomeoneElsesAccessCard();
		SomeOneElseOpenAccessCard = "";
		showMessage("Your message to " + getItem('MessageToReadOnly').innerHTML + " was sent succesfully.", 2);
		getItem('MessageSubject').value = "";
		getItem('MessageBody').value = "";
		getItem('MessageToReadOnly').innerHTML = "";
		if (document.URL.toLowerCase().indexOf('messaging.aspx') > -1) {//the user is sending the message from the messaging system, so update the count of hte outbox and the pager of the outbox messages if the current selected view is outbox
			sentCount++;
			getItem("SentMessageCount").innerHTML = sentCount + "<span>message(s)</span>"; ;
			if (!isInbox) {
				numOfMessages = sentCount;
				drawPaging();
				setTimeout("loadMessagesPage(pageNumber);", 500);
			}
		}
	}
	else
		showMessage("Message is empty,please enter message body.", 2);
}

function showWriteMessage(userId) {
	window.scroll(0, 0);
	if (ID == 0) {
		ActionAfterLogin = "getBasicInfo(" + userId + ");NewMessage();"
		showAccessCard();
	}
	else {
		getBasicInfo(userId);
		NewMessage();
	}
	SomeOneElseOpenAccessCard = userId;
}

function NewMessage() {
	if (ID != 0) {
		openAMessage();
	} else {
		hideSomeoneElsesAccessCard();
		ActionAfterLogin = "getBasicInfo(SomeOneElseOpenAccessCard);NewMessage();";
		showAccessCard();
	}
}
///===================================
///===================================





///===================================
///====Drop Down List Functions ======
///===================================

/// open Or Close Drop DownList Based on state
function openCloseDropDown(DropDown) {
	var EXPANDED_CLASS_NAME = "col-act";
	var COLLAPSED_CLASS_NAME = "col";
	var elem = getItem(DropDown + "_list");
	if (elem.style.display == 'none') {
		replaceStyle(DropDown + "_result", EXPANDED_CLASS_NAME);
		eval("tmpvar =" + DropDown + "_functionToExecuteOnClick");
		if (tmpvar != -1) {
			eval(tmpvar);
		}
	} else {
		replaceStyle(DropDown + "_result", COLLAPSED_CLASS_NAME);
	}
	showHide(DropDown + "_list");
}



/// intialize a specific drop downlist
function populateDropDown(targetName, all) {
	var elem = getItem(targetName + "_itemsMarker");
	var selectedIdeces = eval(targetName + "_SelectedIndeces");
	elem.innerHTML = "";
	var TextArray = eval(targetName + "_arrayText");
	var ValueArray = eval(targetName + "_arrayValue");
	var SelectedIndex = eval(targetName + "_SelectedIndex");
	var isMultiSelect = eval(targetName + "_isMultiSelect");
	for (i = 0; i < TextArray.length; i++) {
		if (!isMultiSelect) {
			if (SelectedIndex != i)
				elem.innerHTML += "<p id=\"" + targetName + "_Item_" + i + "\"><a href=\'javascript:doDropDownSelection(\"" + targetName + "_Item_" + i + "\",true);\'>" + TextArray[i] + "</a></p>";
			else
				elem.innerHTML += "<p id=\"" + targetName + "_Item_" + i + "\" class=\"act\"><a href=\'javascript:doDropDownSelection(\"" + targetName + "_Item_" + i + "\",true);\'>" + TextArray[i] + "</a></p>";
		}
		else {
			if (findFirstItemInArray(selectedIdeces, i) < 0)
				elem.innerHTML += "<p id=\"" + targetName + "_Item_" + i + "\"><a href=\'javascript:doDropDownSelection(\"" + targetName + "_Item_" + i + "\",false);\'>" + TextArray[i] + "</a></p>";
			else
				elem.innerHTML += "<p id=\"" + targetName + "_Item_" + i + "\" class=\"act\"><a href=\'javascript:doDropDownSelection(\"" + targetName + "_Item_" + i + "\",false);\'>" + TextArray[i] + "</a></p>";
		}
	}
	if (all == "True") {
		elem.innerHTML += "<p id=\"" + targetName + "_Item_00\"><a href=\'javascript:doDropDownSelection(\"" + targetName + "_Item_00\",true);\'>All</a></p>";
	}
}

function populateDropDown2(targetName) {
	var elem = getItem(targetName + "_itemsMarker");
	var selectedIdeces = eval(targetName + "_SelectedIndeces");
	elem.innerHTML = "";
	var TextArray = eval(targetName + "_arrayText");
	var ValueArray = eval(targetName + "_arrayValue");
	var SelectedIndex = eval(targetName + "_SelectedIndex");
	var isMultiSelect = eval(targetName + "_isMultiSelect");

	for (i = 0; i < TextArray.length; i++) {
		if (findFirstItemInArray(selectedIdeces, i) < 0)
			elem.innerHTML += "<p id=\"" + targetName + "_Item_" + i + "\"><a href=\'javascript:doDropDownSelection(\"" + targetName + "_Item_" + i + "\",false);\'>" + TextArray[i] + "</a></p>";
		else
			elem.innerHTML += "<p id=\"" + targetName + "_Item_" + i + "\" class=\"act\"><a href=\'javascript:doDropDownSelection(\"" + targetName + "_Item_" + i + "\",false);\'>" + TextArray[i] + "</a></p>";
	}
}

///Do a selection in a dropdownlist
function doDropDownSelection(DropDownNewItemID, andClose) {
	var targetName = DropDownNewItemID.split("_")[0];
	var OldItem = eval(targetName + "_SelectedIndex");
	var TextArray = eval(targetName + "_arrayText");
	var selectedIdeces = eval(targetName + "_SelectedIndeces");
	var isMultiSelect = eval(targetName + "_isMultiSelect");
	var str = targetName + "_SelectedIndex = " + DropDownNewItemID.split("_")[2];
	eval(str);


	// the all case
	if (DropDownNewItemID.split("_")[2] == "00") {
		if (isMultiSelect)
			eval(targetName + "_SelectedIndeces=new Array();");
		else
			eval(targetName + "_SelectedIndex=-1;");
		getItem(targetName + "_selectedText").innerHTML = "All";
		if (andClose)
			openCloseDropDown(targetName);
		fireDoropDownCompleteEvent(targetName);
		if (OldItem != -1 && OldItem != -2) {
			replaceStyle(targetName + "_Item_" + OldItem, "");
		} else {
			if (OldItem == -2) {
				replaceStyle(targetName + "_Item_" + OldItem, "else");
			}
		}

		return;
	}


	if (OldItem != -1 && OldItem != -2) {
		replaceStyle(targetName + "_Item_" + OldItem, "");
	} else {
		if (OldItem == -2) {
			replaceStyle(targetName + "_Item_" + OldItem, "else");
		}
	}


	if (isMultiSelect) {
		index = findFirstItemInArray(selectedIdeces, DropDownNewItemID.split("_")[2]);
		var multiSelectStr;
		if (index < 0) {
			multiSelectStr = targetName + "_SelectedIndeces =" + targetName + "_SelectedIndeces.concat(" + DropDownNewItemID.split("_")[2] + ")";
			eval(multiSelectStr);
			populateDropDown(targetName);
		}
		else {
			multiSelectStr = targetName + "_SelectedIndeces.splice(" + index + ", 1)";
			eval(multiSelectStr);
			populateDropDown2(targetName);
		}
		var strVals = "";
		selectedIdeces = eval(targetName + "_SelectedIndeces");
		for (x = 0; x < selectedIdeces.length; x++) {
			strVals += TextArray[selectedIdeces[x]] + ", ";
		}
		x = String();
		strVals[strVals.length - 2] = '';
		strVals[strVals.length - 1] = '';
		getItem(targetName + "_selectedText").innerHTML = strVals;
		fireDoropDownCompleteEvent(targetName);
		return;
	}
	if (DropDownNewItemID.split("_")[2] != -2) {
		replaceStyle(targetName + "_Item_" + DropDownNewItemID.split("_")[2], "act");
		getItem(targetName + "_selectedText").innerHTML = getSelectedtextDropDownList(targetName);
	} else {
		replaceStyle(targetName + "_Item_" + DropDownNewItemID.split("_")[2], "else-act");
		getItem(targetName + "_selectedText").innerHTML = "";
	}

	if (andClose)
		openCloseDropDown(targetName);
	fireDoropDownCompleteEvent(targetName);
}
/// get selected Index 
function getSelectedIndexDropDownList(dropDownList) {
	try {
		return eval(dropDownList + "_SelectedIndex");
	} catch (ex) {
		//alert(ex.description);
		//alert(dropDownList + "_SelectedIndex");
		return -2;
	}
}

/// get selected text 
function getSelectedtextDropDownList(dropDownList) {
	var selectedIndex = getSelectedIndexDropDownList(dropDownList);
	return eval(dropDownList + "_arrayText" + "[" + selectedIndex + "]");
}


/// get selected Value 
function getSelectedValueDropDownList(dropDownList) {
	var selectedIndex = getSelectedIndexDropDownList(dropDownList);
	if (selectedIndex != -2) {
		return eval(dropDownList + "_arrayValue" + "[" + selectedIndex + "]");
	}
	else {
		return getItem(dropDownList + "_selectedText").innerHTML;
	}
}

function updateDropDownOther(DropDownListName) {
	var textBox = getItem(DropDownListName + "_OtherText");
	if (textBox.value != "") {
		if (!isNaN(textBox.value)) {
			if (textBox.value > 30)
				textBox.value = 30;
			eval(DropDownListName + "_SelectedIndex=-2")
			getItem(DropDownListName + "_selectedText").innerHTML = textBox.value;
			openCloseDropDown(DropDownListName);
		}
	}
}

function fireDoropDownCompleteEvent(DropDownListName) {
	var functionName;
	functionName = DropDownListName + "_functionToExecute";
	var SelectedValue = getSelectedValueDropDownList(DropDownListName);
	functionName = eval(functionName);
	if (functionName != -1) {
		eval(functionName + "('" + SelectedValue + "');");
	}
}

/// =======  this section is for global collapse ========
var DropDowns = new Array();
function registerDropDownControl(DropDownName) {
	DropDowns = DropDowns.concat(DropDownName);
}

function CloseAllDropDowns() {
	var COLLAPSED_CLASS_NAME = "col";
	var x = DropDowns.length;
	for (i = 0; i < DropDowns.length; i++) {
		replaceStyle(DropDowns[i] + "_result", COLLAPSED_CLASS_NAME);
		getItem(DropDowns[i] + "_list").style.display = 'none';
	}
}


///===================================
///===============Baloons=============
///===================================

var BaloonTypes = new Array("baloon-loading", "baloon-error", "baloon-success", "baloon-info", "baloon-question");
function showMessage(messageText, baloonType, batoonText, eventClose, eventYes, topPixels) {
	//replaceStyle('baloonHolder', BaloonTypes[baloonType]);
	if (BaloonTypes[baloonType] == "baloon-loading" || BaloonTypes[baloonType] == "baloon-info" || BaloonTypes[baloonType] == "baloon-question") {
		replaceStyle('messageType', 'PleaseNoteDiv');
		getItem('messageTitle').innerHTML = 'please note!';
	}
	else if (BaloonTypes[baloonType] == "baloon-error") {
		replaceStyle('messageType', 'ErrorOccuredDiv');
		getItem('messageTitle').innerHTML = 'error occured!';
	}
	else if (BaloonTypes[baloonType] == "baloon-success") {
		replaceStyle('messageType', 'approvedDiv');
		getItem('messageTitle').innerHTML = 'approved!';
	}

	if (batoonText)
		getItem('messageTitle').innerHTML = batoonText;

	var balloon = getItem('baloonHolder');
	var messageArea = getItem('baloonText');
	if (messageArea)
		messageArea.innerHTML = messageText;
	if (!balloon)
		return;
	//CenterDiv('baloonHolder', 204);
	//    if (!topPixels) {
	if (balloon)
		balloon.style.top = '300px';
	//    }
	//    else {
	//        if (balloon)
	//            balloon.style.top = topPixels + ('px'); //balloon.style.top=  topPixels + ('px'*2); //Edited By Amr ElGarhy 2 Dec 2007
	//    }
	balloon.style.display = 'block';
	balloon.style.zIndex = 120000;
	if (baloonType == 0) {
		getItem('baloonClose').style.display = 'none';
	}
	else {
		getItem('baloonClose').style.display = 'block';
	}
	if (baloonType == 4) {
		//getItem('baloonClose').style.display = 'none';
		//messageArea.innerHTML += "<a href=\"javascript:" + eventYes + "\">yes</a><a href=\"javascript:" + eventClose + "\">no</a>";
		if (eventClose == "")
			eventClose = 'closeBaloon()';
		//messageArea.innerHTML = messageText + "<p class='YesAndNo' id='baloonButtons'><a href=\"javascript:" + eventClose + "\">no</a><a href=\"javascript:" + eventYes + "\">yes</a></p>";
		getItem('baloonButtons').innerHTML = "<a href=\"javascript:" + eventClose + "\">no</a><a href=\"javascript:" + eventYes + "\">yes</a>";
		getItem('baloonButtons').style.display = 'block';
	}
	else {
		getItem('baloonClose').style.display = 'block';
	}
	if (eventClose && eventClose.length > 0) {
		getItem('baloonClose').href = "javascript:" + "closeBaloon();" + eventClose;
	}
	dimBackground('White');
}


function closeBaloon() {
	var balloon = getItem('baloonHolder');
	balloon.style.display = 'none';
	unDimBackground();
}

///===================================
///===================================
var SEARCH_BOX_MESSAGE = "search directory";
function startSearch(boxName) {
	if (getItem(boxName)) {
		if (getItem(boxName).value != '' && getItem(boxName).value != SEARCH_BOX_MESSAGE) {
			//Added By Amr ElGarhy 15 Jun 2008
			location.href = "/directory.aspx?Term=" + trimAll(getItem(boxName).value);
		} else {
			getItem(boxName).value = SEARCH_BOX_MESSAGE;
		}
	}
}

// Added by Amr ElGarhy 19 Seb 2007
function trimAll(sString) {
	//	while (sString.substring(0, 1) == ' ') {
	//		sString = sString.substring(1, sString.length);
	//	}
	//	while (sString.substring(sString.length - 1, sString.length) == ' ') {
	//		sString = sString.substring(0, sString.length - 1);
	//	}
	sString = sString.replace(/\s+/g, '+');
	return sString;
}

function clearBoxOnFocus(boxName, mess) {
	if (getItem(boxName).value == mess) {
		getItem(boxName).value = '';
	}
}

function searchEnter(key, boxname) {
	if (key.keyCode == 13) {
		setTimeout("startSearch('" + boxname + "')", 500);
		//startSearch(boxname);
		return false;
	} else {
		return true;
	}
}

function setSearchWord(boxName, word) {
	getItem(boxName).value = word;
}
function searchWithTerm(anchorObj) {
	//Added By Amr ElGarhy 15 Jun 2008
	if (searchType == 1)
		location.href = "/classifieds.aspx?Term=" + trimAll(getItem(boxName).value);
	else if (searchType == 0)
		location.href = "directory.aspx?Term=" + anchorObj;
	else if (searchType == 2)
		location.href = "/members.aspx?Term=" + trimAll(getItem(boxName).value);
}

function testUnload() {
	alert("Unload");
}
function PageOnloadEvent() {
	pageIsLoaded = true;


	if (document.getElementById('readerpublishermodule0')) {
		// Grab the appropriate div
		theDiv = document.getElementById('readerpublishermodule0');
		// Grab all of the links inside the div
		links = theDiv.getElementsByTagName('a');
		// Loop through those links and attach the target attribute
		for (var i = 0, len = links.length; i < len; i++) {
			// the _blank will make the link open in new window
			links[i].setAttribute('target', '_blank');
		}
	}

	//checkProfile();//removed by Karim and implemented server side
	if (document.URL.toLowerCase().indexOf('/messaging.aspx') > -1) {
		initializeMessages();
	}
	else if (isDetailPage) {
		SetUserCommentsInfo();
	}

	else if (document.URL.toLowerCase().indexOf('/classifieds.aspx') > -1) {
		loadClassifiedsPage(); // This function exit in classifieds.js
	}

	else if (document.URL.toLowerCase().indexOf('/directory.aspx') > -1) {
		loadDirectoryPage(); // This function exit in classifieds.js
	}

	//Added By Mhassan
	if (document.URL.toLowerCase().indexOf('/subject.aspx') > -1) {
		UpdateUI();
	}
	else if (document.URL.toLowerCase().indexOf('/details.aspx') > -1) {
		UpdateUIDetails();
	}
	else if (isDetailPage) {
		UpdateUIDetails();
	}

	else if (document.URL.toLowerCase().indexOf('/cdetails.aspx') > -1) {
		UpdateUIDetails();
	}
	else if (document.URL.toLowerCase().indexOf('/userprofile.aspx') > -1) {
		if (document.URL.indexOf('add') > 0) {
			openProfileTab(2);
			$get('AddClassified').style.display = '';
			$get('MyClassifieds').style.display = 'none';
		}
		else if (document.URL.indexOf('edit') > 0) {
			openProfileTab(2);
			qs = document.URL.substr(document.URL.indexOf("edit=") + 5);
			LoadAdData(qs);
			OpenForEditClassified();
		}
		if (document.URL.indexOf('tab=Mybusiness') > 0) {
			openProfileTab(4);
		}
		if (document.URL.indexOf('tab=AddBusiness') > 0) {
			openProfileTab(4);
			$get('AddDirectory').style.display = '';
			$get('MyDirectories').style.display = 'none';
		}
	}
	else if (document.URL.indexOf('friends') > 0) {
		openProfileTab(3);
	}


	if (getItem('openCloseFooterLinkRedSea'))
		LoadFooter('openCloseFooterLinkRedSea', 'divFooterContentRedSea');
	else if (getItem('openCloseFooterLinkDubai'))
		LoadFooter('openCloseFooterLinkDubai', 'divFooterContentDubai');
	else if (getItem('openCloseFooterLinkMaldives'))
		LoadFooter('openCloseFooterLinkMaldives', 'divFooterContentMaldives');
	else if (getItem('openCloseFooterLinkSeychelles'))
		LoadFooter('openCloseFooterLinkSeychelles', 'divFooterContentSeychelles');

	if (document.URL.toLowerCase().indexOf('tab=finder') > 0)
		openTab('bsfinder');

}

//function getUserImage(){
//	        //counter++;
//	        getItem('Limg').src = 'Images/Users/original/' + ID + '.jpg';
//}



var arrSwfUpload = new Array;
function initSWF_Classifieds() {
	arrSwfUpload.push(
	 new SWFUpload({
	 	// Backend Settings
	 	upload_url: "../Uploader/upload.aspx?Type=2", // Relative to the SWF file

	 	// File Upload Settings
	 	file_size_limit: "2048", // 2MB
	 	file_types: "*.jpg;*.gif;*.bmp;*.png",
	 	file_types_description: "Image Files",
	 	file_upload_limit: "0",    // Zero means unlimited

	 	// Event Handler Settings
	 	file_dialog_start_handler: fileDialogStart_Classifieds,
	 	file_queued_handler: fileQueued,
	 	file_dialog_complete_handler: fileDialogComplete,
	 	upload_start_handler: uploadStart,
	 	upload_progress_handler: uploadProgress,
	 	upload_success_handler: uploadSuccess,
	 	upload_complete_handler: uploadComplete,
	 	error_handler: uploadError,

	 	// Button settings
	 	button_image_url: "http://img.spotlocal.net/img/userprofile/UpLoadImage2.jpg", // Relative to the SWF file
	 	button_placeholder_id: "flashClassifiedsUploader",
	 	button_width: 175,
	 	button_height: 50,
	 	button_text: '<a class="UploadimageDiv" >upload new photo</a>',
	 	button_text_style: '.UploadimageDiv{ font-size: 17px; cursor:pointer;letter-spacing:-1px;   font-family:Trebuchet MS; color:#666666;cursor:pointer;}',
	 	button_text_top_padding: 6,
	 	button_text_left_padding: 30,

	 	// Flash Settings
	 	flash_url: "../Uploader/swfupload.swf", // Relative to this file

	 	// Debug Settings
	 	debug: false
	 })
    );
}

function initSWF_UserProfile(strPlaceHolderID) {
	arrSwfUpload.push(
	new SWFUpload({
		// Backend Settings
		upload_url: "../Uploader/upload.aspx?Type=0", // Relative to the SWF file

		// File Upload Settings
		file_size_limit: "2048", // 2MB
		file_types: "*.jpg;*.gif;*.bmp;*.png",
		file_types_description: "Image Files",
		file_upload_limit: "0",    // Zero means unlimited

		// Event Handler Settings
		file_dialog_start_handler: fileDialogStart_UserProfile,
		file_queued_handler: fileQueued,
		file_dialog_complete_handler: fileDialogComplete,
		upload_start_handler: uploadStart,
		upload_progress_handler: uploadProgress,
		upload_success_handler: uploadSuccess,
		upload_complete_handler: uploadComplete,
		error_handler: uploadError,

		// Button settings
		button_image_url: "", // Relative to the SWF file
		button_placeholder_id: strPlaceHolderID,
		button_width: 100,
		button_height: 23,
		button_text: '<span class="button">change photo</span>',
		button_text_style: '.button { margin-top:0px; color:#00CCFF; font-weight:bold; font-size:11px; text-decoration:none; font-family:Arial, Helvetica, sans-serif; cursor:pointer; } ',
		button_text_top_padding: 0,
		button_text_left_padding: 0,

		// Flash Settings
		flash_url: "../Uploader/swfupload.swf", // Relative to this file

		// Debug Settings
		debug: false
	})
    );
}


function initSWF_DirectoryPhotos() {
	arrSwfUpload.push(
		new SWFUpload({
			// Backend Settings
			upload_url: "../Uploader/upload.aspx?Type=3", // Relative to the SWF file

			// File Upload Settings
			file_size_limit: "2048", // 2MB
			file_types: "*.jpg;*.gif;*.bmp;*.png",
			file_types_description: "Image Files",
			file_upload_limit: "0",    // Zero means unlimited

			// Event Handler Settings
			file_dialog_start_handler: fileDialogStart_DirectoryPhotos,
			file_queued_handler: fileQueued,
			file_dialog_complete_handler: fileDialogComplete,
			upload_start_handler: uploadStart,
			upload_progress_handler: uploadProgress,
			upload_success_handler: uploadSuccess,
			upload_complete_handler: uploadComplete,
			error_handler: uploadError,

			// Button settings
			button_image_url: "http://img.spotlocal.net/img/userprofile/UpLoadImage2.jpg", // Relative to the SWF file
			button_placeholder_id: "flashUploader_DirectoryPhotos",
			button_width: 175,
			button_height: 50,
			button_text: '<a class="UploadimageDiv" >upload new photo</a>',
			button_text_style: '.UploadimageDiv{ font-size: 17px; cursor:pointer;letter-spacing:-1px;   font-family:Trebuchet MS; color:#666666;cursor:pointer;}',
			button_text_top_padding: 6,
			button_text_left_padding: 30,

			// Flash Settings
			flash_url: "../Uploader/swfupload.swf", // Relative to this file

			// Debug Settings
			debug: false
		})
	);
}

function initSWF_DirectoryLogo() {
	arrSwfUpload.push(
		new SWFUpload({
			// Backend Settings
			upload_url: "../Uploader/upload.aspx?Type=4", // Relative to the SWF file

			// File Upload Settings
			file_size_limit: "2048", // 2MB
			file_types: "*.jpg;*.gif;*.bmp;*.png",
			file_types_description: "Image Files",
			file_upload_limit: "0",    // Zero means unlimited

			// Event Handler Settings
			file_dialog_start_handler: fileDialogStart_DirectoryLogo,
			file_queued_handler: fileQueued,
			file_dialog_complete_handler: fileDialogComplete,
			upload_start_handler: uploadStart,
			upload_progress_handler: uploadProgress,
			upload_success_handler: uploadSuccess,
			upload_complete_handler: uploadComplete,
			error_handler: uploadError,

			// Button settings
			button_image_url: "http://img.spotlocal.net/img/userprofile/UpLoadImage2.jpg", // Relative to the SWF file
			button_placeholder_id: "flashUploader_DirectoryLogo",
			button_width: 175,
			button_height: 50,
			button_text: '<a class="UploadimageDiv" >upload new logo</a>',
			button_text_style: '.UploadimageDiv{ font-size: 17px; cursor:pointer;letter-spacing:-1px;   font-family:Trebuchet MS; color:#666666;cursor:pointer;}',
			button_text_top_padding: 6,
			button_text_left_padding: 30,

			// Flash Settings
			flash_url: "../Uploader/swfupload.swf", // Relative to this file

			// Debug Settings
			debug: false
		})
	);
}


//Example : R MF AC CORRMF STA DFB
function isAccomodation(OptionCode) {
	if (OptionCode != null && OptionCode != "" && OptionCode.length > 6) {
		return (OptionCode.substring(3, 5).toUpperCase() == 'AC');
	}
	return false;
}
function OptionCodeClass(_FullCode) {
	this.Domain = "?";
	this.ServiceType = "??"
	this.Supplier = "??????";
	this.ServiceLevel = "???"; // Standard , Delux , Villa ...... 
	this.MealPlan = "???"; // BB for Bed & breakfast , FB for full board .....
	if (_FullCode != 'undefined' && _FullCode != null && _FullCode != "") {
		this.FullCode = _FullCode;
		this.Domain = _FullCode.substring(0, 1);
		this.Location = _FullCode.substring(1, 3);
		this.ServiceType = _FullCode.substring(3, 5);
		this.Supplier = _FullCode.substring(5, 11);
		this.ServiceLevel = _FullCode.substring(11, 14);
		this.MealPlan = _FullCode.substring(14, _FullCode.length);
	}
	//this.ToString = _formatOptionCode;//this.Domain + this.Location + this.ServiceType + this.Supplier + this.ServiceLevel + this.MealPlan ; 
}
function _formatOptionCode() {
	if (this.FullCode != "")
		return this.FullCode;
	else
		return (this.FullCode = this.Domain + this.Location + this.ServiceType + this.Supplier + this.ServiceLevel + this.MealPlan);
}

function LightItem(_ItemID, _Price, _OptionCode, _Stars) {
	this.ItemID = _ItemID;
	this.Price = _Price;
	this.OptionCode = _OptionCode;
	this.Stars = _Stars;
}


//------------------------------------------------------//
// SDK functions                                        //
//------------------------------------------------------//
function addCommas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function getMax(arrNumbers) {
	var Max = 0;
	if (arrNumbers != null && arrNumbers.length > 0) {
		Max = arrNumbers[0];
		for (var x = 1; x < arrNumbers.length; x++) {
			if (arrNumbers[x] > Max)
				Max = arrNumbers[x];
		}
	}
	return Max;
}

function getMin(arrNumbers) {
	var Min = 0;
	if (arrNumbers != null && arrNumbers.length > 0) {
		Min = arrNumbers[0];
		for (var x = 1; x < arrNumbers.length; x++) {
			if (arrNumbers[x] < Min)
				Min = arrNumbers[x];
		}
	}
	return Min;
}


//Added by mhassan
///===================================
///====auto suggest functions   ======
///===================================

function selectSearchType(itemName) {
	var a = $find("autoSuggest");
	if (a) {
		if (itemName == 'lnkBussinessSearch')
			a.set_serviceMethod('GetSuggestedList');
		else
			a.set_serviceMethod('');
	}

	replaceStyle('lnkBussinessSearch', '');
	replaceStyle('lnkClassifiedsSearch', '');
	replaceStyle('lnkMembersSearch', '');

	replaceStyle(itemName, 'Selected');

	if (itemName == 'lnkBussinessSearch') {
		$get('ctl00_Header1_headerSearchBox').value = 'search directory';
		SEARCH_BOX_MESSAGE = 'search directory';
		searchType = 0;
	}
	else if (itemName == 'lnkClassifiedsSearch') {
		$get('ctl00_Header1_headerSearchBox').value = 'search classifieds';
		SEARCH_BOX_MESSAGE = 'search classifieds';
		searchType = 1;
	}
	else if (itemName == 'lnkMembersSearch') {
		$get('ctl00_Header1_headerSearchBox').value = 'search members';
		SEARCH_BOX_MESSAGE = 'search members';
		searchType = 2;
	}
}

function search(boxName) {
	if (document.all(boxName)) {
		if (document.all(boxName).value != '' && document.all(boxName).value != SEARCH_BOX_MESSAGE) {
			//Added By Amr ElGarhy 15 Jun 2008
			if (searchType == 1) {
				var term = trimAll(document.all(boxName).value);
				if (term.indexOf('!') == 0)
					location.href = "/cdetails.aspx?Term=" + term;
				else
					location.href = "/classifieds.aspx?Term=" + term;
			}
			else if (searchType == 0)
				location.href = "/directory.aspx?Term=" + trimAll(document.all(boxName).value);
			else if (searchType == 2)
				location.href = "/members.aspx?Term=" + trimAll(document.all(boxName).value);
		}
		else {
			document.all(boxName).value = SEARCH_BOX_MESSAGE;
		}
	}
}

function clearSearchBoxOnFocus(boxName, mess) {
	if (getItem(boxName) != null)
		if (getItem(boxName).value == mess) {
		getItem(boxName).value = '';
	}
}

function searchBoxEnter(key, boxname) {
	if (key.keyCode == 13) {
		setTimeout("search('" + boxname + "')", 500);
		return false;
	} else {
		return true;
	}
}


//--mhassan----------------------------------------------------------------
//Method to limit Lenth of text in textbox
//-------------------------------------------------------------------------
function limitTextLength(TextFieldName, length, DisplaySpanName) {
	try {
		var TextField = null;
		var DisplaySpan = null;
		if (TextFieldName != null && TextFieldName != '') {
			TextField = getItem(TextFieldName);
			if (TextField != null) {
				if (TextField.value.length > length) {
					TextField.value = TextField.value.substring(0, length);
					var NewLength = length - TextField.value.length;
					if (NewLength < 0) {
						TextField.value = TextField.value.substring(0, length - 1);
					}
				}
			}
		}
		if (DisplaySpanName != null && DisplaySpanName != '') {
			DisplaySpan = getItem(DisplaySpanName);
			if (DisplaySpan != null) {
				if (TextField.value.length == 0)
					DisplaySpan.innerHTML = length;
				else {
					DisplaySpan.innerHTML = length - TextField.value.length;
				}
			}
		}
		if (event != null) {
			var keyCode = event.keyCode;
			if (keyCode == 8 || keyCode == 46)//8=Backspace and 46=delete
				setTimeout("limitTextLength('" + TextFieldName + "'," + length + ",'" + DisplaySpanName + "')", 1);
		}
	}
	catch (ex) { }
}


function ViewProfile() {
	location = "/userprofile.aspx?ID=" + ID;
}

function ShowSomeOneElseProfile() {
	location = "/userprofilepreview.aspx?ID=" + SomeOneElseOpenAccessCard;
}

function goBack() {
	history.back();
}


function openTermsPopUp(url) {
	mywindow = window.open(url, "");
}



function openCloseFooter(link, footer) {
	if (getItem(link).innerHTML == "Close") {
		getItem(link).innerHTML = "Open";
		replaceStyle(link, "open");
		createCookie('spotFooter', 'close', 5)
	}
	else {
		getItem(link).innerHTML = "Close";
		replaceStyle(link, "close");
		createCookie('spotFooter', 'open', 5)
	}

	Effect.toggle(footer, 'BLIND');
}


function LoadFooter(link, footer) {
	if (readCookie('spotFooter') == "close") {
		getItem(link).innerHTML = "Open";
		replaceStyle(link, "open");
		getItem(footer).style.display = "none";
	}
	else {
		getItem(link).innerHTML = "Close";
		replaceStyle(link, "close");
		getItem(footer).style.display = "";
	}
}

// Added By Amr ElGarhy 15 May 2008
// For Handling any check box checked, not cheched toggling.
function toggleCheckBox(item) {
	if (item.className == 'Selected')
		replaceStyle(item.id, "");
	else
		replaceStyle(item.id, "Selected");
}

function selectUnSelectAll(item) {

	selectedTypes.clear();
	if (item.id.indexOf('typeLink_ALL') != -1) {
		var items = document.getElementsByName('TypeLinks');
		for (var j = 0; j < items.length; j++) {
			if (items[j].parentNode.id == item.id.replace('typeLink_ALL', '')) {
				replaceStyle(items[j].id, item.className);

			}
		}
	}

	for (var i = 0; i < items.length; i++) {
		if (items[i].className == 'Selected')
			selectedTypes.push(items[i].id.replace('typeLink_', ''));
	}

	$get("SortAToZ").className = '';
	$get("SortPopularity").className = '';
	$get("SortPrice").className = '';
	$get("SortMostRecent").className = '';
	replaceStyle('SortMostRecent', 'Sort-DS');

	showLoadProgress();
	Classified.GetNumberOfLabels(selectedTypes, searchKeyWord, onGetNumberOfAdsLabelsComplete, onGetNumberOfAdsLabelsTimeOut, onGetNumberOfAdsLabelsError);
	Classified.GetLabelsData(selectedTypes, 1, numberOfLabelsPerPage, 0, 1, searchKeyWord, onGetAdsLabelsComplete, onGetAdsLabelsTimeOut, onGetAdsLabelsError);
}

function checkSelectedAll(item) {
	var items = document.getElementsByName('TypeLinks');
	var selected = true;
	for (var i = 0; i < items.length; i++) {
		if (items[i].parentNode.id == item.parentNode.id) {

			if (items[i].className == '') {
				selected = false;
				break;
			}
		}
	}

	var allItems = document.getElementsByName(item.parentNode.id);
	if (selected)
		replaceStyle(allItems[0].id, 'Selected');
	else
		replaceStyle(allItems[0].id, '');
}

function onAjaxError(result) {

}

function onAjaxTimeOut(result) {
}



// Date format function -- added by hassan 2-12-2008

/*
* Date Format 1.2.2
* (c) 2007-2008 Steven Levithan <stevenlevithan.com>
* MIT license
* Includes enhancements by Scott Trenda <scott.trenda.net> and Kris Kowal <cixar.com/~kris.kowal/>
*
* Accepts a date, a mask, or a date and a mask.
* Returns a formatted version of the given date.
* The date defaults to the current date/time.
* The mask defaults to dateFormat.masks.default.
*/
var dateFormat = function() {
	var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function(val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function(date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && (typeof date == "string" || date instanceof String) && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date();
		if (isNaN(date)) throw new SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var _ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d: d,
				dd: pad(d),
				ddd: dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m: m + 1,
				mm: pad(m + 1),
				mmm: dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy: String(y).slice(2),
				yyyy: y,
				h: H % 12 || 12,
				hh: pad(H % 12 || 12),
				H: H,
				HH: pad(H),
				M: M,
				MM: pad(M),
				s: s,
				ss: pad(s),
				l: pad(L, 3),
				L: pad(L > 99 ? Math.round(L / 10) : L),
				t: H < 12 ? "a" : "p",
				tt: H < 12 ? "am" : "pm",
				T: H < 12 ? "A" : "P",
				TT: H < 12 ? "AM" : "PM",
				Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
} ();

// Some common format strings
dateFormat.masks = {
	"default": "ddd mmm dd yyyy HH:MM:ss",
	shortDate: "m/d/yy",
	mediumDate: "mmm d, yyyy",
	longDate: "mmmm d, yyyy",
	fullDate: "dddd, mmmm d, yyyy",
	shortTime: "h:MM TT",
	mediumTime: "h:MM:ss TT",
	longTime: "h:MM:ss TT Z",
	isoDate: "yyyy-mm-dd",
	isoTime: "HH:MM:ss",
	isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function(mask, utc) {
	return dateFormat(this, mask, utc);
};






//This function used from the combobox
var currentComboId = '';
function Select(ctlSelect, MethodToCallAfterSelect) {
	currentComboId = ctlSelect.id;
	if (ctlSelect.selectedIndex > -1) {
		if (ctlSelect.options[ctlSelect.selectedIndex].text) {
			$get(ctlSelect.id + '_myp').innerHTML = ctlSelect.options[ctlSelect.selectedIndex].text;
		}
		else {
			$get(ctlSelect.id + '_myp').innerHTML = $get(currentComboId + '_myp').title;
		}
	}
	else
		$get(ctlSelect.id + '_myp').innerHTML = $get(currentComboId + '_myp').title;


	eval(MethodToCallAfterSelect);
}

//For change the view functions while hoverning on the control.
function mouseOver(ctrl) {
	replaceStyle(ctrl.id + '_arrow', 'Hvr');
}

function mouseOut(ctrl) {
	replaceStyle(ctrl.id + '_arrow', '');
}

function onClick(ctrl, MethodToGetData) {
	if (ctrl.options.length > 0)
		return;
	if (!MethodToGetData)
		return;
	currentComboId = ctrl.id;
	$get(ctrl.id + '_myp').innerHTML = 'Loading...';
	eval(MethodToGetData);
}

function onGetDataComplete(result) {
	var data = result.toString().split(',');
	var counter = 0;
	for (var i = 0; i < data.length; i += 2) {
		$get(currentComboId).options[counter] = new Option(data[i + 1], data[i]);
		counter++;
	}
	$get(currentComboId + '_myp').innerHTML = $get(currentComboId + '_myp').title;
}

function onGetDataError(result) {

}

function onGetDataTimeOut(result) {

}

function ContactUs_SendMail() {
	if (!ContactUs_ValidateFormFields())
		return;
	var c_cmbFeedBackType = $get(g_ContactUs_strComboFeedBackTypeID);
	var c_txtName = $get('txtName');
	var c_txtEmail = $get('txtEmail');
	var c_txtMessage = $get('txtMessage');

	var strFeedBacktype = c_cmbFeedBackType.options[c_cmbFeedBackType.selectedIndex].value;
	General.SendContactUsMail(strFeedBacktype, c_txtName.value, c_txtEmail.value, c_txtMessage.value, OnContactUs_SendMail_Complete, onAjaxError, onAjaxTimeOut);
}

function ContactUs_ClearFormFields() {
	$get(g_ContactUs_strComboFeedBackTypeID).selectedIndex = 0;
	Select($get(g_ContactUs_strComboFeedBackTypeID));
	$get('txtName').value = '';
	$get('txtEmail').value = '';
	$get('txtMessage').value = '';
}

function ContactUs_ValidateFormFields() {
	if (!validateEmpty('txtName')) {
		showMessage('please write your name.', 1);
		return false;
	}

	if (!validateEmpty('txtEmail')) {
		showMessage('please write your email.', 1);
		return false;
	}
	if (!validateEmail('txtEmail')) {
		showMessage('email is incorrect.', 1);
		return false;
	}
	if (!validateEmpty('txtMessage')) {
		showMessage('please write the message.', 1);
		return false;
	}
	return true;
}

function OnContactUs_SendMail_Complete(result) {
	ContactUs_ClearFormFields();
	showMessage("FeedBack sent successfully", 2);
}

function getHTMLEncode(t) {
	return t.toString().replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}

function AdLayerShow(iAdID) {
	var strAdTitle, iAdWidth, iAdHeight;
	var arrAds = new Array(
			new Array("Id", "Title", "Width", "Height"),
			new Array(1, "Steigenberger Al Dau Algotherm Red Sea Thalasso and Spa", 820, 600),
			new Array(2, "Little Buddha 360 Tour", 820, 600)
		);
	for (var i = 0; i < arrAds.length; i++) {
		if (arrAds[i][0] == iAdID) {
			strAdTitle = arrAds[i][1];
			iAdWidth = arrAds[i][2];
			iAdHeight = arrAds[i][3];
			break;
		}
	}

	if (strAdTitle && strAdTitle.length > 0) {
		var strUrl = "/AdShow.aspx?ID=" + iAdID + "&TB_iframe=true&height=" + iAdHeight + "&width=" + iAdWidth;
		
			tb_show(strAdTitle, strUrl, '');
		
	}
}
