// check if an item is in an array
Array.prototype.contains = function(obj) {
  var i = this.length;
  while (i--) {
    if (this[i] === obj) {
      return true;
    }
  }
  return false;
}

// check if arrays are equal
Array.prototype.compare = function(testArr) {
    if (this.length != testArr.length) return false;
    for (var i = 0; i < testArr.length; i++) {
        if (this[i].compare) { 
            if (!this[i].compare(testArr[i])) return false;
        }
        if (this[i] !== testArr[i]) return false;
    }
    return true;
}

////////////////////////////////////////////////////////////////////////////////////////////

// declare space slide element so it's available here
var mySlide = [];

// set a flag if this is the initial load
firstload = true;

// selected categories, cities & tags arrays
var allcities = [];			    	
var selectedcities = [];
var selectedcats = [];										
var selectedspaces = [];								
var selectedtags = [];

function resetcities(){

	var citylinks = $$(".propertyCities").getElements("a");
	var temp = citylinks.pop(); // mootools returns a two dimensional array so we need the temp array
	
	allcities = [];			    	
	selectedcities = [];	
	
	for (var i=0; i < temp.length; i++) {
		allcities.push(temp[i].get('rel'));
		selectedcities.push(temp[i].get('rel'));
	}	
	
}	

function resetspaces(){

	var spacelinks = $$(".spaces").getElements("a");
	var temp = spacelinks.pop(); // mootools returns a two dimensional array so we need the temp array
	
	allspaces = [];			    	
	selectedspaces = [];	
	
	for (var i=0; i < temp.length; i++) {
		allspaces.push(temp[i].get('rel'));
		selectedspaces.push(temp[i].get('rel'));
	}	
	
}	
			    	
function addcitytoarray(selectedcity){
	// add categories to the array		
	for (var i=0; i < allcities.length; i++) {
			if (allcities[i] == selectedcity){
				selectedcities.splice(i,0,selectedcity);
	  		}else {
	  			// do nothing
	  		}
	  	}
}

function removecityfromarray(existingcity){
	// remove categories from the array
	for (var i=0; i < selectedcities.length; i++) {
			if (selectedcities[i] == existingcity){
				selectedcities.splice(i,1);
	  		}else {
	  			// do nothing
	  		}
	  	}
	  				
}

function addcattoarray(selectedcategory){
	// add categories to the array
	selectedcats.push(selectedcategory);

}

function removecatfromarray(existingcategory){
	// remove categories from the array
	for (var i=0; i < selectedcats.length; i++) {
		if (selectedcats[i] == existingcategory){
			selectedcats.splice(i,1);
  		} else {
	  			// do nothing
	  		}
  	}

}

function addspacetoarray(selectedspace){
	// add spaces to the array
	selectedspaces.push(selectedspace);
	
}

function removespacefromarray(existingspace){
	// remove spaces from the array
	for (var i=0; i < selectedspaces.length; i++) {
		if (selectedspaces[i] == existingspace){
			selectedspaces.splice(i,1);
  		} else {
	  			// do nothing
	  		}
  	}

}

function addtagtoarray(selectedtag){
	// add tags to the array
	selectedtags.push(selectedtag);
	
}

function removetagfromarray(existingtag){
	// remove tags from the array
	for (var i=0; i < selectedtags.length; i++) {
		if (selectedtags[i] == existingtag){
			selectedtags.splice(i,1);
  		} else {
	  			// do nothing
	  		}
  	}

}

var allselectedcities = false;
	
function selectallcities(){
	
	var allcitieslink = document.getElementById('allcities');
	
	if(allselectedcities == false){
    	allcitieslink.innerHTML = 'deselect all';
    	allselectedcities = true;
	} else {
    	allcitieslink.innerHTML = 'select all';
    	allselectedcities = false;
	}

}

var allselectedcategories = false;

function selectallcategories(){

	var allcategorieslink = document.getElementById('allcategories');
		
	if(allselectedcategories == false){
    	allcategorieslink.innerHTML = 'deselect all';
    	allselectedcategories = true;
	} else {
    	allcategorieslink.innerHTML = 'select all';
    	allselectedcategories = false;
	}

}

////////////////////////////////////////////////////////////////////////////////////////////

// Custom SWFAddress and Ajax handling

function getTransport() {
    if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        try {
            return new ActiveXObject('Msxml2.XMLHTTP');
        } catch(e) {
            return new ActiveXObject('Microsoft.XMLHTTP');
        }
    }
}

////////////////////////////////////////////////////////////////////////////////////////////

// update the content
function updateChange(xhr) {
    if (xhr.readyState == 4) {
        if (xhr.status == 200) {
            var content = document.getElementById('result');
            content.innerHTML = xhr.responseText;
			$('browsecta').removeClass('loading'); // remove loading animation
            //this is where to add a transition if wanted
        } else {
			$('browsecta').removeClass('loading'); // remove loading animation
            //'Error: ' + xhr.status + ' probably from clicking too fast.'
        }
    }
}

////////////////////////////////////////////////////////////////////////////////////////////

function handleChange(event) {
	// grab the hash and split out the values to individual arrays
    var swfaddressvalue = event.path.substring(1);	
    
    var myparams = [];
    if(swfaddressvalue != ""){
    
    	myparams = swfaddressvalue.split("&");
    
	    var ajaxstate = myparams[0].slice(5);
	    var opencats = myparams[1].slice(6);
	    var opencities = myparams[2].slice(9);
	    var opentags = myparams[3].slice(6);
	    var openpropertytype = myparams[4].slice(13);
	    var openspaces = myparams[5].slice(15);  
	    
	    // on cold load preserve the array
	    
	    var opencatsarray = [];
	    if (opencats != "" && opencats != "residential properties" && opencats != "commercial properties"){
	    	opencatsarray = opencats.split(",");
	    	selectedcats = opencats.split(",");
	    } else {
	    	opencats = "";
	    }
	    
	    if (opencats == document.getElementById('allcategories').get('rel')){
	    	allselectedcategories = false;
	    	selectallcategories();
	    }
	    
	    var opencitiesarray = [];
	    if (opencities != ""){
	    	opencitiesarray = opencities.split(",");
	    	selectedcities = opencitiesarray;
	    } else {
	    	resetcities();
	    }
	    
	    if (opencities == allcities || (opencities == 'all' && opencities.length > 0)){
    		allselectedcities = false;
	    	selectallcities();
	    } 
	    
	    var opentagsarray = [];
	    if (opentags != ""){
	    	opentagsarray = opentags.split("+");
	    		selectedtags = opentagsarray;
	    } else {
	    	opentags = "";
	    }
	    
	    var openspacesarray = [];
	    if (openspaces != ""){
	    	openspacesarray = openspaces.split(",");
	    	selectedspaces = openspacesarray;
	    } else {
	    	openspaces = "";
	    }
	    
    } else {
    	myparams = "";
		ajaxstate = false;
    }

		// update property styles selected state
		$$(".propertyStyles").each(function(container){
			var links = container.getElements("a");		    		
				
				if(opencatsarray){
					for (var i=0; i < links.length; i++) {			
						if (links[i].hasClass('selected') && !opencatsarray.contains(links[i].get('rel'))){
							links[i].removeClass('selected');
							removecatfromarray(links[i].get('rel'));
				  		} else if (!links[i].hasClass('selected') && opencatsarray.contains(links[i].get('rel'))){
							links[i].addClass('selected');
				  		} else {
				  			// nothing to see here
				  		}
				  	}
			  	} else {
						links.removeClass('selected'); // nothing selected so remove them all
						selectedcats = [];
			  	}
			  	
		});
				
		// update property cities selected state
		$$(".propertyCities").each(function(container){
			var links = container.getElements("a");
	    
	    	// if nothing is selected update the array to contain all cities
	    	// necessary because we use negation cases
		    if (opencities == ""){
		    	for (var i=0; i < links.length; i++) {
		    		opencitiesarray.push(links[i].get('rel'));
		    	}
		    }
				
				if(opencitiesarray){			
					for (i=0; i < links.length; i++) {			
						if (links[i].hasClass('selected') && opencitiesarray.contains(links[i].get('rel'))){
							links[i].removeClass('selected');
				  		} else if (!links[i].hasClass('selected') && !opencitiesarray.contains(links[i].get('rel'))){
							links[i].addClass('selected');
				  		} else {
				  			// nothing to see here
				  		}
				  	}
			  	} else {
						links.removeClass('selected'); // nothing selected so remove them all
						resetcities();
			  	}
		});
				
		// update property tags selected state
		$$(".tags").each(function(container){
			var links = container.getElements("a");
				
				if(opentagsarray){
					for (var i=0; i < links.length; i++) {
						if (links[i].hasClass('selected') && !opentagsarray.contains(links[i].get('rel'))){
							links[i].removeClass('selected');
							removetagfromarray(links[i].get('rel'));
				  		} else if (opentagsarray.contains(links[i].get('rel'))){
							links[i].addClass('selected');
				  		} else {
				  			// nothing to see here
				  		}
				  	}
			  	} else {
						links.removeClass('selected'); // nothing selected so remove them all
						selectedtags = [];
			  	}
		});
				
		// update property space selected state
		$$(".spaces").each(function(container){
			var links = container.getElements("a");
			var attributecontainer = $$(".tags").getElements("a");
				
				if(openspacesarray){
					for (var i=0; i < links.length; i++) {
						if (links[i].hasClass('current') && !openspacesarray.contains(links[i].get('rel'))){
							links[i].removeClass('current');
							removespacefromarray(links[i].get('rel'));
							// slide out empty attributes nav
							$$(".tags").each(function(slider){
								myFx = new Fx.Slide(slider, { duration: 200 });
								myFx.hide();							
							});
				  		} else if (openspacesarray.contains(links[i].get('rel'))){
							links[i].addClass('current');
				  		} else {
				  			// nothing to see here
				  		}
				  	}
			  	} else {
						links.removeClass('current'); // nothing selected so remove them all
						
						// slide out empty attributes nav
						$$(".tags").each(function(slider){
							myFx = new Fx.Slide(slider, { duration: 200 });
							myFx.hide();							
						});
						
			  	}
	
		});

	//////////////////////////////////

    var index, rel, links = document.getElementsByTagName('a'), path = event.path;
   
    if (path.substr(path.length - 1) != '/') {
    	path += '/';
    }
   
    var parameters = '';
    for (var p in event.parameters) {
        parameters += '&' + p + '=' + event.parameters[p];
    }
    
    $('browsecta').addClass('loading');
    
    var xhr = getTransport();
    xhr.onreadystatechange = function() {
        updateChange(xhr);
    }
    
    // grab the domain and set the base path to fix cross domain issues
    if(window.location.host == 'homeshoothome.net'){
    	var basepath = 'homeshoothome.net';
    } else if(window.location.host == 'homeshoothome.com'){
    	var basepath = 'homeshoothome.com';
    } else {
    	//this is not a recognized domain
    }
    
    if(ajaxstate == 'true'){
    	xhr.open('get', 'http://' + basepath + '/wp-content/themes/hsh/ajaxproperties.php?' + swfaddressvalue + parameters, true);
    	xhr.send('');
    } else if (ajaxstate == false && firstload == false){
		window.location.reload();
		$('browsecta').removeClass('loading'); // remove loading animation
    } else {
		// load the default content
		$('browsecta').removeClass('loading'); // remove loading animation
	}
    
	return false;
}

////////////////////////////////////////////////////////////////////////////////////////////

SWFAddress.addEventListener(SWFAddressEvent.CHANGE, handleChange);

////////////////////////////////////////////////////////////////////////////////////////////
