
//var searchPath = '/clientarea/venmore/liverpool_property_search.php';
//var mapSearchPath = '/clientarea/venmore/liverpool_property_search_map.php';
var searchPath = '/liverpool_property_search.php';
var mapSearchPath = '/liverpool_property_search_map.php';
var studentSearchPath = '/search_student_accomodation_liverpool.php';
var studentMapSearchPath = '/liverpool_property_search_map.php';

//Estate Agent IDs
// Venmore = 930
// William Gleave = 1147
// BFL = 223
var eaid = 930;

$(document).ready(function(){
	
	/*$('#menu li ul').css( {backgroundPosition : "0 300px"} );
	
	
	$('#menu li ul li').mouseenter(function(){
		var pos = $(this).position().top;
		$('#menu li ul')
			.animate({backgroundPosition:"(0 "+pos+"px)"},{duration:300});
	});
	
	$('#menu li ul').mouseleave(function(){
		$('#menu li ul')
			.animate({backgroundPosition:"(0 300px)"},{duration:300});
	});*/
	
	$("#pageflip").hover(function() { 
		$("#pageflip img , .msg_block").stop()
			.animate({ 
				width: '307px',
				height: '319px'
			}, 500);
		} , function() {
		$("#pageflip img").stop() 
			.animate({
				width: '100px',
				height: '102px'
			}, 220);
		$(".msg_block").stop() 
			.animate({
				width: '100px',
				height: '98px'
			}, 200); 
	});
	
	
	$('#menu ul.sub li').css( {backgroundPosition : "-140px 0"} );
	
	
	$('#menu li ul li').mouseenter(function(){
		$(this)
			.animate({backgroundPosition:"(0 0)"},{duration:300});
	}).mouseleave(function(){
		$(this)
			.animate({backgroundPosition:"(-140px 0)"},{duration:300});
	});
	
	
	
    if(doHomesMap){
        homesMap();
    }

    /*
     * Extend jQuery to include URL get variable parsing
     */
    $.extend({
      getUrlVars: function(){
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for(var i = 0; i < hashes.length; i++)
        {
          hash = hashes[i].split('=');
          vars.push(hash[0]);
          vars[hash[0]] = hash[1];
        }
        return vars;
      },
      getUrlVar: function(name){
        return $.getUrlVars()[name];
      }
    });
    //---------------------------------------------------



    //Retrieve get variables
    var currentPage = $.getUrlVar('currentPage');
    if(isUndefined(currentPage)){currentPage = "1";}

    var perpage = $.getUrlVar('perpage');
    if(isUndefined(perpage)){perpage = "9";}

    var GType = $.getUrlVar('GType');
    if(isUndefined(GType)){GType = "2";}

    var XSLT = $.getUrlVar('XSLT');
    if(isUndefined(XSLT)){XSLT = "-1";}

    var PriceOrder = $.getUrlVar('PriceOrder');
    if(isUndefined(PriceOrder)){PriceOrder = "Desc";}

    var Town = $.getUrlVar('Town');
	Town = unescape(Town);
    if(isUndefined(Town)){Town = "";}
    Town = Town.toLowerCase();
    if(Town == "enter+postcode+or+area" || Town == "enter postcode or area" || Town == "enter%20postcode%20or%20area"){
        Town = "";
    }

    var GlobalPropType = $.getUrlVar('GlobalPropType');
    if(isUndefined(GlobalPropType)){GlobalPropType = "";}

    var Bedrooms = $.getUrlVar('Bedrooms');
    if(isUndefined(Bedrooms)){Bedrooms = "";}

    var MinPrice = $.getUrlVar('MinPrice');
    if(isUndefined(MinPrice)){MinPrice = "";}

    var MaxPrice = $.getUrlVar('MaxPrice');
    if(isUndefined(MaxPrice)){MaxPrice = "";}

    var RentalPeriod = $.getUrlVar('RentalPeriod');
    if(isUndefined(RentalPeriod)){RentalPeriod = "1";}
    //-------------------------------------------
    


    //Do the search when the page first loads
    //searchProps(currentPage, perpage, GType, XSLT, PriceOrder, Town, GlobalPropType, Bedrooms, MinPrice, MaxPrice, RentalPeriod);
	if(location.pathname == searchPath){
		//updateResults();
		searchProps(currentPage, perpage, GType, XSLT, PriceOrder, Town, GlobalPropType, Bedrooms, MinPrice, MaxPrice, RentalPeriod, '');
	} 
	
	if(location.pathname == studentSearchPath){
		//updateResults();
		searchProps(currentPage, perpage, GType, XSLT, PriceOrder, Town, GlobalPropType, Bedrooms, MinPrice, MaxPrice, 4, 'STUDENT ACCOMODATION');
	}
    //----------------------------------------------------------------------------------------------------------------------------


    //Set the click action for the reorder links for the search
    $('#lowestPrice').click(function(){
        PriceOrder = "Asc";
        var Town = $("#Town").val();
        if(Town == "enter+postcode+or+area" || Town == "enter postcode or area" || Town == "enter%20postcode%20or%20area"){
            Town = "";
        }
        var GlobalPropType = $("#GlobalPropType").val();
        var Bedrooms = $("#Bedrooms").val();
        var MinPrice = $("#MinPrice").val();
        var MaxPrice = $("#MaxPrice").val();
        window.location.search = "?perpage="+perpage+"&GType="+GType+"&XSLT="+XSLT+"&PriceOrder="+PriceOrder+"&Town="+Town+"&GlobalPropType="+GlobalPropType+"&Bedrooms="+Bedrooms+"&MinPrice="+MinPrice+"&MaxPrice="+MaxPrice+"&RentalPeriod="+RentalPeriod;
    });
    $('#highestPrice').click(function(){
        PriceOrder = "Desc";
        if(Town == "enter+postcode+or+area" || Town == "enter postcode or area" || Town == "enter%20postcode%20or%20area"){
            Town = "";
        }
        var GlobalPropType = $("#GlobalPropType").val();
        var Bedrooms = $("#Bedrooms").val();
        var MinPrice = $("#MinPrice").val();
        var MaxPrice = $("#MaxPrice").val();
        window.location.search = "?perpage="+perpage+"&GType="+GType+"&XSLT="+XSLT+"&PriceOrder="+PriceOrder+"&Town="+Town+"&GlobalPropType="+GlobalPropType+"&Bedrooms="+Bedrooms+"&MinPrice="+MinPrice+"&MaxPrice="+MaxPrice+"&RentalPeriod="+RentalPeriod;
    });
    //------------------------------------------------------------------------------------------------------------------------------
    
    
    
    //Set the color of the selected search order
    if(PriceOrder == "Asc"){
        $('#lowestPrice').attr("class",'red');
    }
    if(PriceOrder == "Desc"){
        $('#highestPrice').attr("class",'red');
        $('#lowestPrice').attr("class",'');
    }
    //--------------------------------------------
    
    
    
    
    //Set the height of the container to 500 if empty or small
    if($('#propertyResults').height() < 500){
        $('#propertyResults').height(500);
    }
    //--------------------------------------------------------



    //Set the height of the description to 500 when the read more button is clicked
    var targetHeight = $('#descriptionCopy').height();
    targetHeight = targetHeight+"px";
    $("#readMore").toggle(function(){
      $("#descriptionHolder").animate({
            height: targetHeight
      }, 500, function(){ $("#readMore").html('Read Less')} );
    },function(){
      $("#descriptionHolder").animate({
            height: '220px'
      }, 500, function(){ $("#readMore").html('Read More<img src="images/img_sort_down.png" alt="Down" width="15" height="15" align="absmiddle"/>')} );
    }
	);
    //-----------------------------------------------------------------------------


	
	


});


/*
 * Check to see if argument is undefined
 *
 * Returns Boolean
 */
function isUndefined(x){
    return (x === void(0));
}



/*
 * Sets the pagination for the page
 */
function doPagination(numPages, currentPage, perpage, GType, XSLT, PriceOrder, Town, GlobalPropType, Bedrooms, MinPrice, MaxPrice, RentalPeriod, type){
    var pagination = document.getElementById("pagination");
    if(pagination != null){
        while(pagination.firstChild){
            pagination.removeChild(pagination.firstChild);
        }
        var newHTML = "<div class='pageLinkGroup'>";
        for(var i = 1; i <= numPages; i++){
//            if(i != 1 && (i - 1) % 17 == 0){
//                newHTML+= "</div><div class='pageLinkGroup'>";
//            }
            newHTML+= "<div class='pageLink";
            if(i == currentPage){
                newHTML+= "On";
            }
            newHTML+= "' onclick='searchProps("+i+", \""+perpage+"\", \""+GType+"\", \""+XSLT+"\", \""+PriceOrder+"\", \""+Town+"\", \""+GlobalPropType+"\", \""+Bedrooms+"\", \""+MinPrice+"\", \""+MaxPrice+"\", \""+RentalPeriod+"\", \""+type+"\");'>"+i+"</div>";
        }
        newHTML+= "</div>";
        pagination.innerHTML = newHTML;
    }
}

                         
                         
                         

/*
 * Searches database for matching properties
 */
function searchProps(currentPage, perpage, GType, XSLT, PriceOrder, Town, GlobalPropType, Bedrooms, MinPrice, MaxPrice, RentalPeriod, type){
	
	$('#preLoader').css('display','block');
	
    var resultsHTML = "";
	
	var stringArgs = 'op=search&perpage='+perpage+'&currentPage='+currentPage+'&GType='+GType+'&XSLT='+XSLT+'&PriceOrder='+PriceOrder+'&Town='+Town+'&GlobalPropType='+GlobalPropType+'&Bedrooms='+Bedrooms+'&MinPrice='+MinPrice+'&MaxPrice='+MaxPrice+'&RentalPeriod='+RentalPeriod+'&type='+type;
	
	//prompt("","phpScripts/get_properties_xml.php?"+stringArgs);
	
    $.ajax({
    type: "GET",
	url: "phpScripts/get_properties_xml.php",
	//url: "phpScripts/getproperties_io.php",
	dataType: 'xml',
	cache: true,
	data: {'perpage' : perpage, 'currentPage' : currentPage, 'GType' : GType, 'XSLT' : XSLT, 'PriceOrder' : PriceOrder, 'Town' : Town, 'GlobalPropType' : GlobalPropType, 'Bedrooms' : Bedrooms,  'MinPrice' : MinPrice, 'MaxPrice' : MaxPrice, 'RentalPeriod' : RentalPeriod, 'type' : type },
	success: function(xml){
	//		alert('response');
            $('#propertyResults').html("There were no properties found matching your search criteria");
            //Find the number of properties return and the number of pages required to display them
            //var numProperties = ($(xml).find('property').length);
            //var numPages = Math.ceil(numProperties / perpage);
            var numProperties = $(xml).find('properties').attr('totalProperties');
            //alert(numProperties);
			var numPages = Math.ceil(numProperties / perpage);
			
			var numPropertiesResult = ($(xml).find('property').length);
			if(numPropertiesResult<perpage){
				var numRows = Math.ceil(numPropertiesResult / 3);
			}else{
				var numRows = Math.ceil(perpage / 3);
			}
			var pageHeight = (360*numRows)+'px';
			//alert(pageHeight);
            //-------------------------------------------------------------------------------------
            
            
            
            //Insert Pagination
            doPagination(numPages, currentPage, perpage, GType, XSLT, PriceOrder, Town, GlobalPropType, Bedrooms, MinPrice, MaxPrice, RentalPeriod);
            //-------------------------------------------------------------------------------------
            
            
            //For each propery returned, output the result panel if the property is on the current page
            var count = 0;
            var panelNum = 0;
            $(xml).find('property').each(function(){
                count++;
                //if(Math.ceil(count / perpage) == currentPage){
                    panelNum++;
                    var propid = $(this).attr('id');
                    var ebid = $(this).attr('ebid');
                    var sold = $(this).attr('sold');
                    var priceval = $(this).attr('priceval');
                    var bedrooms = $(this).attr('bedrooms');
                    var bathrooms = $(this).attr('bathrooms');
                    var receptions = $(this).attr('receptions');
                    var photoID = $(this).attr('photoID');
                    var rentalperiod = $(this).attr('rentalperiod');
					var groupName = $(this).attr('groupName');
					var statusimage = $(this).attr('statusimage');
					var statuslabel = $(this).attr('statuslabel');
                    var sa1 = $(this).find('sa1').text();
                    var sa2 = $(this).find('sa2').text();
                    var twn = $(this).find('twn').text();
                    var cty = $(this).find('cty').text();
                    var pc = $(this).find('pc').text();
                    var ea_tel = $(this).find('ea_tel').text();
                    var photo = "http://data.dezrez.com/PictureResizer.ASP?PropertyID="+propid+"&PhotoID="+photoID+"&AgentID="+eaid+"&BranchID="+ebid+"&width=199&rotation=0";
                    var description = $(this).find('description4').text();
                    
                    resultsHTML += propResultHTML(panelNum, sa1, sa2, pc, priceval, photo, propid, groupName, bedrooms, description, bathrooms, receptions, ebid, rentalperiod, currentPage, perpage, GType, XSLT, PriceOrder, Town, GlobalPropType, Bedrooms, MinPrice, MaxPrice, RentalPeriod, statusimage, statuslabel);
                //}
				
				$('#propertyResults').css('height', pageHeight);
				 
                $('#propertyResults').html(resultsHTML);

				
                //GET IN TOUCH PANELS
                $(".hiddenDetails").hide();

                $(".btnGetInTouch").click(function(){
                    var holder = $(this).parent();
                    var panel = $(this).parent().parent();
                    var contact = panel.find(".hiddenDetails");
                    holder.fadeOut(function(){
                        contact.fadeIn();
                    });
                });

                $(".closer").click(function(){
                    var contact = $(this).parent();
                    var panel = $(this).parent().parent();
                    var back = panel.find(".searchResultContent");
                    contact.fadeOut(function(){
                            back.fadeIn();
                    });
                });

                var focusEl = document.getElementById("refineTypeBuy");
                if(focusEl != null){
                    focusEl.focus();
                }
                
                
            });
			//Hide preloader
			$('#preLoader').css('display','none');
			
			$('#viewAsList').attr("href", "liverpool_property_search.php?args"+stringArgs);
			$('#viewAsMap').attr("href", "liverpool_property_search_map.php?args"+stringArgs);                
        }//end success
    });
}


/*
 * Create the HTML panel for property details supplied by arguments
 */
function propResultHTML(panelNum, sa1, sa2, pc, priceval, photo, propid, groupName, bedrooms, description, bathrooms, receptions, ebid, rentalperiod, currentPage, perpage, GType, XSLT, PriceOrder, Town, GlobalPropType, Bedrooms, MinPrice, MaxPrice, RentalPeriod, statusimage, statuslabel){
    var HTML = "";
    
    if(panelNum % 3 == 0){
        HTML += '<div class="padRight">';
    }
    
    HTML += '<div class="searchResult">';
        HTML += '<div class="holderDiv"></div>';
        HTML += '<div class="searchResultContent">';
		 HTML += '<div id="resultHeader">';
            HTML += '<table class="titleBar" border="0" cellpadding="0" cellspacing="0">';
		HTML += '<tr>';
                    HTML += '<td colspan="2" class="addr">'+sa1+'</td>';
                HTML += '</tr>';
		HTML += '<tr>';
					HTML += '<td colspan="2">';
					HTML += '<table border="0" cellpadding="0" cellspacing="0">';
						HTML += '<tr>';
                    		HTML += '<td class="addr" style="padding:0 0 10px 0; width:100px;">'+sa2+' '+pc+'</td>';
                    		HTML += '<td class="price" align="right" style="padding:0 0 10px 0; width:100px;">&pound;'+priceval+'</td>';
						HTML += '</tr>';
					HTML += '</table>';
		HTML += '</td>';
	HTML += '</tr>';
    HTML += '</table>';
	HTML += '</div>';
            HTML += '<a href="property_details.php?id='+propid;
            HTML += '&currentPage='+currentPage+'&perpage='+perpage+'&GType='+GType+'&XSLT='+XSLT+'&PriceOrder='+PriceOrder+'&Town='+Town+'&GlobalPropType='+GlobalPropType+'&Bedrooms='+Bedrooms+'&MinPrice='+MinPrice+'&MaxPrice='+MaxPrice+'&RentalPeriod='+RentalPeriod+'"';
            HTML += '><img class="resultImg" src="'+photo+'" alt="" width="199" height="105"/></a>';
			if(statusimage!=''){
				HTML += '<img class="flashStatusResult" src="images/'+statusimage+'" alt="'+statuslabel+'" />';
			}
			HTML += '<div class="descriptionHolder">';
			HTML += '<a href="property_details.php?id='+propid;
            HTML += '&currentPage='+currentPage+'&perpage='+perpage+'&GType='+GType+'&XSLT='+XSLT+'&PriceOrder='+PriceOrder+'&Town='+Town+'&GlobalPropType='+GlobalPropType+'&Bedrooms='+Bedrooms+'&MinPrice='+MinPrice+'&MaxPrice='+MaxPrice+'&RentalPeriod='+RentalPeriod+'"';
            HTML += ' class="red"><strong>';
			if(bedrooms>0){
            	HTML += ''+bedrooms+' Bedroom';
			}
			HTML += ' '+groupName+'</strong></a>';
            HTML += '<p class="searchDesc">'+description+'</p>';
			HTML += '</div>';
            HTML += '<table class="roomTypes" border="0" cellpadding="0" cellspacing="0">';
                    HTML += '<tr>';
                            HTML += '<td class="nums">'; if(bedrooms>0){ HTML +=bedrooms+ 'x';}  HTML +='</td>';
                            HTML += '<td class="symbols">'; if(bedrooms>0){ HTML +='<img src="images/symbol_bed.gif" alt="'+bedrooms+' bedrooms" title="'+bedrooms+' bedrooms" width="33" height="18"/>';}  HTML +='</td>';
                            HTML += '<td class="nums">'; if(bathrooms>0){ HTML +=bathrooms+' x</td>';}
                            HTML += '<td class="symbols">'; if(bathrooms>0){ HTML +='<img src="images/symbol_bath.gif" alt="'+bathrooms+' bathroom"  title="'+bathrooms+' bathroom" width="20" height="18"/>';}  HTML +='</td>';
                            HTML += '<td class="nums">'; if(receptions>0){ HTML +=receptions+' x</td>';}
                            HTML += '<td class="symbols">'; if(receptions>0){ HTML +='<img src="images/symbol_sofa.gif" alt="'+receptions+' Living spaces" title="'+receptions+' Living spaces" width="32" height="16"/>';}  HTML +='</td>';
                    HTML += '</tr>';
            HTML += '</table>';
            HTML += '<a href="property_details.php?id='+propid;
            HTML += '&currentPage='+currentPage+'&perpage='+perpage+'&GType='+GType+'&XSLT='+XSLT+'&PriceOrder='+PriceOrder+'&Town='+Town+'&GlobalPropType='+GlobalPropType+'&Bedrooms='+Bedrooms+'&MinPrice='+MinPrice+'&MaxPrice='+MaxPrice+'&RentalPeriod='+RentalPeriod+'"';
            HTML += ' class="btnSearchResult">More Details</a>';
            HTML += '<a href="Javascript: return false;" class="btnGetInTouch">Get In Touch</a>';
        HTML += '</div>';    
    
        var office = getContactDetails(ebid, rentalperiod, propid);

        HTML += '<div class="hiddenDetails">';
            HTML += '<a href="Javascript: return false;" class="closer"><img src="images/btn_close_red.gif" alt="close" width="15" height="15" /></a>';
            HTML += '<div class="imgs">';
                HTML += ' <img src="images/img_get_in_touch.gif" alt="Get In Touch" width="180" height="51" />';
                HTML += ' <img src="'+office.contactImg+'" alt="Contact" width="126" height="108" />';
                HTML += '<br/><span class="red">'+office.contactName + ', ' + office.contactRole +'</span>';
            HTML += ' </div>';
            HTML += '<table class="newContactPanel" border="0" cellpadding="0" cellspacing="0">';
                HTML += '<tr>';
                    HTML += '<td>';
                        HTML += '<span class="red"><strong>Call My Team</strong></span>';
                        HTML += '<br/>'+office.contactTel+'';
                    HTML += '</td>';
                HTML += '</tr>';
                HTML += '<tr>';
                    HTML += '<td>';
                        HTML += '<a href="mailto:'+office.contactEmail+'" class="red"><strong>'+office.contactEmail+'</strong></a>';
                    HTML += '</td>';
                HTML += '</tr>';
            HTML += '</table>';
            var fwdAddr = sa1;
            var addrLen = fwdAddr.length;
            if(fwdAddr.charAt(addrLen - 1) == ','){
                fwdAddr = fwdAddr.substring(0, addrLen - 1);
                fwdAddr += " "+pc;
            }
            HTML += '<img class="btn" src="images/btn_req_view.gif" alt="Request A Viewing" width="150" height="23" onclick="makeRequest(this, \'view\', \''+fwdAddr+'\',  \''+office.contactEmail+'\', \''+office.contactTel+'\');"/>';
            HTML += '<img class="btn" src="images/btn_make_enq.gif" alt="Make an Enquiry" width="150" height="23" onclick="makeRequest(this, \'enquiry\', \''+fwdAddr+'\',  \''+office.contactEmail+'\', \''+office.contactTel+'\');"/>';
        HTML += '</div>';
        
    HTML += '</div>';


    if(panelNum % 3 == 0){
        HTML += '</div>';
    }

    return HTML;
}


function getContactDetails(ebid, rentalperiod, id){
    var office = new ContactOffice(ebid, rentalperiod, id);
    return office;
}


/*
 * Create a ContactOffice object from the supplied arguments
 */
function ContactOffice(ebid, rentalperiod, id){
    if(ebid==1710){
        this.contactImg = 'images/img_agent_logo.jpg';
        this.contactName = 'Venmore Auctions';
        this.contactTel = '0151 236 6746';
        this.contactEmail = 'auctions@venmores.co.uk';
        this.contactRole = 'Sales Manager';
    }
    if(rentalperiod<2){        
        if(ebid == 1533){
            this.contactImg = 'images/img_agent_jh.jpg';
            this.contactName = 'Joanna Hudson';
            this.contactEmail = 'city@venmores.co.uk';
			this.contactTel = '0151 236 4400';
			this.contactRole = 'Sales Manager';
        }
        if(ebid == 1616){
            this.contactImg = 'images/img_agent_sc.jpg';
            this.contactName = 'Sam Clothier';
            this.contactEmail = 'allerton@venmores.co.uk';
			this.contactTel = '0151 733 9000';
			this.contactRole = 'Sales Manager';
        }
    }
    if(rentalperiod>1){
        this.contactImg = 'images/img_agent_dk.jpg';
        this.contactName = 'Darren Kay';
        
        this.contactRole = 'Lettings Manager';
        if(ebid == 1533){this.contactEmail = 'city@venmores.co.uk'; this.contactTel = '0151 236 4400';}
        if(ebid == 1616){this.contactEmail = 'allerton@venmores.co.uk'; this.contactTel = '0151 734 6890';}
    }    
}

function updateResults(){
	//Set Vars
	var RentalPeriod = $('input:radio:checked').val();
	var Town = $("#Town").val();
	var aTown = Town.toLowerCase();
	if(aTown == "enter postcode or area"){
		Town = "";
	}
	var GlobalPropType = $("#GlobalPropType").val();
	var Bedrooms = $("#Bedrooms").val();
	var MinPrice = $("#MinPrice").val();
	var MaxPrice = $("#MaxPrice").val();

	var currentPage = $.getUrlVar('currentPage');
	if(isUndefined(currentPage)){currentPage = "1";}

	var perpage = $.getUrlVar('perpage');
	if(isUndefined(perpage)){perpage = "9";}

	var GType = $.getUrlVar('GType');
	if(isUndefined(GType)){GType = "2";}

	var XSLT = $.getUrlVar('XSLT');
	if(isUndefined(XSLT)){XSLT = "-1";}

	var PriceOrder = $.getUrlVar('PriceOrder');
	if(isUndefined(PriceOrder)){PriceOrder = "Desc";}
	
    if(location.pathname != searchPath){
        if(location.pathname == mapSearchPath){
            loadMarkers(RentalPeriod, Town, GlobalPropType, Bedrooms, MinPrice, MaxPrice, GType);
        }else{
            document.getElementById("refineForm").submit();
        }        
    }else{
		
        searchProps(1, perpage, GType, XSLT, PriceOrder, Town, GlobalPropType, Bedrooms, MinPrice, MaxPrice, RentalPeriod, '');

    }
    
}
