var SITE_URL = "/";
//var SITE_URL = "http://www.homesguide.com.au/";
//var SITE_URL = "/hg/";
$(document).ready(function(){
		//searchText auto complete
		$("#searchText").autocomplete(SITE_URL+"search.php?action=suburbs", {
		matchContains: true,
		minChars: 0,
		mustMatch: false,
		matchSubset:1,
		autoFill: false,
		multiple: true
	});

	$("#agencySearch").autocomplete(""); //temporary fix until what "autocomplete" is worked out and what it actually does to the textfield before loading


/* --------------- NEWS-TICKER --------------- */

/*$(function(){
	$('#newsTicker').vTicker({ 
		speed: 300,
		pause: 8000,
		animation: 'fade',
		mousePause: true,
		showItems: 1
	});
});*/


/* --------------- CALENDAR --------------- */

	$('#startDate').calendar({
		dateFormat:'%d/%m/%y'
	});
	$('#endDate').calendar({
		dateFormat:'%d/%m/%y'
	});
	/*$('#auctions_startDate').calendar({
		dateFormat:'%d/%m/%y'
	});
	$('#auctions_endDate').calendar({
		dateFormat:'%d/%m/%y'
	});
					
	$('#garageSales_startDate').calendar({
		dateFormat:'%d/%m/%y'
	});
	$('#garageSales_endDate').calendar({
		dateFormat:'%d/%m/%y'
	});*/
	//account settings / user details
	
});


function searchTextDefault(defaultVal, inputField){
		$("#searchText").attr('style', 'width:280px; border:1px solid #ccc; padding:3px;');
		var active_color = '#000'; // Colour of user provided text
		var inactive_color = '#888'; // Colour of default text

		$(document).ready(function() {
		  $("#"+inputField).css("color", inactive_color);
		  var default_values = new Array();
		  $("#"+inputField).focus(function() {
			if (!default_values[this.id]) {
			  default_values[this.id] = this.value;
			}
			if (this.value == defaultVal) {
			  this.value = '';
			}
			 this.style.color = active_color;
			
			$(this).blur(function() {
			  if (this.value == '') {
				this.style.color = inactive_color;
				this.value = defaultVal;
			  }
			});
		  });
	});
}

function activateAdvanceSearch(formID){
	if (formID){
		form=document.getElementById(formID);
		if ($('#'+formID+"_"+'displayText').html()  == 'Advanced Search')
		{
			form.advancedS.value = 'true';
		}
		else {
			form.advancedS.value = '';
		}
	}
}


function searchToggle(searchDivID, formID) {
	activateAdvanceSearch(formID);
	$("#"+searchDivID).toggle();
	
	if ($('#'+formID+"_"+'displayText').html() == "Advanced Search")
		$('#'+formID+"_"+'displayText').html("Basic Search");
	else
		$('#'+formID+"_"+'displayText').html("Advanced Search");
} 

function showNumbers(classVal) {
	$("."+classVal).show();
	recordPhoneCall();
	if ($('#agentsNumber').html("<a style='width:95px; text-align:center;' class='btnBlack' id='callAgent' href='javascript:showNumbers('agentsNumber');'><strong>Call This Agent</strong></a><br />"))
		$('#agentsNumber').html("");
	else
		$('#agentsNumber').html("<a style='width:95px; text-align:center;' class='btnBlack' id='callAgent' href='javascript:showNumbers('agentsNumber');'><strong>Call This Agent</strong></a><br />");
}

function recordPhoneCall() {
	proID=document.getElementById('ProID').value;
	$.ajax({
		type:"GET",
		url:SITE_URL+"details.php?action=recordToStats&ProID="+proID
	});
}

function showEmailForm(classVal) {
	$("."+classVal).show();
	if ($('#emailForm').html("<a style='width:95px; text-align:center;' class='btnBlack' id='emailAgent' href='javascript:showEmailForm('emailForm');'><strong>Email This Agent</strong></a>"))
		$('#emailForm').html("");
	else
		$('#emailForm').html("<a style='width:95px; text-align:center;' class='btnBlack' id='emailAgent' href='javascript:showEmailForm('emailForm');'><strong>Email This Agent</strong></a>");
}

function showNumbers2(classVal) {
	$("."+classVal).show();
	recordPhoneCall();
	if ($('#agentsNumber2').html("<a style='width:95px; text-align:center;' class='btnBlack' id='callAgent2' href='javascript:showNumbers2('agentsNumber2');'><strong>Call This Agent</strong></a><br />"))
		$('#agentsNumber2').html("");
	else
		$('#agentsNumber2').html("<a style='width:95px; text-align:center;' class='btnBlack' id='callAgent2' href='javascript:showNumbers2('agentsNumber2');'><strong>Call This Agent</strong></a><br />");
}
function showEmailForm2(classVal) {
	$("."+classVal).show();
	if ($('#emailForm2').html("<a style='width:95px; text-align:center;' class='btnBlack' id='emailAgent2' href='javascript:showEmailForm2('emailForm2');'><strong>Email This Agent</strong></a>"))
		$('#emailForm2').html("");
	else
		$('#emailForm2').html("<a style='width:95px; text-align:center;' class='btnBlack' id='emailAgent2' href='javascript:showEmailForm2('emailForm2');'><strong>Email This Agent</strong></a>");
}

function showContactDetails(classVal) {
	$("."+classVal).toggle();
	if ($('#agentsNumber').html("<a style='width:95px; text-align:center;' class='btnBlack' id='callAgent' href='javascript:showContactDetails('agentsNumber');'><strong>Call This Agent</strong></a><br />"))
		$('#agentsNumber').html("");
	else
		$('#agentsNumber').html("<a style='width:95px; text-align:center;' class='btnBlack' id='callAgent' href='javascript:showContactDetails('agentsNumber');'><strong>Call This Agent</strong></a><br />");
}

function showLoginBox(classVal) {
	$("#"+classVal).toggle();
}

function showLostPasswordBox(classVal) {
	$("#"+classVal).toggle();	
}

function showImages(classVal) {
	$("."+classVal).toggle();
	var text = document.getElementById("displayText");
	if ($('#moreImagesText').html() == "Show More Images") {
		$('#moreImagesText').html("Hide Images");
	}
	else {
		$('#moreImagesText').html("Show More Images");
		$("."+classVal).hide();
	}
	
} 

function showPlan(classVal) {
	$("#plan_"+classVal).toggle();
	var text = document.getElementById("viewPlan_"+classVal);
	if ($('#viewPlan_'+classVal).html() == "<strong>View</strong>") {
		$('#viewPlan_'+classVal).html("<strong>Hide</strong>");
	}
	else {
		$('#viewPlan_'+classVal).html("<strong>View</strong>");
		$("#"+classVal).hide();
	}
	
} 

function byAgent(){
	$("#searchResidentialAgent").show();
	$("#searchResidentialForSale").hide();
	$("#byAgent").attr('class', 'selected');
	$("#forSale").attr('class', '');

}

function processSearch(formID){
	document.getElementById(formID).submit();
}

function openHomes_initCallback(carousel) {

    jQuery('#openHomes-next').bind('click', function() {
        carousel.next();
        return false;
    });

    jQuery('#openHomes-prev').bind('click', function() {
        carousel.prev();
        return false;
    });
};

jQuery(document).ready(function() {
    jQuery('#openHomes').jcarousel({
        vertical: true,
		animation:0,
        scroll: 1,
	    initCallback: openHomes_initCallback,
        // This tells jCarousel NOT to autobuild prev/next buttons
        buttonNextHTML: null,
        buttonPrevHTML: null
    });
});



function auctions_initCallback(carousel) {
    jQuery('#auctions-next').bind('click', function() {
        carousel.next();
        return false;
    });

    jQuery('#auctions-prev').bind('click', function() {
        carousel.prev();
        return false;
    });
};

jQuery(document).ready(function() {
    jQuery('#auctions').jcarousel({
        vertical: true,
		animation:0,
        scroll: 1,
	    initCallback: auctions_initCallback,
        // This tells jCarousel NOT to autobuild prev/next buttons
        buttonNextHTML: null,
        buttonPrevHTML: null
    });
});


function garageSalesNSW_initCallback(carousel) {

    jQuery('#garageSalesNSW-next').bind('click', function() {
        carousel.next();
        return false;
    });

    jQuery('#garageSalesNSW-prev').bind('click', function() {
        carousel.prev();
        return false;
    });
};

jQuery(document).ready(function() {
    jQuery('#garageSalesNSW').jcarousel({
        vertical: true,
		animation:0,
        scroll: 1,
	    initCallback: garageSalesNSW_initCallback,
        // This tells jCarousel NOT to autobuild prev/next buttons
        buttonNextHTML: null,
        buttonPrevHTML: null
    });
});


function garageSalesQLD_initCallback(carousel) {

    jQuery('#garageSalesQLD-next').bind('click', function() {
        carousel.next();
        return false;
    });

    jQuery('#garageSalesQLD-prev').bind('click', function() {
        carousel.prev();
        return false;
    });
};

jQuery(document).ready(function() {
    jQuery('#garageSalesQLD').jcarousel({
        vertical: true,
		animation:0,
        scroll: 1,
	    initCallback: garageSalesQLD_initCallback,
        // This tells jCarousel NOT to autobuild prev/next buttons
        buttonNextHTML: null,
        buttonPrevHTML: null
    });
});



jQuery(document).ready(function() {
    jQuery('#garageSalesVIC').jcarousel({
        vertical: true,
		animation:0,
        scroll: 1,
	    initCallback: garageSalesVIC_initCallback,
        // This tells jCarousel NOT to autobuild prev/next buttons
        buttonNextHTML: null,
        buttonPrevHTML: null
    });
});


function garageSalesVIC_initCallback(carousel) {

    jQuery('#garageSalesVIC-next').bind('click', function() {
        carousel.next();
        return false;
    });

    jQuery('#garageSalesVIC-prev').bind('click', function() {
        carousel.prev();
        return false;
    });
};



jQuery(document).ready(function() {
    jQuery('#garageSalesACT').jcarousel({
        vertical: true,
		animation:0,
        scroll: 1,
	    initCallback: garageSalesACT_initCallback,
        // This tells jCarousel NOT to autobuild prev/next buttons
        buttonNextHTML: null,
        buttonPrevHTML: null
    });
});


function garageSalesACT_initCallback(carousel) {

    jQuery('#garageSalesACT-next').bind('click', function() {
        carousel.next();
        return false;
    });

    jQuery('#garageSalesACT-prev').bind('click', function() {
        carousel.prev();
        return false;
    });
};


jQuery(document).ready(function() {
    jQuery('#garageSalesNT').jcarousel({
        vertical: true,
		animation:0,
        scroll: 1,
	    initCallback: garageSalesNT_initCallback,
        // This tells jCarousel NOT to autobuild prev/next buttons
        buttonNextHTML: null,
        buttonPrevHTML: null
    });
});


function garageSalesNT_initCallback(carousel) {

    jQuery('#garageSalesNT-next').bind('click', function() {
        carousel.next();
        return false;
    });

    jQuery('#garageSalesNT-prev').bind('click', function() {
        carousel.prev();
        return false;
    });
};

jQuery(document).ready(function() {
    jQuery('#garageSalesSA').jcarousel({
        vertical: true,
		animation:0,
        scroll: 1,
	    initCallback: garageSalesSA_initCallback,
        // This tells jCarousel NOT to autobuild prev/next buttons
        buttonNextHTML: null,
        buttonPrevHTML: null
    });
});


function garageSalesSA_initCallback(carousel) {

    jQuery('#garageSalesSA-next').bind('click', function() {
        carousel.next();
        return false;
    });

    jQuery('#garageSalesSA-prev').bind('click', function() {
        carousel.prev();
        return false;
    });
};


jQuery(document).ready(function() {
    jQuery('#garageSalesTAS').jcarousel({
        vertical: true,
		animation:0,
        scroll: 1,
	    initCallback: garageSalesTAS_initCallback,
        // This tells jCarousel NOT to autobuild prev/next buttons
        buttonNextHTML: null,
        buttonPrevHTML: null
    });
});


function garageSalesTAS_initCallback(carousel) {

    jQuery('#garageSalesTAS-next').bind('click', function() {
        carousel.next();
        return false;
    });

    jQuery('#garageSalesTAS-prev').bind('click', function() {
        carousel.prev();
        return false;
    });
};

jQuery(document).ready(function() {
    jQuery('#garageSalesWA').jcarousel({
        vertical: true,
		animation:0,
        scroll: 1,
	    initCallback: garageSalesTAS_initCallback,
        // This tells jCarousel NOT to autobuild prev/next buttons
        buttonNextHTML: null,
        buttonPrevHTML: null
    });
});


function garageSalesWA_initCallback(carousel) {

    jQuery('#garageSalesWA-next').bind('click', function() {
        carousel.next();
        return false;
    });

    jQuery('#garageSalesWA-prev').bind('click', function() {
        carousel.prev();
        return false;
    });
};

/* --------------- ICON SUB-MENU --------------- */

$(document).ready(function(){
	var timeoutSubMenu = null

// COMPETITIONS
	$("#compsBtn").mouseenter(function(){
		$('.iconSubMenu').slideUp('fast');	
	});

// MY TOOLS
	$("#myToolsBtn").mouseenter(function(){
	if ($('#myTools').is(":hidden")) {
		$('.iconSubMenu').slideUp('fast');	
		$('#myTools').slideDown('fast');
	};
	});
	
// MY TOOLS (news-ticker link)
	$("#myToolsLink").mouseenter(function(){
	if ($('#myTools').is(":hidden")) {
		$('.iconSubMenu').slideUp('fast');	
		$('#myTools').slideDown('fast');
	};
	});

// MAGAZINES
	$("#magazinesBtn").mouseenter(function(){	
	if ($('#magazines').is(":hidden")) {
		$('.iconSubMenu').slideUp('fast');	
		$('#magazines').slideDown('fast');
	}
	});
	

// HOMESGUIDE DIRECTORY
	$("#directorySearchBtn").mouseenter(function(){			 
	if ($('#directorySearch').is(":hidden")) {
		$('.iconSubMenu').slideUp('fast');	
		$('#directorySearch').slideDown('fast');
	};
	});
	
// HOMESGUIDE DIRECTORY (news-ticker link)
	$("#directorySearchLink").mouseenter(function(){			 
	if ($('#directorySearch').is(":hidden")) {
		$('.iconSubMenu').slideUp('fast');	
		$('#directorySearch').slideDown('fast');
	};
	});

// AGENTS HOME
	$("#agentsHomeBtn").mouseenter(function(){
		$('.iconSubMenu').slideUp('fast');	
	});

// TIMEOUT ALL SUB-MENU
	$(".iconSubMenu").hover(
  	function () {
    	clearTimeout(timeoutSubMenu);
 	 },
  	function () {
		timeoutSubMenu = window.setTimeout(function() {
		$('.iconSubMenu').slideUp('fast');
		}, 1000);
  	});

});

/* --------------- ENQUIRY LINK & POP-UP --------------- */

function popUpEnquiryForm(tsID){
	window.open(SITE_URL+'enquiry.php?action=enqTradeService&tsID='+tsID, null,'height=360,width=480,status=no,toolbar=no,menubar=no,location=no, scrollbars=no');
}

/* --------------- EMAIL A FRIEND LINK & POP-UP --------------- */

function popUpEmailAFriendForm(){
	proID=$("#ProID").val();
	window.open(SITE_URL+'enquiry.php?action=emailAFriend&ProID='+proID, null,'height=400,width=450,status=no,toolbar=no,menubar=no,location=no, scrollbars=no');
}


/* --------------- PNG FIX --------------- */

var clear="images/blank.gif" //path to clear.gif

pngfix=function(){var els=document.getElementsByTagName('*');var ip=/\.png/i;var i=els.length;while(i-- >0){var el=els[i];var es=el.style;if(el.src&&el.src.match(ip)&&!es.filter){es.height=el.height;es.width=el.width;es.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+el.src+"',sizingMethod='crop')";el.src=clear;}else{var elb=el.currentStyle.backgroundImage;if(elb.match(ip)){var path=elb.split('"');var rep=(el.currentStyle.backgroundRepeat=='no-repeat')?'crop':'scale';es.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+path[1]+"',sizingMethod='"+rep+"')";es.height=el.clientHeight+'px';es.backgroundImage='none';var elkids=el.getElementsByTagName('*');if (elkids){var j=elkids.length;if(el.currentStyle.position!="absolute")es.position='static';while (j-- >0)if(!elkids[j].style.position)elkids[j].style.position="relative";}}}}}
if (document.window) {
window.attachEvent('onload',pngfix);
}


/* --------------- SUBMIT FORMS WITH ENTER KEY --------------- */

function checkEnter(e){ //e is event object passed from function invocation
var characterCode

if(e && e.which){ //if which property of event object is supported (NN4)
e = e
characterCode = e.which //character code is contained in NN4's which property
}
else{
e = event
characterCode = e.keyCode //character code is contained in IE's keyCode property
}

if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
login()
return false
}
else{
return true
}

}


/* --------------- DATA LIST ON-CLICK --------------- */

function goToListing(listingNumber, type)
{
	if (type==1)
		window.location = SITE_URL+"details.php?ProID="+listingNumber;
	if (type==2)
		window.location = SITE_URL+"garage_sale.php?garageID="+listingNumber+"&action=garageSales";
}

/* --------------- DATA LIST IE-HOVER --------------- */

function setBg(element, colour) {
if (element.style) element.style.background = colour;
}

/* --------------- REGION TABS --------------- */

function showState(state) {
	$('#nsw').hide();
	$('#nswBtn').attr('class','stateTab');
	$('#qld').hide();
	$('#qldBtn').attr('class','stateTab');
	$('#vic').hide();
	$('#vicBtn').attr('class','stateTab');
	$('#act').hide();
	$('#actBtn').attr('class','stateTab');
	$('#nt').hide();
	$('#ntBtn').attr('class','stateTab');
	$('#sa').hide();
	$('#saBtn').attr('class','stateTab');
	$('#tas').hide();
	$('#tasBtn').attr('class','stateTab');
	$('#wa').hide();
	$('#waBtn').attr('class','stateTab');
	$('#'+state).show();
	$('#'+state+'Btn').attr('class','stateTabSelected');

	map = new GMap2(document.getElementById("map_canvas"));

    //setMapCentre(map,-37.814251, 144.963169);
	map.addControl(new GSmallMapControl());
	map.addControl(new TextualZoomControl());
	getCurGarageSaleInfo(state);
}

function hideAllStates(){
	$('#qld').hide();
	$('#vic').hide();
	$('#act').hide();
	$('#nt').hide();
	$('#sa').hide();
	$('#tas').hide();
	$('#wa').hide();
}

function updateUserDetails()
{
	if ($("#editMode").val()=="")
	{
		$(".userDetailsText").hide();
	    $(".userDetailsTextField").show();
		$("#editMode").val(true);
		$(".boxFooter").show();
	}
	else {
		$(".userDetailsText").show();
	    $(".userDetailsTextField").hide();
		$("#editMode").val("");
		$(".boxFooter").hide();
	}
}

function deleteUser(){
	answer = confirm("Are you sure you want to delete your account? \nAny current garage sales and trade services attached to this account will also be permanently deleted. This CANNOT be undone.");
	if (answer)
	{	
		$("#delete").val(true);
		document.userDetails.submit();
	}
}

function doUpdate(){
	fName = document.forms["userDetails"].fName.value;
	lName = document.forms["userDetails"].lName.value;
	email = document.forms["userDetails"].email.value;
	phone = document.forms["userDetails"].phone.value;
	postCode = document.forms["userDetails"].postCode.value;
	passWord = document.forms["userDetails"].passWord.value;
	userID = document.forms["userDetails"].userID.value;

	if (passWord=="*******")
		passWord="";
	$.ajax({
		type: "GET",
		url: SITE_URL+"user.php",
		data: "action=update&userID="+userID+"&fName="+fName+"&lName="+lName+"&email="+email+"&phone="+phone+"&postCode="+postCode+"&passWord="+passWord,
		success: function (response) {
			updateUserDetails();

			//now also update the texual representation of the user details..
			$("#fNameText").html(fName);
			$("#lNameText").html(lName);
			$("#emailText").html(email);
			$("#phoneText").html(phone);
			$("#postCodeText").html(postCode);
			$("#passWordText").html(passWord);
		}
	});
}

function login(){
	var email = $("#email").val();
	var passWord = $("#passWord").val();
	var remember = "";
	if (document.getElementById('remember').checked)
		remember = "on";

	$.ajax({
		type: "POST",
		url: SITE_URL+"user.php",
		data: "action=login&email="+email+"&passWord="+passWord+"&remember="+remember,
		success: function (response) {
			if (response)
			{
				if (response!="LOGIN_FAILED")
				{
					userObj = eval("("+response+")");
					if (userObj)
					{
						$(".userLogin").html('Welcome '+userObj.firstName + ' '+ userObj.lastName+'.  '+ '  <a href="'+SITE_URL+'user.php?action=accountSettings&default=true" class="black"><strong>My Account</strong></a> | <a href="'+SITE_URL+'user.php?logOut=true" class="black"><strong>Logout</strong></a>');
						$('#loginBox').hide();
						$('#passwordBox').hide();						
						$('#loginTick').show();
					}

				}
				else{
					$("#statusMsg").html("<strong>You have entered an invalid email and/or password.</strong><br /><br />");
				}
		}
	  }
    });

	return false;
}

function clearStatusMsg(){
	$('#statusMsg').html('');
}

/* --------------- REGISTRATION FORM (VALIDATION) --------------- */

function validateUserRegForm(){
	errors = "";
	if (document.forms['fUserRegForm'].fName.value == '') {
		errors += " - Please enter your First Name \n";
	}
	if (document.forms['fUserRegForm'].lName.value == '') {
		errors += " - Please enter your Last Name \n";
	}
	if (document.forms['fUserRegForm'].email.value == '') {
		errors += " - Please enter your Email \n";
	}
	if (document.forms['fUserRegForm'].postCode.value == '') {
		errors += " - Please enter your Postcode \n";
	}
	if (document.forms['fUserRegForm'].marketingQuestion.value==''){
		errors += " - Please let us know how you heard about us \n";
	}
	if (document.forms['fUserRegForm'].passWord.value == '') {
		errors += " - Please enter your Password \n";
	}
	if (document.forms['fUserRegForm'].confirmPassword.value == '') {
		errors += " - Please confirm your Password \n";
	}
	if (document.forms['fUserRegForm'].confirmPassword.value != document.forms['fUserRegForm'].passWord.value) {
		errors += " - Please re-confirm your Password \n";
	}
	if (document.forms['fUserRegForm'].email.value != '') {
		if (!echeck(document.forms['fUserRegForm'].email.value))
		{
			errors += " - Your email address is invalid. Please re-enter your email.\n";
		}
	}
	if (errors)
	{
		alert(errors);
		return false;
	}
	return true;
}

function isChecked(form, field, value){
	val = checkedItems(form,field);
	for (q = 0; q < val.length; q++){
		if (val[q].value!="")
		{
			if (val[q].value==value)
			{
				return true;
			}
		}
	}

	return false;
}

function insertFlash(fileName, div, width, height, version, URL){
	$(document).ready(function(){
		var bannerImg = URL+fileName;
		$('#'+div).flash({ src: bannerImg,width: width,height: height, scale: 'exactfit'},{version: version});
	});
}


function removeComma(fileName){
	fileName=fileName.slice(0, -1);
	return fileName;
}

function limitText(limitField, limitCount, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	} else {
		//limitCount = limitNum - limitField.value.length;
		//$('#countdown').html(limitCount.value);
		limitCount.value = limitNum - limitField.value.length;
	}
}


function selectAll(field)
{
if (field.value)
	field.checked = true;

for (i = 0; i < field.length; i++){
		field[i].checked = true ;
	}
}

function unSelectAll(field)
{
	if (field.value)
		field.checked = false;
	for (i = 0; i < field.length; i++){
		field[i].checked = false ;
	}
}

function resetSearchText(){

	if (document.getElementById('searchText').value=='')
	{
		document.getElementById('searchText').value='Enter a Suburb, Postcode, State or Property ID'; 
	}
	else if (document.getElementById('searchText').value=='Enter a Suburb, Postcode, State or Property ID'){
		//alert('yep');
		document.getElementById('searchText').value='';
	}
	
}


function evalEncode(response){
	if(response) {
		return eval("("+response+")");
	}
}


function checkedItems(form,field){
	val = document.forms[form].elements[field]
	h=0;
	items=new Array();
	
	for (p = 0; p < val.length; p++){
		//alert(val[i].checked);	
		if (val[p].checked==true)
		{
			items[h] = val[p];
			h++;
		}
	}

	if (items)
		return items;
}

function borrowValue(field1,field2){
	document.getElementById(field2).value = document.getElementById(field1).value;
}

function selectUnSelectAll(form, field, checkBoxToCheck){
	if (checkedItems(form, field).length) 
	{
		unSelectAll(checkBoxToCheck); 
	}
	else { 
		selectAll(checkBoxToCheck); 
	}
}


function printableBrochure(proID){
	window.open(SITE_URL+'details.php?ProID='+proID+'&preview=true&print=true', null, 'height=700,width=1000,status=no,toolbar=no,menubar=no,location=no, scrollbars=yes');
}

function updateSearch(){
	$("#searchLoader").show();
	action = $("#action").val();
	searchType = $("#searchType").val();
	advancedS = $("#advancedS").val();
	defaultVal = $("#default").val();

	$.ajax({
		type: "GET",
		url: SITE_URL+"index.php",
		data: "ajax=updateSearch&searchType="+searchType+"&advancedS="+advancedS+"&default="+defaultVal+"&action="+action,
		success: function (response){
			$("#searchPanel").html(response);
			$("#loader").hide();
		}
	});
		
}

function checkSearch(e){ //e is event object passed from function invocation
var characterCode

if(e && e.which){ //if which property of event object is supported (NN4)
e = e
characterCode = e.which //character code is contained in NN4's which property
}
else{
e = event
characterCode = e.keyCode //character code is contained in IE's keyCode property
}

if(characterCode == 13){ //if generated character code is equal to ascii 13 (if enter key)
doSearch()
return false
}
else{
return true
}

}

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function checkItem(form, field, value){
	val= document.forms[form].elements[field];
	for (q = 0; q < val.length; q++){
			if (val[q].value!="")
			{
				if (val[q].value==value)
				{
					val[q].checked=true;
				}
		}
	}
}


function selectUnSelectAll(form, field, checkBoxToCheck){
	if (checkedItems(form, field).length) 
	{
		unSelectAll(checkBoxToCheck); 
	}
	else { 
		selectAll(checkBoxToCheck); 
	}
}

function printPage(url, form){
	if (form=="")
	{
		form="#searchProperty";
	}
	else {
		form="form";
	}
	//comp.php?action=findCompetition&print=true&ord=
	if (document.getElementById('ord'))
	{
		if (document.getElementById('ord').value)
		{
			ord=document.getElementById('ord').value;
		}
	}
	url=url+"&"+$(form).serialize()+"&print=true";

	if (document.getElementById('ord'))
	{
		url=url+"&ord="+ord;
	}

	window.open(url);
}


function echeck(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    return false
		 }

 		 return true					
}

 function windowOpen(url){
	 window.open(url);
 }

 

function evalEncode(response){
	return eval("("+response+")");
}


function commaSeperateArrayVal(array){	
	itemsCSV="";
	if (array.length>1)	{i=1;}else {i=0;}
		for(i=0;i<array.length;i++){
			itemsCSV+=array[i].value+",";
		}
		return itemsCSV;
}

function urlencode(str) {
str = escape(str).replace('+', '%2B').replace('%20', '+').replace('*', '%2A').replace('/', '%2F').replace('@', '%40').replace('%2C%20', '+').replace('%2C', '+');
return str;
}

function getFormFields(form){
	var $inputs = $('#'+form+' :input');
	return $inputs;
}
function doSearch(){
		GETParams="";
		URLRewrite="";

		var values = {};
		$inputs = getFormFields('fResSearch');
		result = $('#fResSearch').serialize();

		$inputs.each(function() {
			values[this.name] = $(this).val();
			if ($(this).val()!="" && $(this).val()!=0 && $(this).val()!="Min." &&
			$(this).val()!="Max." && this.name!="formURL" && $(this).val()!="SEARCH" && $(this).val()!=null)
			{
				if ($(this).attr('type')=='select-multiple')
				{
					//GETParams+=this.name+"="+$(this).val()+"&";
					propTypes=$(this).val().toString();
					propTypes=propTypes.split("|");
					propTypesStr=""

					for (i=0;i<propTypes.length;i++ )
					{
						if (propTypes[i])
						{
							if (propTypes[i].substring(0,1)==',')
							{
								propTypes[i]=propTypes[i].substr(1);
							};
							propTypesStr+=propTypes[i]+"|";
						}
					}

					GETParams+=this.name+"="+propTypesStr+"&";
				}
				else if ($(this).attr('type')=='checkbox')
				{
					if ($(this).attr('checked'))
					{
						GETParams+=this.name+"="+$(this).val()+"&";
					}
				}
				else {
					GETParams+=this.name+"="+$(this).val()+"&";
				}


				if (this.name=="bedrooms_min")
				{
					URLRewrite+="+bedrooms+"+$(this).val();	
				}
				else if (this.name=="bathrooms_min")
				{
					URLRewrite+="+bathrooms+"+$(this).val();	
				}
			}
		});


		searchText=$("#searchText").val();
		if (searchText!="" & searchText.search("Enter a ")!=0)
		{
			searchText = urlencode(searchText);
			formURL = $("#formURL").val();
			//$("#fResSearch").attr('action', formURL+"Search/"+searchText+URLRewrite+"/"+GETParams);
			GETParams=GETParams.slice(0,-1);
			window.location=formURL+"Search/"+searchText+URLRewrite+"/?"+GETParams;
		}
		else {
			$("#searchText").attr('style', 'width:280px; color:red; font-weight:bold; border:1px solid #ccc; padding:3px;');
		}
}
function addToPropList(ProID){
	$.ajax({
		type:"GET",
		url: SITE_URL+"property_list.php",
		data: "action=add&ProID="+ProID,
		success: function (response) {
			if (response>0)
			{
				//alert("This property was successfully added to your property list!");
				$("#removePropList_"+ProID).show();
				$("#savePropList_"+ProID).hide();
			}
			else {
				alert("This property is already in your property list and/or you are not logged in!");
			}
		}
	});
}

function removeFromPropList(ProID){
	$.ajax({
		type:"GET",
		url:SITE_URL+"property_list.php",
		data: "action=remove&ProID="+ProID,
		success: function (response){
			if (!response)
			{
				//alert("This property was successfully removed from your property list!");
				$("#removePropList_"+ProID).hide();
				$("#savePropList_"+ProID).show();
			}
			else {
				alert("There was an error in removing this property from your property list, please try again later.");
			}
		}
	});
}

function retLostPass(){
	email = document.getElementById('emailAdd').value;
	if (email)
	{
		$.ajax({
			type:"POST",
			url:SITE_URL+"user.php",
			data:"action=retPass&email="+email,
			success: function (response) {
				if (response>0)
				{
					$("#lostPass_statusMsg").html("An email has been sent to "+email+".<br /><br />");
					$("#lostPass_statusMsg").attr("class", "noticeGreen");
				}
				else {
					$("#lostPass_statusMsg").html("Sorry, no account matches that email address.<br /><br />");
					$("#lostPass_statusMsg").attr("class", "noticeRed");
				}
			}
		});
	}
	else {
			$("#lostPass_statusMsg").html("Please enter an email address.<br /><br />");
			$("#lostPass_statusMsg").attr("class", "noticeRed");
	}
}

function retAgentLostPass(){
	agencyID = document.getElementById('agencyID2').value;
	userName = document.getElementById('userName2').value;
	
	if (agencyID && userName)
	{
		$.ajax({
			type:"POST",
			url:SITE_URL+"index.php",
			data:"action=retAgentPass&agencyID="+agencyID+"&userName="+userName,
			success: function (response) {
				if (response=="SUCCESS")
				{
					$("#lostPass_statusMsg").html("An email has been sent to "+response+".<br /><br />");
					$("#lostPass_statusMsg").attr("class", "noticeGreen");
				}
				else {
					$("#lostPass_statusMsg").html("Sorry, no account matches that agency ID and username.<br /><br />");
					$("#lostPass_statusMsg").attr("class", "noticeRed");
				}
			}
		});
	}
}


