// vim:set ts=4 sw=4 sts=4 foldmethod=marker syntax=javascript:
/* JS related to displaying and allowing user to choose a school
 * author: Michael Chen
 * author: Mark Jen
 *
 *
 * NOTE 9/3/08, MK: This file was moved to /edit_profile/schools.js and is
 * currently still under development as part of the new Profile page rewrite.
 * Since it turned out that Search was using this file too, I'm putting a copy
 * of the file back in its original location.
 * As soon as the new Profile page is live, this file (school_info.js) should not
 * be used anymore and instead we should either reference to the new file OR
 * extract its functionality that's been used for Search
 * @requires tagged/util/domMethods.js -  need display()
 * @requires tagged/util/hintinput.js - typeahead provides hinting
 */
TAGGED.namespace("profile.school_info");

/********************************
 * constants
 ********************************/

TAGGED.profile.school_info.countries = [{code:"US", name : "United States"},
              {code:"AU", name : "Australia"},
              {code:"CA", name : "Canada"},
              {code:"GB", name : "United Kingdom"},
              {code:"IE", name : "Ireland"},
              {code:"NZ", name : "New Zealand"}];

//array of states for the supported countries, might need to remove some of the special districts
//storing the states here to save 1 ajax call since states don't change
TAGGED.profile.school_info.states =   {"US" : [{code : -1, name : "&nbsp;"},{code:"Alabama",name:"Alabama"},{code:"Alaska",name:"Alaska"},{code:"Arizona",name:"Arizona"},{code:"Arkansas",name:"Arkansas"},{code:"California",name:"California"},{code:"Colorado",name:"Colorado"},{code:"Connecticut",name:"Connecticut"},{code:"Delaware",name:"Delaware"},{code:"District of Columbia",name:"District of Columbia"},{code:"Florida",name:"Florida"},{code:"Georgia",name:"Georgia"},{code:"Hawaii",name:"Hawaii"},{code:"Idaho",name:"Idaho"},{code:"Illinois",name:"Illinois"},{code:"Indiana",name:"Indiana"},{code:"Iowa",name:"Iowa"},{code:"Kansas",name:"Kansas"},{code:"Kentucky",name:"Kentucky"},{code:"Louisiana",name:"Louisiana"},{code:"Maine",name:"Maine"},{code:"Maryland",name:"Maryland"},{code:"Massachusetts",name:"Massachusetts"},{code:"Michigan",name:"Michigan"},{code:"Minnesota",name:"Minnesota"},{code:"Mississippi",name:"Mississippi"},{code:"Missouri",name:"Missouri"},{code:"Montana",name:"Montana"},{code:"Nebraska",name:"Nebraska"},{code:"Nevada",name:"Nevada"},{code:"New Hampshire",name:"New Hampshire"},{code:"New Jersey",name:"New Jersey"},{code:"New Mexico",name:"New Mexico"},{code:"New York",name:"New York"},{code:"North Carolina",name:"North Carolina"},{code:"North Dakota",name:"North Dakota"},{code:"Ohio",name:"Ohio"},{code:"Oklahoma",name:"Oklahoma"},{code:"Oregon",name:"Oregon"},{code:"Pennsylvania",name:"Pennsylvania"},{code:"Rhode Island",name:"Rhode Island"},{code:"South Carolina",name:"South Carolina"},{code:"South Dakota",name:"South Dakota"},{code:"Tennessee",name:"Tennessee"},{code:"Texas",name:"Texas"},{code:"Utah",name:"Utah"},{code:"Vermont",name:"Vermont"},{code:"Virginia",name:"Virginia"},{code:"Washington",name:"Washington"},{code:"West Virginia",name:"West Virginia"},{code:"Wisconsin",name:"Wisconsin"},{code:"Wyoming",name:"Wyoming"}],
               "AU" : [{code : -1, name : "&nbsp;"},{code:"Australian Capital Territory", name: "Australian Capital Territory"}, {code:"New South Wales", name: "New South Wales"}, {code:"Northern Territory", name: "Northern Territory"}, {code:"Queensland", name: "Queensland"}, {code:"South Australia", name: "South Australia"}, {code:"Tasmania", name: "Tasmania"}, {code:"Victoria", name: "Victoria"}, {code:"Western Australia", name: "Western Australia"}],
               "CA" : [{code : -1, name : "&nbsp;"},{code:"Alberta",name:"Alberta"},{code:"British Columbia",name:"British Columbia"},{code:"Manitoba",name:"Manitoba"},{code:"New Brunswick",name:"New Brunswick"},{code:"Newfoundland",name:"Newfoundland"},{code:"Northwest Territories",name:"Northwest Territories"},{code:"Nova Scotia",name:"Nova Scotia"},{code:"Nunavut",name:"Nunavut"},{code:"Ontario",name:"Ontario"},{code:"Prince Edward Island",name:"Prince Edward Island"},{code:"Quebec",name:"Quebec"},{code:"Saskatchewan",name:"Saskatchewan"},{code:"Yukon Territory",name:"Yukon Territory"}],
               "GB" : [{code : -1, name : "&nbsp;"},{code:"East Midlands", name: "East Midlands"}, {code:"Eastern England", name: "Eastern England"}, {code:"Greater London", name: "Greater London"}, {code:"Isles", name: "Isles"}, {code:"North East England", name: "North East England"}, {code:"North West England", name: "North West England"}, {code:"Northern Ireland", name: "Northern Ireland"}, {code:"Scotland", name: "Scotland"}, {code:"South East England", name: "South East England"}, {code:"South West England", name: "South West England"}, {code:"Wales", name: "Wales"}, {code:"West Midlands", name: "West Midlands"}, {code:"Yorkshire and Humberside", name: "Yorkshire and Humberside"}],
               "IE" : [{code : -1, name : "&nbsp;"},{code:"Cavan", name: "Cavan"}, {code:"Carlow", name: "Carlow"},{code:"Clare", name: "Clare"}, {code:"Cork", name: "Cork"},  {code:"Donegal", name: "Donegal"}, {code:"Dublin", name: "Dublin"},
                        {code:"Galway", name: "Galway"},  {code:"Kerry", name: "Kerry"}, {code:"Kildare", name: "Kildare"}, {code:"Kilkenny", name: "Kilkenny"}, {code:"Laois", name: "Laois"},{code:"Leitrim", name: "Leitrim"}, {code:"Limerick", name: "Limerick"}, {code:"Longford", name: "Longford"}, {code:"Louth", name: "Louth"}, {code:"Mayo", name: "Mayo"}, {code:"Meath", name: "Meath"},{code:"Monaghan", name: "Monaghan"}, {code:"Offaly", name: "Offaly"},
                        {code:"Roscommon", name: "Roscommon"}, {code:"Sligo", name: "Sligo"}, {code:"Tipperary", name: "Tipperary"},
                        {code:"Waterford", name: "Waterford"}, {code:"Westmeath", name: "Westmeath"}, {code:"Wexford", name: "Wexford"}, {code:"Wicklow", name: "Wicklow"}],
               "NZ" : [{code : -1, name : "&nbsp;"},{code:"Auckland", name: "Auckland"}, {code:"Bay of Plenty", name: "Bay of Plenty"}, {code:"Canterbury", name: "Canterbury"}, {code:"Chatham Islands", name: "Chatham Islands"}, {code:"Gisborne", name: "Gisborne"}, {code:"Hawkes Bay", name: "Hawkes Bay"}, {code:"Manawatu-Wanganui", name: "Manawatu-Wanganui"}, {code:"Marlborough", name: "Marlborough"}, {code:"Nelson", name: "Nelson"}, {code:"Northland", name: "Northland"}, {code:"Otago", name: "Otago"}, {code:"Southland", name: "Southland"}, {code:"Taranaki", name: "Taranaki"}, {code:"Tasman", name: "Tasman"}, {code:"Waikato", name: "Waikato"}, {code:"Wellington", name: "Wellington"}, {code:"West Coast", name: "West Coast"}]
               };

//year range should be 2008-1930
TAGGED.profile.school_info.startYearsMin = 1930;
TAGGED.profile.school_info.startYearsMax = 2008;

TAGGED.profile.school_info.endYearsMin = 1930;
TAGGED.profile.school_info.endYearsMax = 2008;

//2014-1930 for graduation year, it could be in the future +6 year
TAGGED.profile.school_info.gradYearsMin = 1930;
TAGGED.profile.school_info.gradYearsMax = 2014;

/********************************
 * helper functions
 ********************************/

// helper function to construct a query string from the drop downs for a particular type
TAGGED.profile.school_info.buildQuery = function () {
    // initial query string
    var q = '&type='+document.forms['add_school'].type.value;

    // grab country
    var countryDropDown = document.getElementById('school_add_country');
    if (!countryDropDown) {
        return false;
    } else {
        var countryValue = countryDropDown.value;
        q += '&country=' + countryValue;
    }

    // grab state if exists
    var stateDropDown = document.getElementById('school_add_state');
    if (stateDropDown) {
        var stateValue = stateDropDown.value;
        q += '&state=' + stateValue;
    }

    // grab province if exists (query param is still called state)
    var provinceDropDown = document.getElementById('school_add_province');
    if (provinceDropDown) {
        var provinceValue = provinceDropDown.value;
        q += '&state=' + provinceValue;
    }

    // grab city if exists
    var cityDropDown = document.getElementById('school_add_city');
    if (cityDropDown) {
        var cityValue = cityDropDown.value;
        q += '&city=' + cityValue;
    }

    return q;
}

TAGGED.profile.school_info.selectOption = function (selectObj, targetValue) {
    if (!selectObj) return;
    for(var i in selectObj.options) {
        var option = selectObj.options[i];
        if (option && option.value == targetValue) {
            option.selected = true;
        }
    }
}

/********************************
 * display functions
 ********************************/

// show the HTML to add a school for the given type
/* 8/25/09: Not sure if this function is even used still... search is such a mess,
 * I can't figure it out. Either way, I've converted autocomplete here to no longer
 * use the typeahead wrapper.
 */
TAGGED.profile.school_info.showAddSchool = function (role, type) {
    var form = document.forms['add_school'];
    form.role.value = role;
    // select the right type in the browse drop down
    TAGGED.profile.school_info.selectOption(form.type, type);
    var searchField = D.get('school_search');
    searchField.value = '';

    // attach hint input to search field
    TAGGED.util.hintinput.attach(searchField, form, 'Start typing a school name here...');
    // define data source
    var dataSource = new YAHOO.util.XHRDataSource('/proxy/s.php');
    dataSource.responseType = YAHOO.util.XHRDataSource.TYPE_JSON;
    dataSource.responseSchema = {
        resultsList : 'results',
        fields : ['schoolName', 'schoolTypeId', 'schoolId', 'schoolCityName', 'schoolCityCode', 'schoolStateAbbrev']
    };
    var AC = new YAHOO.widget.AutoComplete('school_search', 'school_search_ac_container', dataSource);
    AC.resultTypeList = false;
    AC.formatResult = function(result, q) {
        var html = result.schoolName+'<br/><span class="schoolSearchResultLoc">'+result.schoolCityName;
        html += ', '+result.schoolStateAbbrev+'</span>';
        var re = new RegExp('('+q+')', 'ig');
        return html.replace(re, '<strong>$1</strong>');
    };
    AC.generateRequest = function(sQuery) {
        // TO DO: usercc is currently a global var inside the template... not good.
        return '?method=schoolsta&type='+type+'&country='+usercc+'&match='+sQuery;
    };
    AC.itemSelectEvent.subscribe(function(resultArray) {
        var schoolId = resultArray[2];
        var schoolName = resultArray[0];
        TAGGED.profile.school_info.affiliationOnClick(schoolId, schoolName);
    });        
    AC.useIFrame = true;
    AC.minQueryLength = 1;
    AC.maxResultsDisplayed = 10;
    AC.animVert = true;
    AC.autoHighlight = true;
    AC.allowBrowserAutocomplete = false;
    
    // commenting out, doesnt appear to be used anywhere (should now be ' = AC')
    //TAGGED.profile.school_info.ta = typeAhead;

    // build the drop downs for country
    // TODO: pull the user's country by default
    tagged.util.browser.buildSelect('school_add_country_span', 'school_add_country', TAGGED.profile.school_info.countries, 'school_select', user_cc);
    YAHOO.util.Event.addListener('school_add_country', 'change', TAGGED.profile.school_info.countryChange);
    TAGGED.profile.school_info.countryChange(null);

    // show the div with the add_school form
    tagged.util.domMethods.display('school_add', true, 'block');

    var typeLabel = document.getElementById('school_' + role + '_' + type + '_label');
    var typeName = typeLabel.innerHTML;
    var addSchoolType = document.getElementById('school_add_type_name');
    addSchoolType.innerHTML = typeName;

    // hide the other school info divs
    for (var i = 1; i <= 2; i++) {
        for (var j = 1; j <= 10; j++) {
            tagged.util.domMethods.display('school_'+i+'_'+j, false);
        }
    }
    // hide the seperator
    tagged.util.domMethods.display('role_separator', false);

    return false;
}

// hide the add school divs,  and show the user's current schools
TAGGED.profile.school_info.hideAddSchool = function () {
    for (var i = 1; i <= 2; i++) {
        for (var j = 1; j <= 10; j++) {
            tagged.util.domMethods.display('school_'+i+'_'+j, true, 'block');
       }
    }
    // show the seperator
    tagged.util.domMethods.display('role_separator', true);

    // hide the add school div
    tagged.util.domMethods.display('school_add', false);
    // reset the other parts of the add school form
    TAGGED.profile.school_info.resetAddSchoolForm();

    return false;
}

TAGGED.profile.school_info.typeChange = function() {
    TAGGED.profile.school_info.resetAddSchoolForm();
    TAGGED.profile.school_info.typeAndCountrySelected();
}

TAGGED.profile.school_info.resetAddSchoolForm = function() {
    // hide the add school detail
    tagged.util.domMethods.display('school_add_details', false);
    // hide the browse list
    tagged.util.domMethods.display('school_add_list', false);
    // make sure main cancel div is showing
    tagged.util.domMethods.display('school_add_cancel', true);

    // kill any state/city generated drop down
    document.getElementById('school_add_state_span').innerHTML = '';
    document.getElementById('school_add_city_span').innerHTML = '';
}

// Change country, shows zipcode or city depending what's selected
TAGGED.profile.school_info.countryChange = function(e) {
    TAGGED.profile.school_info.resetAddSchoolForm();

    var countryDropDown = document.getElementById('school_add_country');
    var value = countryDropDown.value;

    // figure out what types are available. Process Types generates the state or city drop down
    var postObj = {
        method : 'tagged.affiliations.getTypes',
        callback : 'TAGGED.profile.school_info.processTypes',
        country : value
    };
    TAGGED.api.call(postObj);
};

TAGGED.profile.school_info.processTypes = function(o) {
    if ((o.stat == 'ok') && o.result) {
        // preserve the currently selected type if available
        var oldType = document.forms['add_school'].type.value;

        // generate the new type drop down
        tagged.util.browser.buildSelect('school_add_type_span', 'type', o.result.data, 'school_select', oldType);
        YAHOO.util.Event.addListener(document.forms['add_school'].type, "change", TAGGED.profile.school_info.typeChange);

        TAGGED.profile.school_info.typeAndCountrySelected();
    }
}

// this function should be called whenever type and country are set and we want to populate the next step in browse
TAGGED.profile.school_info.typeAndCountrySelected = function() {
    // US has states & CA has provinces, everyone else just has cities
    var countryDropDown = document.getElementById('school_add_country');
    var value = countryDropDown.value;

    // if college, then grab the schools; otherwise, grab cities
    var type = document.forms['add_school'].type.value;
    if (value != 'US' && value != 'CA' && value != 'AU' && type == 4) {
        TAGGED.profile.school_info.getSchools(TAGGED.profile.school_info.processSchools, TAGGED.profile.school_info.buildQuery());
    } else {
        var states = TAGGED.profile.school_info.states[value];
        tagged.util.browser.buildSelect('school_add_state_span', 'school_add_state', states, 'school_select', '');
        YAHOO.util.Event.addListener('school_add_state', "change", TAGGED.profile.school_info.stateChange);
    }
}

//this retrieves the cities or affiliations depending on the school type and what not,
//the server will return the cities or affiliations on the input
TAGGED.profile.school_info.stateChange = function(e) {
    // hide school list if it exists
    tagged.util.domMethods.display('school_add_list', false);

    // if the user chooses blank, make sure cities display is not shown and the city selector is reset
    if (this.value == -1) {
        document.getElementById('school_add_city_span').innerHTML = '';
        return;
    }

    var countryValue = document.getElementById('school_add_country').value;

    // if this is a college request, show schools; otherwise, show cities
    var type = document.forms['add_school'].type.value;

    if (type == 4 && countryValue != 'AU') {
        TAGGED.profile.school_info.getSchools(TAGGED.profile.school_info.processSchools, TAGGED.profile.school_info.buildQuery());
    } else {
        TAGGED.profile.school_info.getCities(TAGGED.profile.school_info.processCities, TAGGED.profile.school_info.buildQuery());
    }
};

/********************************
 * ajax functions
 ********************************/

// grabs eligible cities list and creates drop down
TAGGED.profile.school_info.getCities = function (callback, query) {
    var cb = { success:callback, failure:null };
    YAHOO.util.Connect.asyncRequest('GET', '/proxy/s.php?method=getcities'+query, cb);
}

// process the ajax response from getting cities
TAGGED.profile.school_info.processCities = function (o) {
    var response = eval('(' + o.responseText + ')');
    // no data returned
    if(!response.results)
        return;

    var results = [];
    results[0] = {'code': -1, 'name': '&nbsp;'};
    for (var i in response.results) {
        var idx = parseInt(i);
        results[idx+1] = { 'code': response.results[idx].cityCode, 'name': response.results[idx].cityName };
    }
    var typeName = document.forms['add_school'].type.options[document.forms['add_school'].type.selectedIndex].text;

    if (response.results.length == 0) {
        document.getElementById('school_add_city_span').innerHTML = '';
        alert("No " +  typeName + " in this region");
        return;
    }
    // see if we have a saved city setting
    var selectedValue = '';
    if (TAGGED.profile.school_info.oldCityValue) {
        selectedValue = TAGGED.profile.school_info.oldCityValue;
    }

    // build the cities drop down
    tagged.util.browser.buildSelect(
        'school_add_city_span',
        'school_add_city',
        results,
        'school_select',
        selectedValue);

    if (selectedValue) {
        TAGGED.profile.school_info.getSchools(TAGGED.profile.school_info.processSchools, TAGGED.profile.school_info.buildQuery());
    }

    // add the listener for change events
    YAHOO.util.Event.addListener('school_add_city', "change", TAGGED.profile.school_info.cityChange);
}

// handle city dropdown change, shows a list of affiliations
TAGGED.profile.school_info.cityChange = function(e) {
    // hide school list if it exists
    tagged.util.domMethods.display('school_add_list', false);

    // make sure user selected a city
    if (this.value != '-1') {
        TAGGED.profile.school_info.getSchools(TAGGED.profile.school_info.processSchools, TAGGED.profile.school_info.buildQuery());
    }
};

// grab list of schools via ajax and create school list
TAGGED.profile.school_info.getSchools = function(callback, query) {
    var cb = { success:callback, failure:null };
    YAHOO.util.Connect.asyncRequest('GET', '/proxy/s.php?method=getschools'+query, cb);
}

// process the ajax response from getting schools
TAGGED.profile.school_info.processSchools = function (o) {
    var response = eval('(' + o.responseText + ')');
    // no data returned
    var numAffiliations = response.results.length;
    if (numAffiliations == 0)
        return;
    var buf = new tagged.util.stringBuffer();

    buf.add('<div class="school_add_item_col">');
    var colBreak = Math.ceil(numAffiliations / 3);

    for(var i in response.results) {
        var school = response.results[i];
        var escapeName = school.schoolName.replace(/"/g, '&quot;'); //'"//close the regular expression
        escapeName = tagged.util.string.escapeQuotes(escapeName);
        buf.add('<div class="school_add_item"><a href="#" onclick="return TAGGED.profile.school_info.affiliationOnClick('+
                school.schoolId + ',\'' + escapeName + '\');">' +
                school.schoolName + '</a></div>');

        if ((i%colBreak == colBreak-1) && i != response.results.length) {
            buf.add('</div><div class="school_add_item_col">');
        }
    }

    buf.add('</div><div class="clearBoth"></div>');

    document.getElementById('school_add_list').innerHTML = buf.toString();

    // show the school list div
    tagged.util.domMethods.display('school_add_list', true, 'block');

    // make sure details div is hidden
    tagged.util.domMethods.display('school_add_details', false);
}

//handle user clicking on a school
TAGGED.profile.school_info.affiliationOnClick = function (schoolId, schoolName) {
    // grab the type name from the type selector
    var typeName = document.forms['add_school'].type.options[document.forms['add_school'].type.selectedIndex].text;

    if (typeName) {
        document.getElementById('school_add_details_type_name_span').innerHTML = typeName;
    }

    // create start/end year fields
    tagged.util.dates.getYears(
        'school_add_start_year_span',
        'start_year',
        'start_year',
        '',
        TAGGED.profile.school_info.startYearsMin,
        TAGGED.profile.school_info.startYearsMax);

    // add the listener for change events
    YAHOO.util.Event.addListener('start_year', "change", TAGGED.profile.school_info.startYearChange);

    tagged.util.dates.getYears(
        'school_add_end_year_span',
        'end_year',
        'end_year',
        '',
        TAGGED.profile.school_info.endYearsMin,
        TAGGED.profile.school_info.endYearsMax);

    // add "Present" option
    var present = new Option('Present',0);
    var endYearSelect = document.forms['add_school'].end_year;
    try {
        endYearSelect.add(present, endYearSelect.options[1]); // standards compliant; doesn't work in IE
    } catch(ex) {
        endYearSelect.add(present, 1); // IE only
    }

    // if high school or college, create grad year
    var type = document.forms['add_school'].type.value;

    if (type == 3 || type == 4) {
        tagged.util.domMethods.display('school_add_grad_year_div', true);

        // add the listener for change events
        YAHOO.util.Event.addListener('end_year', "change", TAGGED.profile.school_info.endYearChange);

        tagged.util.dates.getYears(
            'school_add_grad_year_span',
            'grad_year',
            'grad_year',
            '',
            TAGGED.profile.school_info.gradYearsMin,
            TAGGED.profile.school_info.gradYearsMax);
    } else {
        tagged.util.domMethods.display('school_add_grad_year_div', false);
    }

    // fill in the school ID and school name fields
    document.forms['add_school'].elements['affiliation_id'].value = schoolId;

    document.getElementById('school_add_details_name_span').innerHTML = schoolName;

    // show the details div
    tagged.util.domMethods.display('school_add_details', true, 'block');
    // hide the main cancel div (we're going to use the one inside the details div)
    tagged.util.domMethods.display('school_add_cancel', false);
    //in case there are a lot of affiliations scroll down automatically
    var elem =  document.getElementById('school_add_details');
    var offset =  tagged.util.browser.getOffsetY(elem);
    window.scrollTo(0, offset);
    // make sure I don't follow the link
    return false;
}

TAGGED.profile.school_info.offsetY = function (elem){
    return elem.offsetParent ? elem.offsetTop + TAGGED.profile.school_info.offsetY(elem.offsetParent) : elem.offsetTop;
}

TAGGED.profile.school_info.startYearChange = function (e) {
    var type = document.forms['add_school'].type.value;

    // if the user chooses blank do nothing
    if (this.value == -1) {
        return;
    }

    // pre-fill end year
    var offset = 0;
    switch(parseInt(type)) {
        case 1:
            offset = 6;
            break;
        case 2:
            offset = 3;
            break;
        case 3:
        case 4:
            offset = 4;
            break;
    }

    // figure out the target value
    var targetValue = parseInt(this.value) + offset;

    // if there's a grad year drop down, prefill that
    var gradYearDropDown = document.forms['add_school'].elements['grad_year'];
    if (gradYearDropDown) {
        TAGGED.profile.school_info.selectOption(gradYearDropDown, targetValue);
    }

    // if we're beyond the max, select present
    if (targetValue > TAGGED.profile.school_info.endYearsMax) {
        targetValue = 0;
    }
    var endYearDropDown = document.forms['add_school'].elements['end_year'];
    TAGGED.profile.school_info.selectOption(endYearDropDown, targetValue);

}

TAGGED.profile.school_info.endYearChange = function (e) {
    // if the user chooses blank do nothing
    if (this.value == -1) {
        return;
    }

    var gradYearDropDown = document.forms['add_school'].elements['grad_year'];
    TAGGED.profile.school_info.selectOption(gradYearDropDown, parseInt(this.value));
}

TAGGED.profile.school_info.removeSchool = function (userAffiliationId) {
    if (confirm('Do you want to remove this school?')){
        // call the API
        var postObj = {
            method : 'tagged.affiliations.remove',
            callback : 'TAGGED.profile.school_info.refreshSchoolInfo',
            user_affiliation_id : userAffiliationId,
            refresh_school_tab : true
        };

        TAGGED.api.call(postObj);
    }
    // make sure link isn't followed
    return false;
}

/**
Add the current school to user's affilition list. The server will send back the updated html with the new school
*/
TAGGED.profile.school_info.handleForm = function (formObj) {
    var postObj = {
        method : 'tagged.affiliations.add',
        callback : 'TAGGED.profile.school_info.refreshSchoolInfo',
        refresh_school_tab : true
    };

    // grab all the data from the form
    for (var i in formObj) {
        var formField = formObj[i];
        if (formField && (formField.type == 'hidden' || formField.type == 'select-one')) {
            if ((formField.name == 'start_year' || formField.name == 'end_year' || formField.name == 'grad_year') && formField.value == -1) {
                alert('Please make sure to add all details.');
                return false;
            }

            postObj[formField.name] = formField.value;
        }
    }

    // see if the end year doesn't make sense given the start year
    if (formObj['end_year'].value != 0 && formObj['start_year'].value > formObj['end_year'].value) {
        alert('Please check your years attended.');
        return false;
    }

    // you can't graduate before your start year (you end after your grad year though)
    if (formObj['grad_year'] && formObj['grad_year'].value < formObj['start_year'].value){
        alert('Please check your years attended.');
        return false;
    }

    TAGGED.api.call(postObj);

    // make sure the form doesn't actually submit
    return false;
}

// if successful, gets a new HTML to inject for the schools & colleges tab
TAGGED.profile.school_info.refreshSchoolInfo = function (o)
{
    if ((o.stat == 'ok') && o.schoolsHtml) {
        document.getElementById('tab3').innerHTML = o.schoolsHtml;
        window.scrollTo(0, 0); //scroll to the top after adding a school
    }
}

// called onChange of a school type's privacy drop-down
TAGGED.profile.school_info.changeVisibility = function (useraffId, setting)
{
    var postObj = {
        method : 'tagged.affiliations.setVisibility',
        callback : 'TAGGED.profile.school_info.visibilityChanged',
        user_affiliation_id : useraffId,
        setting: setting
    };

    TAGGED.api.call(postObj);
}

// handles jsonp response
TAGGED.profile.school_info.visibilityChanged = function (o) {}

// required for safe loader
TAGGED.profile.school_info.init = function () { }
