var SORT_ORDER = 0;
var LOCATION_ID = 1;
var AVAILABLE_LIST_LABEL = 2;
var SELECTED_LIST_LABEL = 3;
var STATE_CODE = 4;
var DISPLAYABLE = 5;

function initLocations(propOrOffice){
	var radios;
	var hiddenLocations;
	if (propOrOffice == 'office') {
		radios = document.getElementsByName("advancedOfficeSearch:stateRadios");
	}
	else {
		radios = document.getElementsByName("advancedPropertySearch:stateRadios");
	}
	
	var hiddenObj = null;
	if (propOrOffice == 'office') {
		hiddenObj = document.getElementById("advancedOfficeSearch:selectedLocations");
		if(hiddenObj != null) {
			hiddenLocations = hiddenObj.value.split(",");
		}
	}  else {
		hiddenObj = document.getElementById("advancedPropertySearch:selectedLocations");
		if(hiddenObj != null) {
			hiddenLocations = hiddenObj.value.split(",");
		}
	}
	
	var selectedLocations = document.getElementById("userSelectedItems");
	var availableSelectBox = document.getElementById("availableLocations");   
	
	//First, load the values into the selected items
	if(hiddenLocations != null) {
		for(var j = 0;j< hiddenLocations.length;j++){
			var arrMatch = findLocationArray(hiddenLocations[j]);
			if(null != arrMatch && !containsValue('userSelectedItems', arrMatch[LOCATION_ID])){
				arrMatch[DISPLAYABLE] = false;
				addOption(selectedLocations, arrMatch[SELECTED_LIST_LABEL], arrMatch[LOCATION_ID]);
			}
		}
	}
	
	//Next, load the available locations, if state is selected
	if(radios != null) {
		var state = getCurrentState(radios);
		if(state != null){
		    removeAllAvailableOptions(availableSelectBox);
		    reloadAvailableOptions(state);
		}
	}
}

/**
 * Checks to see if the select box contains the value specified by theValue
 */
function containsValue(selectBoxId, theValue){
	var selectBox = document.getElementById(selectBoxId);
	if(selectBox == null) return false;
	for(var i = 0;i< selectBox.options.length;i++){
		if(selectBox.options[i].value == theValue){
			return true;
		}
	}
	return false;
}


function processLocations(propOrOffice) {
	var hiddenField;
	if (propOrOffice == 'office') {
		hiddenField = document.getElementById("advancedOfficeSearch:selectedLocations");
	}
	else {
		hiddenField = document.getElementById("advancedPropertySearch:selectedLocations");
	}

	
	//var selectedLocations = document.getElementById("advancedPropertySearch:userLocations");
	var selectedLocations = document.getElementById("userSelectedItems");
	var result = "";
	
	if(null != selectedLocations){
		for (i = 0; i < selectedLocations.options.length; i++) {
			var current = selectedLocations.options[i];
			result += current.value;
			if (i < (selectedLocations.options.length - 1)) {
				result += ",";
			}
		}
		for (i = 0; i < selectedLocations.options.length; i++) {
			var current = selectedLocations.options[i];
			current = null;
		}
		//alert("result: "+result);
		if (result == "") {
			result = " ";
		}
		hiddenField.value = result;
		//alert("result: " + result);
	}
}

function selectAll(selectBoxId, startIndex){
	var selectBox = document.getElementById(selectBoxId);
	if(null != selectBox){
		var selectBox = document.getElementById(selectBoxId);
		for(i=selectBox.options.length-1; i >= startIndex; i--){
			selectBox.options[i].selected=true;
		}
	}
}

function displayAvailableTowns(propOrOffice){
    var radios;
	if (propOrOffice == 'office') {
		radios = document.getElementsByName("advancedOfficeSearch:stateRadios");
	}
	else {
		radios = document.getElementsByName("advancedPropertySearch:stateRadios");
	}
    var availableSelectBox = document.getElementById("availableLocations");
    if(radios != null) {
	    var state = getCurrentState(radios);
	    if(state != null){
		    removeAllAvailableOptions(availableSelectBox);
		    reloadAvailableOptions(state);
	    }
	}
}

function NEMRemove(propOrOffice){
    var radios = null;
	if (propOrOffice == 'office') {
		radios = document.getElementsByName("advancedOfficeSearch:stateRadios");
	}
	else {
		radios = document.getElementsByName("advancedPropertySearch:stateRadios");
	}
	
	if(radios == null) return;
    var availableSelectBox = document.getElementById("availableLocations");
    var state = getCurrentState(radios);
    
    removeAllAvailableOptions(availableSelectBox);
    reloadAvailableOptions(state);
}

function NEMAdd(propOrOffice){
    var from = document.getElementById("availableLocations");
    //var to = document.getElementById("advancedPropertySearch:userLocations");
    var to = document.getElementById("userSelectedItems");
    var radios = null;
	if (propOrOffice == 'office') {
		radios = document.getElementsByName("advancedOfficeSearch:stateRadios");
	}
	else {
		radios = document.getElementsByName("advancedPropertySearch:stateRadios");
	}
    if(radios == null) return;
    var state = getCurrentState(radios);
    var selectedItems = new Array();
    var optionsToRemove = to.options;
    
    //get the currently selected values from availableSelectBox
    for(var i=from.options.length-1;i >= 0;i--){
        var current = from.options[i];
        if(current.selected && !isSelected(current.value)){
            var locationId = current.value;
            var relatedArray = findLocationArray(locationId);
            addOption(to, relatedArray[SELECTED_LIST_LABEL], relatedArray[LOCATION_ID]);
            from.remove(i);
        }
    }
    //loop over, to see if they exist in selected.  If not, add them.
    
    //Clear the available items and repopulate
    //removeAllAvailableOptions(availableSelectBox);
    
    //Reload all
    //reloadAvailableOptions();
}

function reloadAvailableOptions(selectedState){
    var availableSelectBox = document.getElementById("availableLocations");
    if(availableSelectBox == null) return;
    for(i=0;i < arr.length;i++){                    
        var current = arr[i][LOCATION_ID];
        var isStateSelected = arr[i][STATE_CODE] == selectedState;
        var selected = isSelected(current);
        
        if(selected){
            arr[i][DISPLAYABLE] = false;
        }else{
            if(isStateSelected){
                arr[i][DISPLAYABLE] = true;
                addOption(availableSelectBox, arr[i][AVAILABLE_LIST_LABEL], arr[i][LOCATION_ID]);
            }
        }                        
    }
}

function addOption(selectbox, text, value ){
    var optn = document.createElement("OPTION");
    optn.text = text;
    optn.value = value;
    selectbox.options.add(optn);
}

function removeSelectedOptions(from, to, propOrOffice){
    var radios;
	if (propOrOffice == 'office') {
		radios = document.getElementsByName("advancedOfficeSearch:stateRadios");
	}
	else {
		radios = document.getElementsByName("advancedPropertySearch:stateRadios");
	} 
    var fromSelectBox = document.getElementById(from);
    var toSelectBox = document.getElementById(to);                  
    var state = getCurrentState(radios);
    
    var reloadAvailableTowns = false;
    
    for(var i=fromSelectBox.options.length-1;i >= 0;i--){
        var locationId = fromSelectBox.options[i].value;
        var relatedArray = findLocationArray(locationId);
        if(fromSelectBox.options[i].selected){
            fromSelectBox.remove(i);
        }
        if(relatedArray[STATE_CODE] == state){
            reloadAvailableTowns =true;
        }
    }
    
    if(reloadAvailableTowns){
        removeAllAvailableOptions(toSelectBox);
        reloadAvailableOptions(state);
    }
}

function addSelectedOptions(from, to){
    var fromSelectBox = document.getElementById(from);
    var toSelectBox = document.getElementById(to);
    for(i=0;i < fromSelectBox.options.length; i++){
        if(fromSelectBox.options[i].selected){
            var locationArray = findLocationArray(fromSelectBox.options[i].value);
            addOption(toSelectBox, locationArray[SELECTED_LIST_LABEL], fromSelectBox.options[i].value);
            fromSelectBox.remove(i);
            --i;
        }
    }
}

function findLocationArray(locationId){
    for(i=0;i < arr.length;i++){
        if(arr[i][LOCATION_ID] == locationId){
            return arr[i];
        }
    }
}

function removeAllAvailableOptions(selectbox){
    var i;
    if(selectbox != null) {
	    for(i=selectbox.options.length-1;i>=0;i--){
	        selectbox.remove(i);
	    }
	}
}

function getCurrentState(radios){
    for (var i=0; i < radios.length; i++){
        if (radios[i].checked){
            return rad_val = radios[i].value;
        }
    }
    return "";
}

function isSelected(locationId){
    //var selectedSelectBox = document.getElementById("advancedPropertySearch:userLocations");
    var selectedSelectBox = document.getElementById("userSelectedItems");    
    var opts = selectedSelectBox.options;
    var found = false;
    for (var i=0; i < opts.length; i++){
        if(opts[i].value == locationId){
            return true;
        }
    }
    return false;
}

function validateAdvSearchForm() {
	var selectedTowns = document.getElementById('userSelectedItems');
	var selectedTownsTD = document.getElementById('selectedLocationsErrorDiv');
	var errorMsg = document.getElementById('advancedPropertySearch:errorMsg');
	if(selectedTowns == null) {
		return true;
	}
	var optionsLength = selectedTowns.options;
	var isValid = false;
	if(optionsLength.length > 0) {
		selectedTownsTD.className = 'nonErrorStyle';
		errorMsg.style.display= 'none';
		isValid = true;
	} else {
		selectedTownsTD.className = 'ErrorStyle';
		errorMsg.style.display= 'inline';
		isValid = false;
	}
	
	isValid = validatePropertyType() && isValid;
	return isValid;
}

var selectedAdvSearchTabIndex = 0;
function toggleAdvSearchTabs(tabIndex,tabCount) {
	var advSearchTabCount = 0;
	for(var i=0;i<tabCount;i++) {
		var tabObj = document.getElementById('tab' + i);
		if(tabObj == null) {
			continue;
		}
		
		if(i == selectedAdvSearchTabIndex) {
			deactivateTab(i,advSearchTabCount);
		}
		
		advSearchTabCount++;
	}
	activateTab(parseInt(tabIndex),advSearchTabCount);
	selectedAdvSearchTabIndex = tabIndex;
	
}

function disableOrEnableCollectionFields(flag) {
	var formName = "advancedPropertySearch";
	var fields = ['garageRB','resultsTypeRadios'];
	var objs = null;
	for(var i=0;i<fields.length;++i) {
		objs = document.getElementsByName(formName + ':' + fields[i]);
		for(var j=0;j<objs.length;++j)
			if(objs[j] != null) objs[j].disabled = flag;
	}
}

function disableOrEnableFormFields(flag) {
	var formName = "advancedPropertySearch";
	var fields = ['beds','baths','fireplaceCB','minGrossLivingArea','maxAge','showOpenHousesFirst','resultsTypeRadios'];
	var obj = null;
	for(var i=0;i<fields.length;++i) {
		obj = document.getElementById(formName + ':' + fields[i]);
		if(obj != null) obj.disabled = flag;
	}
}

function changePropertyType() {
	var propertyTypes = document.getElementsByName('advancedPropertySearch:propertyType');
	var flag = true;
	var landIndex = 3;
	var startIndex = 0;
	if(propertyTypes[0].tagName == 'TABLE') {
		landIndex = 4; 
		startIndex = 1;
	}
	for(var i=startIndex;i<propertyTypes.length - 1;++i) {
		if(propertyTypes[i].checked == true) {
			flag = false;
			break;
		}
	}
	if(propertyTypes[landIndex].checked == true) flag = flag && true;
	else flag = false;
	disableOrEnableFormFields(flag);
	disableOrEnableCollectionFields(flag);
}