var emptyCallBack = function() {
    return true;
};

function setIndustry(id) {
    subindustrylist.setSelectedIndustryId(id, emptyCallBack);
}

function setSubIndustry(id) {
    subindustrylist.setSelectedSubIndustryId(id, emptyCallBack);
}

function setCity(id) {
    citylist.setSelectedCityId(id, emptyCallBack);
}

//  --------------------------------
//      Job posting form functions
//  --------------------------------

var updateSubIndustryChoice = function() {
    var selectedIndustry = dwr.util.getValue('industry_choice');
    subindustrylist.getSubIndustriesByIndustry(selectedIndustry, updateSubIndustryChoiceCallback);
};

var updateSubIndustryChoiceCallback = function(data) {
    dwr.util.removeAllOptions('subIndustry_choice');
    dwr.util.addOptions('subIndustry_choice', [{id: -1, name: ''}], 'id', 'name');
    dwr.util.addOptions('subIndustry_choice', data, 'id', 'name');
};

var addIndustrySubIndustryPair = function(advertId) {
    showLoading('industries_list');
    var selectedIndustry = dwr.util.getValue('industry_choice');
    var selectedSubIndustry = dwr.util.getValue('subIndustry_choice');
    var callback = renderIndustriesCallback(advertId);
    commonRemoteIndustry.addIndustrySubIndustryPair(advertId, selectedIndustry, selectedSubIndustry, callback);
};

var removeIndustrySubIndustryPair = function(advertId, pairId) {
    showLoading('industries_list');
    var callback = renderIndustriesCallback(advertId);
    commonRemoteIndustry.removeIndustrySubIndustryPair(advertId, pairId, callback);
};

var clearIndustrySubIndustryPairs = function(advertId) {
    showLoading('industries_list');
    var callback = renderIndustriesCallback(advertId);
    commonRemoteIndustry.clearIndustrySubIndustryPairs(advertId, callback);
};

var initIndustryPairs = function(advertId) {
    var industries = $('industries');
    var subIndustries = $('subIndustries');
    var industryIds = getOptionsValues(industries);
    var subIndustryIds = getOptionsValues(subIndustries);
    var callback = renderIndustriesCallback(advertId);
    commonRemoteIndustry.initIndustryPairs(advertId, industryIds, subIndustryIds, callback);
};

var renderIndustriesCallback = function(advertId) {
    return function(data) {
        dwr.util.setValue('industries_list', dwr.util.unescapeHtml(data));
        commonRemoteIndustry.getIndustryPairs(advertId, setIndustryPairsCallback);
    };
};

var setIndustryPairsCallback = function(data) {
    dwr.util.removeAllOptions('industries');
    dwr.util.removeAllOptions('subIndustries');
    for (var i = 0; i < data.length; i++) {
        var pair = data[i];
        dwr.util.addOptions('industries', [pair.industry], 'id', 'name');
        dwr.util.addOptions('subIndustries', [pair.subIndustry], 'id', 'name');
    }
    var industries = $('industries');
    var subIndustries = $('subIndustries');
    selectAllOptions(industries);
    selectAllOptions(subIndustries);
    hideLoading('industries_list');
};

var selectAllOptions = function(selectInput) {
    var selectedOptions = selectInput.options;
    for (var i = 0; i < selectedOptions.length; i++) {
        selectedOptions[i].selected = true;
    }
};

var getOptionsValues = function(selectInput) {
    var selectOptions = selectInput.options;
    var optionsValues = new Array();
    for (var i = 0; i < selectOptions.length; i++) {
        optionsValues.push(selectOptions[i].value);
    }
    return optionsValues;
};


var getSelectedOptionValue = function(selectInput) {
    var selectOptions = selectInput.options;
    var selectedIndex = selectInput.selectedIndex;
    return selectOptions[selectedIndex].value;
};

//  --------------------------------
//      End
//  --------------------------------

function updateSubIndustries(industry) {
    subindustrylist.setSelectedIndustryId(industry, emptyCallBack);
    subindustrylist.getSubIndustriesByIndustry(dwr.util.getValue('industries'), createSubIndustriesList);
}

function createSubIndustriesList(data) {
    dwr.util.removeAllOptions('subIndustries');
    dwr.util.addOptions('subIndustries', [{id: -1, name: ''}], 'id', 'name');
    dwr.util.addOptions('subIndustries', data, 'id', 'name');
}

function updateRegions(country) {
    regionlist.setSelectedCountry(country, emptyCallBack);
    regionlist.getRegionsByCountry(dwr.util.getValue('countries'), createRegionsList);
}

function createRegionsList(data) {
    dwr.util.removeAllOptions('regions');
    dwr.util.addOptions('regions', [{id: -1, name: ''}], 'id', 'name');
    dwr.util.addOptions('regions', data, 'id', 'name');
}

function updateCities(region) {
    citylist.setSelectedRegionId(region, emptyCallBack);
    citylist.getCitiesByRegion(dwr.util.getValue('regions'), createCitiesList);
}

function createCitiesList(data) {
    dwr.util.removeAllOptions('cities');
    dwr.util.addOptions('cities', [{id: -1, name: ''}], 'id', 'name');
    dwr.util.addOptions('cities', data, 'id', 'name');
}

function updateDesiredRegions() {

    var selected = new Array();
    var desiredCountries = document.getElementById("desiredCountries");

    for (var i = 0; i < desiredCountries.options.length; i++)
        if (desiredCountries.options[i].selected)
            selected.push(desiredCountries.options[i].value);

    regionlist.getRegionsByCountries(selected, createDesiredRegionsList);
}

function createDesiredRegionsList(data) {
    dwr.util.removeAllOptions('desiredRegions');
    dwr.util.addOptions('desiredRegions', ['']);
    dwr.util.addOptions('desiredRegions', data, 'id');
}

function updateDesiredCities() {

    var selected = new Array();
    var desiredRegions = document.getElementById("desiredRegions");

    for (var i = 0; i < desiredRegions.options.length; i++)
        if (desiredRegions.options[i].selected)
            selected.push(desiredRegions.options[i].value);

    citylist.getCitiesByRegions(selected, createDesiredCitiesList);
}

function createDesiredCitiesList(data) {
    dwr.util.removeAllOptions('desiredCities');
    dwr.util.addOptions('desiredCities', ['']);
    dwr.util.addOptions('desiredCities', data, 'id');
}

var selectedList;
var availableList;
var domainTextInput;

function createListObjects() {
    availableList = document.getElementById("registeredEnterprises");
    selectedList = document.getElementById("blockedEnterprises");
    domainTextInput = document.getElementById("addEnterpriseDomain");
}

function delAttribute()
{
    var selIndex = selectedList.selectedIndex;
    if (selIndex < 0)
        return;

    enterprisesBlocking.removeEnterprise(selectedList.options[selIndex].value, emptyCallBack);

    availableList.appendChild(selectedList.options.item(selIndex))
    selectNone(selectedList, availableList);
    setSize(availableList, selectedList);


}

function addAttribute()
{
    var addIndex = availableList.selectedIndex;
    if (addIndex < 0) {
        return;
    }

    enterprisesBlocking.addEnterprise(availableList.options[addIndex].value, emptyCallBack);

    selectedList.appendChild(availableList.options.item(addIndex));
    selectNone(selectedList, availableList);
    setSize(selectedList, availableList);
    selectedList.focus();
}

function delAll() {
    var len = selectedList.length - 1;
    for (var i = len; i >= 0; i--) {
        availableList.appendChild(selectedList.item(i));
    }
    selectNone(selectedList, availableList);
    setSize(selectedList, availableList);
    enterprisesBlocking.removeAll(emptyCallBack);
}

function selectAllBlocked() {
    var len = selectedList.length - 1;
    for (var i = len; i >= 0; i--) {
        selectedList.item(i).selected = true;
    }
}

function selectNone(list1, list2) {
    list1.selectedIndex = -1;
    list2.selectedIndex = -1;
    addIndex = -1;
    selIndex = -1;
}

function setSize(list1, list2) {
    list1.size = getSize(list1);
    list2.size = getSize(list2);
}

function getSize(list) {
    /* Mozilla ignores whitespace, IE doesn't - count the elements in the list */
    var len = list.childNodes.length;
    var nsLen = 0;
    //nodeType returns 1 for elements
    for (i = 0; i < len; i++) {
        if (list.childNodes.item(i).nodeType == 1)
            nsLen++;
    }
    if (nsLen < 2)
        return 2;
    else
        return nsLen;
}

function showSelected() {
    var optionList = document.getElementById("selectedOptions").options;
    var data = '';
    var len = optionList.length;
    for (i = 0; i < len; i++) {
        if (i > 0)
            data += ',';
        data += optionList.item(i).value;
    }
    alert(data);
}

function addDomain() {
    if (domainTextInput.value != '') {
        var option = window.document.createElement("OPTION") ;

        enterprisesBlocking.addEnterprise(domainTextInput.value, emptyCallBack);
        selectedList.options.add(option);
        option.text = domainTextInput.value;
        option.value = domainTextInput.value;
        selectNone(selectedList, availableList);
        setSize(selectedList, availableList);
        selectedList.focus();
    }
}

var selectJobType = function(elementsName) {
    var name = 'jobTimeType';
    if (typeof(elementsName) != 'undefined' && elementsName != '') {
        name = elementsName;
    }
    var jobTypes = document.getElementsByName(name);
    for (var i = 0; i < jobTypes.length; i++) {
        if (jobTypes[i].checked) {
            jobTypes[i].click();
            break;
        }
    }
};

var updateSalaryRanges = function(sender) {
    var annual = $('annualSalaryRange');
    var daily = $('dailySalaryRange');
    var hourly = $('hourlySalaryRange');
    var any = $('jobTimeType.any');
    var consultant = $('jobTimeType.consultant');
    var intern = $('jobTimeType.internship');

    if (annual && daily && hourly) {

        if (sender == 'annual') {
            if (annual.selectedIndex > 0)
            {
                daily.selectedIndex = 0;
                hourly.selectedIndex = 0;
                if (consultant.checked || intern.checked) {
                    any.checked = true;
                }
            }
        }
        else if (sender == 'daily') {
            if (daily.selectedIndex > 0) {
                annual.selectedIndex = 0;
                hourly.selectedIndex = 0;
                if (intern.checked) {
                    any.checked = true;
                }
            }
        }
        else if (sender == 'hourly') {
            if (hourly.selectedIndex > 0) {
                daily.selectedIndex = 0;
                annual.selectedIndex = 0;
                if (intern.checked) {
                    any.checked = true;
                }
            }
        }
        else if (sender == 'consultant') {
            if (annual.selectedIndex > 0) {
                annual.selectedIndex = 0;
            }
            annual.disabled = true;
            daily.disabled = false;
            hourly.disabled = false;
        }
        else if (sender == 'internship') {
            if (annual.selectedIndex > 0) {
                annual.selectedIndex = 0;
            }
            annual.disabled = true;
            if (daily.selectedIndex > 0) {
                daily.selectedIndex = 0;
            }
            daily.disabled = true;
            if (hourly.selectedIndex > 0) {
                hourly.selectedIndex = 0;
            }
            hourly.disabled = true;
        }
        else if (sender == 'any' || sender == 'temporary') {
            annual.disabled = false;
            daily.disabled = false;
            hourly.disabled = false;
        }
        else if (sender == 'part_time' || sender == 'full_time') {
            annual.disabled = false;
            if (daily.selectedIndex > 0) {
                daily.selectedIndex = 0;
            }
            daily.disabled = true;
            if (hourly.selectedIndex > 0) {
                hourly.selectedIndex = 0;
            }
            hourly.disabled = true;
        }
    }
};

var advancedOptionsOn = false;
var emailOptionsOn = false;

var prefs = ['byPhone', 'byFax', 'byMail', 'byEmail'];

var swtchAdvancedOptions = function(elementId) {

    advancedOptionsOn = $('byQual').checked;
    emailOptionsOn = $('byEmail').checked || $('byQual').checked;

    if (advancedOptionsOn) {
        $('webmailerOptions').style.display = '';
        $('emailOptions').style.display = '';
        $('filterOptions').style.display = '';
        $('anonymousOptions').style.display = '';
    }
    else {
        $('webmailerOptions').style.display = 'none';
        $('emailOptions').style.display = 'none';
        $('filterOptions').style.display = 'none';
        $('anonymousOptions').style.display = 'none';
    }

    if (emailOptionsOn) {
        $('emailOptions').style.display = '';
    }
    else {
        $('emailOptions').style.display = 'none';
    }
};

var anonymizePosting = function(elementId) {
    if (elementId == 'anonymous') {
        if ($('anonymous').checked && $('byQual').checked) {
            for (var i = 0; i < prefs.length; i++) {
                $(prefs[i]).checked = false;
            }
        }
    }
    else {
        var prefsChecked = false;
        for (var i = 0; i < prefs.length; i++) {
            if ($(prefs[i]).checked) {
                prefsChecked = true;
                break;
            }
        }
        if (prefsChecked) {
            $('anonymous').checked = false;
        }
    }
};

var setUploadIndex = function(field, index) {
    var uploadIndexField = document.createElement('input');
    uploadIndexField.setAttribute('type', 'hidden');
    uploadIndexField.setAttribute('name', field);
    uploadIndexField.setAttribute('value', index);

    var firstDocForm = document.getElementsByTagName('form')[0];
    firstDocForm.appendChild(uploadIndexField);
};

var getFileName = function(filePath) {
    var result = '';
    if (typeof(filePath) != 'undefined') {
        var cleanPath = filePath.replace(/\\/g, '/');
        var pathTokens = cleanPath.split('/');
        if (pathTokens.length > 0) {
            result = pathTokens[pathTokens.length - 1];
        }
    }

    return result;
};

