/* XHTML strict gets rid of target="blank", so we
convert all links with rel="newWindow" to pop up in new window */

function externalLinks() {

 if (!document.getElementsByTagName) return;
 var anchors = document.getElementsByTagName("a");
 for (var i=0; i<anchors.length; i++) {
   var anchor = anchors[i];
   if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "newWindow"){
     	anchor.target = "_blank";
    }
 }
}

function doCounty(state,table)
{	
	if(state != ""){		
		var countyReq = new Request({url: 'HomePage', method: 'GET', onSuccess: function(responseText, responseXML) {
    		document.forms['searchForm'].innerHTML=responseText;
    		setUpMultipickSelects();
		}}).send('state='+state+'&table='+table);
	}else{
		var countyOptions = document.forms['searchForm'].map_area.options;	
		for(var i = 0; i < countyOptions.length; i++)
		{
			countyOptions[i].selected = false;
		}
		countyOptions[0].selected = true;
		document.forms['searchForm'].map_area.disabled=true;
	}
}

function switchResIci(target){
	
	if(target=='mls'){
		$('mlsTab').className="active_tab";
		$('iciTab').className="inactive_tab";
	}else{
		$('mlsTab').className="inactive_tab";
		$('iciTab').className="active_tab";
	}
	var tableReq = new Request({url: 'HomePage', method: 'GET', onSuccess: function(responseText, responseXML) {
    		document.forms['searchForm'].innerHTML=responseText;
		}}).send('table='+target);
}

function switchTabs(target){
	if(target=='id'){
		$('idTab').className="active_tab";
		$('addressTab').className="inactive_tab";
		$('addressSearch').style.display="none";
		$('idSearch').style.display="";
	}else{
		$('idTab').className="inactive_tab";
		$('addressTab').className="active_tab";
		$('addressSearch').style.display="";
		$('idSearch').style.display="none";
	}
}

//Check if string is currency
var isCurrency_re = /^(?:\$\s*)?(?:(?:\d{0,3}(?:[, ]\d{0,3})*[, ])+\d{3}|\d+)(?:\.\d*)?(?:\s*\$)?$/;

function isCurrency (s) {

    return String(s).search (isCurrency_re) != -1
}

//validate currency fields for boards that have manual inputs

function validateForm(){

	minPrice = document.getElementById("min_price").value;
	maxPrice = document.getElementById("max_price").value;
	
	
	
	if((minPrice == "" || isCurrency(minPrice)) && (maxPrice == "" || isCurrency(maxPrice)) ){
	
		minPrice = minPrice.replace(",","");
		minPrice = minPrice.replace("$","");
		minPrice = minPrice.replace(" ","");
		maxPrice = maxPrice.replace(",","");
		maxPrice = maxPrice.replace("$","");
		maxPrice = maxPrice.replace(" ","");
		
		minPrice = parseInt(minPrice,10);
		maxPrice = parseInt(maxPrice,10);
		
		if( (!isNaN(minPrice) && !isNaN(maxPrice)) && (minPrice >= maxPrice)  ){
	
			alert("Minimum Price must be less than Maximum Price.");
			return false;
		}
		
		if(isNaN(minPrice)){ minPrice = ""; }
		if(isNaN(maxPrice)){ maxPrice = ""; }
		
		document.getElementById("min_price").value = minPrice;
		document.getElementById("max_price").value = maxPrice;
		
		return true;
		
	}else{
		alert("Please enter a valid currency amount.");
		return false;
	}
}

function validateAndFilter(){
	
	if(validateForm()){
		doRefresh();
		return false;
	}else{
		return false;
	}
}

function checkIntField(field, fieldName){
	
	val = parseInt(field.value,10);

	if(!isNaN(val)){
		return true;
	}else{
		alert("please enter a valid "+fieldName)
		return false;
	}
}

function checkEmptyField(field, fieldName){
	
	if(field.value != ""){
		return true;
	}else{
		alert("please enter a valid "+fieldName)
		return false;
	}
}

function submitMlsSearch(field, fieldName){
	
	if(checkIntField(field, fieldName)){
		field.form.action += "?id="+field.value;
		return true;
	}else{
		return false;
	}
}

//////////////////////////////////////////////////////////
//select field magnification on mouseover - uses mootools//
////////////////////////////////////////////////////////

var popupOpenDelay;
var popupCloseDelay;
var lastSelected;

function showSelectPopup(element){
	
	//delay this so we dont show the popup if the mouse briefly flies over target
	popupOpenDelay = setTimeout(function(){

		var scrollOffset = window.getScroll().y;
		var elementOffset = element.getPosition();
		var topOffset = elementOffset.y;
		var leftOffset = elementOffset.x;
		
		var optionCount = element.length;
		
		if(optionCount < 2) return; //don't bother
		
		var popup = document.createElement("div");
		
		popup.className = "selectPopup";		
		popup.style.top = topOffset  + "px";
		popup.style.left = leftOffset - 3 + "px";	
		
		var select = document.createElement("div");
		select.className = "selectOptionList";
		var maxHeight = window.getCoordinates().height - topOffset + scrollOffset - 50;
		
		
		var totalHeight = 16 * (optionCount) + 3; //line height * number of lines
		
		if(totalHeight < 80){
			
			select.style.height = "80px";
			
		}else if(totalHeight > maxHeight){
			
			select.style.height = maxHeight + "px";
			
		}else{
			select.style.height = totalHeight + "px";
		}
		
		var ul = document.createElement("ul");
		
		select.appendChild(ul);
		
		popup.appendChild(select);
		$(popup).setStyle('opacity',0);
		
		document.body.appendChild(popup);
		
		$(popup).set('tween', {duration: 250} ).tween('opacity', [0,1]);
			
		for(var i=0; i < optionCount; i++){
			
			var p = document.createElement("li");
			p.innerHTML = element.options[i].text;
			
			if(element.options[i].selected){
				p.className = "selected";
				lastSelected = p;
			}else{
				p.className = "";
			}
			
			
			if(i == 0){ //special logic for "search all" field
				
				p.onclick = function(evt){
					
					list = popup.getElements("li");
	                
	                var e=evt||window.event; //IE uses window.event instead
	                if(e.shiftKey) { return false; }
	                
	                if(this.className == "selected"){
              		return false;
              	}else{
              		this.className = "selected";
              		for(var i=1; i<list.length; i++){
              			list[i].className = "";
              		}
              	}
	                
	                copySelectedToOriginal(element,popup);
					return false;
	                
				};
				
			}else{
			
				p.onclick = function(evt){
	                
					list = popup.getElements("li");
					
					var e=evt||window.event; //IE uses window.event instead
	                
	                //allow user to shift-select multiple fields
	                if(e.shiftKey) {
	                    var start = list.indexOf(this);
	                    var end = list.indexOf(lastSelected); 
	
	                    for(i=Math.min(start,end);i<=Math.max(start,end);i++) {
	                     
	                        	list[i].className = lastSelected.className;
	                    }
	                }else{
					
	                	if(this.className == "selected"){
	                		this.className = "";
	                	}else{
	                		this.className = "selected";
	                	}			
	                }
	                
	                list[0].className = ""; //deselect "search all"
	                lastSelected = this;
	                copySelectedToOriginal(element,popup);
					return false;
				};
			}
			
			//prevent the text from being selected in IE
			p.onselectstart = function(){ return false; };
			
			ul.appendChild(p);
			
		}
		
		
		
		popup.addEvent('mouseenter', function() {
			clearTimeout(popupCloseDelay);
		  });
		
		popup.addEvent('mouseleave', function() {
			
			hideSelectPopup(element, popup);
		  });
		
		element.style.visibility = "hidden";
	
	},200);

}


function hideSelectPopup(element, popup){

	if(popup){
		
		//delay closing popup to compensate for user error
		popupCloseDelay = setTimeout(function(){
			$(popup).set('tween', {duration: 200, onComplete:  function(){
				
				element.style.visibility = "visible";
				document.body.removeChild(popup);
				popup = null;	
				}
			}).tween('opacity', [1,0]);
			
		},175);
	}
}


function copySelectedToOriginal(element, popup){
	
	var list = popup.getElements("li");

	for(var i=0; i < list.length; i++){
		
		element.options[i].selected = list[i].className;
	}
	//must explicitly fire the change event so the
	//original element's onchange functions get called
	element.fireEvent("change");
	
}

//sets up all mulipick selects to use the select hover popup, and fixes iOS bugs

function setUpMultipickSelects(){
	
	
	//disable this feature for IE6 and older, and iOS devices
	if( !(Browser.Engine.trident && parseInt(Browser.Engine.version) < 5) && !isIos() ){
		
		$$("select.multipick").addEvents({
			mouseenter: function() {
				showSelectPopup(this);
			},
			mouseleave: function(){
				clearTimeout(popupOpenDelay);
			}
		});
		
	}
	
	//fixes the problem where iOS devices would not fire
	//the onchange events on multiple select boxes, which made
	//auto population of map_area boxes and live count preview impossible


	if( isIos() ){

		$$("select.multipick").addEvent('blur', function(){
		
			this.fireEvent("change");
		});
	}
}

function doListingPhotoSlideshow(id,photocount,uniqueid,photoServer,board){

	var currImgSrc = document.getElementById(id).src;
	var photoURL = photoServer+'/photo_server.php?btnSubmit=GetPhoto&board='+board+'&name=';
	var failover = '&failover=portal_Blank.gif';
	var re = /\.L[0-9]+/;
	var num = currImgSrc.match(re)[0].substring(2);
	var currImgNum = parseInt(num,10);
	
	var listingPhotoArray = [];
	
	for(i = currImgNum; i < photocount; i++){

		var nextId;
		if(i < 10){
			nextId = '0'+i;
		}else{
			nextId = i;
		}	
		var newURL = uniqueid + '.L' + nextId + failover;
		
		listingPhotoArray.push(newURL);
	}
	
	var listingShow = new Slideshow("slidetest", listingPhotoArray, { captions: false, loader: false, controller: false, delay:750, duration:500, height: 105, width: 150, hu: photoURL });
}

//Return true if device is an iphone/ipad/ipod
function isIos(){
	return (
    	(navigator.platform.indexOf("iPhone") != -1) ||
    	(navigator.platform.indexOf("iPod") != -1)	||
		(navigator.platform.indexOf("iPad") != -1)
	);
}

/* global onload function. For page-specific onload
functionality, override doLoad in the page's 'headerIncludes' file */

window.addEvent('domready', function() {
	
	setUpMultipickSelects();
	externalLinks();
	doLoad();
	
});
	
function doLoad(){}
