
// $Id: optionTab.js,v 1.16 2008/09/19 00:21:02 daniel Exp $

//** Global Variables **

//add the dropdown select using Rico
var onloads = new Array();


/* 
 * initiate the tag for select box. 
 * Defaultly the countries will be showed, 
 * regions will be hidden
 */
var cTag=true;
var rTag=false;

/*
 * temporary array for storing selected 
 * countries and regions, because there is
 * no other ways to mark countries and
 * regions seperately in 'selected countries
 * regions' select box
 */
var countries = new Array();
var regions = new Array();

//** functions **

/*
 * Rico loading array
 * if there are more functions needed to be
 * loaded when startup, push them into this
 * array
 */
onloads.push( makeAccordion );

//startup loading
function bodyOnLoad() {
    for ( var i = 0 ; i < onloads.length ; i++ )
    onloads[i]();
}

//accordion widget from Rico
function makeAccordion() {
    var accordion = new Rico.Accordion( 'rolodexAccordion',{panelHeight: 'auto',
     onShowTab: showTabContent, collapsedTextColor:'#ffffff',collapsedBg:'#6b79b5' });
}


/*
 * update the tag and initiate the 
 * button when showing tabs 
 */
function showTabContent(aTab){
    if(aTab.content.id == 'countries'){
        cTag = true;
        rTag = false;
        buttonInit('optCountries', 'compCountries', countries);
        //button captions
        $('addSelected').title = 'Add selected countries';
        $('delPartSelected').title = 'Remove all countries';
        $('addPartSelected').title = 'Add all countries';
        //cursor
        $('titleBarCountries').style.cursor = 'default';
        $('titleBarRegions').style.cursor = 'pointer';
        $('countriesText').style.textDecoration = 'none';
        $('regionsText').style.textDecoration = 'underline';
    }else if(aTab.content.id == 'regions'){
        cTag = false;
        rTag = true;
        buttonInit('optRegions', 'compCountries', regions);
        //button captions
        $('addSelected').title = 'Add selected regions';
        $('delPartSelected').title = 'Remove all regions';
        $('addPartSelected').title = 'Add all regions';
        //cursor
        $('titleBarCountries').style.cursor = 'pointer';
        $('titleBarRegions').style.cursor = 'default';
        $('countriesText').style.textDecoration = 'underline';
        $('regionsText').style.textDecoration = 'none';
    }    
}

/*
 * check button status, define whether 
 * the buttions looked disable or not
 */
function buttonInit(sBox1, sBox2, sBox1Array){
    obj1 = $(sBox1);
    obj2 = $(sBox2);

    if(hasOptions(obj1)){
        swpButtonStyle('addPortion', 'unchg');
        swpButtonStyle('addSingle', 'unchg');
        $('addPartSelected').style.cursor = 'pointer';
        $('addSelected').style.cursor = 'pointer';
    }else{
        swpButtonStyle('addPortion', 'chg');
        swpButtonStyle('addSingle', 'chg');
        $('addPartSelected').style.cursor = 'default';
        $('addSelected').style.cursor = 'default';
    }

    if(sBox1Array.length == 0){
        swpButtonStyle('delPortion', 'chg');
        $('delPartSelected').style.cursor = 'default';
    }else{
        swpButtonStyle('delPortion', 'unchg'); 
        $('delPartSelected').style.cursor = 'pointer';      
    }
    
    if(hasOptions($('compCountries'))){
        swpButtonStyle('delall', 'unchg');
        swpButtonStyle('delSingle', 'unchg');
        $('delSelected').style.cursor = 'pointer';
        $('moveAll').style.cursor = 'pointer';
    }else{
        swpButtonStyle('delall', 'chg');
        swpButtonStyle('delSingle', 'chg');
        $('delSelected').style.cursor = 'default';
        $('moveAll').style.cursor = 'default';
    }
    
    if(!hasOptions($('optCountries')) && !hasOptions($('optRegions'))){
        swpButtonStyle('addall', 'chg');
        swpButtonStyle('addSingle', 'chg');
        $('addSelected').style.cursor = 'default';
        $('addAllOp').style.cursor = 'default';
    }else{
        swpButtonStyle('addall', 'unchg');
        $('addAllOp').style.cursor = 'pointer';
    }
}

/*
 * swap button css so that they can 
 * have a disable look when needed
 */
function swpButtonStyle(id, key){
    if(key == 'unchg'){  
        $(id).className = 'buttonOpacityUnchg';
    }else if(key == 'chg'){
        $(id).className = 'buttonOpacityChg';
    }
}

/*
 * "add" button function
 */
function addOptions(text){
    if(cTag == true){
        var fromList = $('optCountries');
        var tag = 'optCountries';
    }else if(rTag == true){
        var fromList = $('optRegions');
        var tag = 'optRegions';
    }
    var toList = $('compCountries');
    addOperation(fromList, toList, tag);
    if(cTag == true){
        buttonInit('optCountries', 'compCountries', countries);
    }else if(rTag == true){
        buttonInit('optRegions', 'compCountries', regions);
    }
    checkEmptyList(fromList, text);
    checkEmptyList(toList, text);
}

/*
 * perform the actually "add" to the select box
 */ 
function addOperation(from, to, tag){
    // Unselect matching options, if required
    if (arguments.length>3) {
        var regex = arguments[3];
        if (regex != "") {
            unSelectMatchingOptions(from,regex);
        }
    }
    // Move them over
    if (!hasOptions(from)) { return; }
    for (var i=0; i<from.options.length; i++) {
        var o = from.options[i];
        if (o.selected) {
            if (!hasOptions(to)) {
                var index = 0;
            }
            else {
                var index=to.options.length;
            }
            to.options[index] = new Option( o.text, o.value, false, false);
            if(tag == 'optCountries'){
                countries.push(o.text);
            }else if(tag == 'optRegions'){
                regions.push(o.text);
            }
        }
    }
    // Delete them from original
    for (var i=(from.options.length-1); i>=0; i--) {
        var o = from.options[i];
        if (o.selected) {
            from.options[i] = null;
        }
    }
    if ((arguments.length<4) || (arguments[3]==true)) {
        sortSelect(from);
        sortSelect(to);
    }
    from.selectedIndex = -1;
    to.selectedIndex = -1;
}

/*
 * "delete" button function
 */
function delOptions(text){
    var fromList = $('compCountries');
    delOperation(fromList, true);
    if(cTag == true){
        buttonInit('optCountries', 'compCountries', countries);
    }else if(rTag == true){
        buttonInit('optRegions', 'compCountries', regions);
    }
    var toList = $('optCountries');
    checkEmptyList(toList, text);  
    var toList = $('optRegions');
    checkEmptyList(toList, text);
    checkEmptyList(fromList, text);
}

/*
 * searching for proper select box the selected option belongs to
 * when argument[1] == true, any selected options can be move back
 * to the select box they are from
 * otherwise only selected options belong to the tab showing can
 * be move back
 */
function locateSelectBox(text){
    var flag = 0;
    if(arguments.length == 2 && arguments[1] == true){
        for(var i=0; i<countries.length; i++){
            if(countries[i] == text){
                flag = 1;
                clearTmpArray(countries, i);
                break;
            }
        }
        if(flag == 0){
            for(var i=0; i<regions.length; i++){
                if(regions[i] == text){
                    flag = 2;
                    clearTmpArray(regions, i);
                    break;
                }
            }
        }
    }else{
        for(var i=0; i<countries.length; i++){
            if(countries[i] == text && cTag == true){
                flag = 1;
                clearTmpArray(countries, i);
                break;
            }
        }
        if(flag == 0){
            for(var i=0; i<regions.length; i++){
                if(regions[i] == text && rTag == true){
                    flag = 2;
                    clearTmpArray(regions, i);
                    break;
                }
            }
        }
    }
    return flag;
}

/*
 * move the selected options out of the temperary arrays
 * which store the compCountrie options
 */
function clearTmpArray(tmpArray, index){
    for(var i=index; i<tmpArray.length-1; i++){
       tmpArray[i] = tmpArray[i+1];
    }
    tmpArray.pop();
}

/*
 * perform the actual delete 
 */
function delOperation(from){
        // Unselect matching options, if required
    if (arguments.length>2) {
        var regex = arguments[3];
        if (regex != "") {
            unSelectMatchingOptions(from,regex);
        }
    }
    // Move them over
    if (!hasOptions(from)) { return; }
    for (var i=0; i<from.options.length; i++) {
        var o = from.options[i];
        if (o.selected) {
            if(arguments.length == 2 && arguments[1] == true){
                var flag = locateSelectBox(o.text, true);
            }else{
                var flag = locateSelectBox(o.text);
            }
                if(flag == 1){
                    to = $('optCountries');
                }else if(flag == 2){
                    to = $('optRegions');
                }else if(flag == 0){
                    return;
                }
            
            if (!hasOptions(to)) {
                var index = 0;
            }
            else {
                var index=to.options.length;
            }
            to.options[index] = new Option( o.text, o.value, false, false);
        }
    }
    // Delete them from original
    for (var i=(from.options.length-1); i>=0; i--) {
        var o = from.options[i];
        if (o.selected) {
            from.options[i] = null;
        }
    } 
    if ((arguments.length<2) || (arguments[1]==true)) {
        sortSelect(from);
        sortSelect($('optCountries'));
        sortSelect($('optRegions'));
    }
    from.selectedIndex = -1;
    $('optCountries').selectedIndex = -1; 
    $('optRegions').selectedIndex = -1;    
}

/*
 * if one list has become empty, or ceased being empty,
 * set or unset the default text
 */
function checkEmptyList(list, text) {
    if (list.options.length > 0) {
        for (i = 0; i < list.options.length ; i++) {
            if (list.options.length != 1 &&
                list.options[i].value == " ") {
                list.options[i] = null;
            }
        }
    }
//    else {
//        list.options[0] = new Option(text," ");
//    }
}


/*
 * sortSelect(select_object)
 * Pass this function a SELECT object and the options will be sorted
 * by their text (display) values
 */
function sortSelect(obj)
{
    var o = new Array();
    if (!hasOptions(obj)) { return; }
    for (var i=0; i<obj.options.length; i++) {
        o[o.length] = new Option( obj.options[i].text, obj.options[i].value, obj.options[i].defaultSelected, obj.options[i].selected) ;
    }
    if (o.length==0) { return; }
    o = o.sort(
    function(a,b) {
        if ((a.text+"") < (b.text+"")) { return -1; }
        if ((a.text+"") > (b.text+"")) { return 1; }
        return 0;
    }
    );

    for (var i=0; i<o.length; i++) {
        obj.options[i] = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
    }
}

/*
 * hasOptions(obj)
 * Utility function to determine if a select object has an options array
 */
function hasOptions(obj)
{
	if (obj!=null && obj.options.length!=0) {
	    return true;
	}
	return false;
}

/*
 * perform "add" function when only adding all the countries
 * or regions
 */
function addPortions(text){
    if(cTag == true){
        var fromList = $('optCountries');
        var tag = 'optCountries';
    }else if(rTag == true){
        var fromList = $('optRegions');
        var tag = 'optRegions';
    }
    var toList = $('compCountries');
    addPort(fromList, toList, tag);
    if(cTag == true){
        buttonInit('optCountries', 'compCountries', countries);
    }else if(rTag == true){
        buttonInit('optRegions', 'compCountries', regions);
    } 
    checkEmptyList(fromList, text);
    checkEmptyList(toList, text);
}

/*
 *perform portion add
 */
function addPort(from, to, tag){
    selectAllOptions(from);
    addOperation(from, to, tag);
}

/*
 * perform "delete" function when only deleting all the countries
 * or regions
 */
function delPortions(text){
    if(cTag == true){
        var toList = $('optCountries');
    }else if(rTag == true){
        var toList = $('optRegions');
    }
    var fromList = $('compCountries');
    delPort(fromList);
    if(cTag == true){
        buttonInit('optCountries', 'compCountries', countries);
    }else if(rTag == true){
        buttonInit('optRegions', 'compCountries', regions);
    }     
    checkEmptyList(fromList, text);
    checkEmptyList(toList, text)
}

/*
 * perform portion delete
 */
function delPort(from){
    if(cTag == true){
        selectPortion(from, countries);
    }else if(rTag == true){
        selectPortion(from, regions);
    }
    delOperation(from);
}

/*
 * selectAllOptions(select_object)
 * This function takes a select box and selects all options (in a
 * multiple select object). This is used when passing values between
 * two select boxes. Select all options in the right box before
 * submitting the form so the values will be sent to the server.
 */
function selectAllOptions(obj)
{
    if (!hasOptions(obj)) {
        return;
    }
    for (var i=0; i<obj.options.length; i++) {
        obj.options[i].selected = true;
    }
}

/*
 * select all the countries or regions in "compCountries" select box
 * when move either of them back
 */
function selectPortion(obj, comObj){
    if (!hasOptions(obj)) {
        return;
    }
    for (var i=0; i<obj.options.length; i++) {
         obj.options[i].selected = false;
    }
    for (var i=0; i<comObj.length; i++){
        for(var j=0; j<obj.options.length; j++){
            if(comObj[i] == obj.options[j].text){
                obj.options[j].selected = true;
                break;
            }
        }
    }
}

/*
 * adding all the countries and regions
 * to the compCountries select box
 */
function addAll(){
    var text = ' ';    
    var toList = $('compCountries');
    var fromList = $('optRegions');
    addPort(fromList, toList, 'optRegions');
    checkEmptyList(fromList, text);
    var fromList = $('optCountries');
    addPort(fromList, toList, 'optCountries');
    if(cTag == true){
        buttonInit('optCountries', 'compCountries', countries);
    }else if(rTag == true){
        buttonInit('optRegions', 'compCountries', regions);
    }
    checkEmptyList(fromList, text);
    checkEmptyList(toList, text);
}

/*
 * delete all the countries and regions
 * from the compCountries select box
 */
function removeAll(){
    var text = ' ';
    var fromList = $('compCountries');
    delAll(fromList);
    if(cTag == true){
        buttonInit('optCountries', 'compCountries', countries);
    }else if(rTag == true){
        buttonInit('optRegions', 'compCountries', regions);
    }     
    checkEmptyList(fromList, text);
    var toList = $('optCountries');
    checkEmptyList(toList, text);
    toList = $('optRegions');
    checkEmptyList(toList, text);
}

/*
 * perform deleting for all 
 * in compCountries select box
 */
function delAll(from){
    selectPortion(from, countries);      
    delOperation(from, true);
    selectPortion(from, regions);
    delOperation(from, true);
}


//** functions used by async.js **

function selectAll()
{
    var selbox = $('compCountries');
    if (selbox.options.length != 0) {
        for (i = 0; i < selbox.options.length; i++) {
            selbox.options[i].selected = true;
        }
    }
    return true;
}

/*
 * select none of the options in the dynamic select list, this should be
 * called after form submission if selectAll is called before submission
 */
function selectNone()
{
    var selbox = $('compCountries');
    if (selbox.options.length != 0) {
        for (i = 0; i < selbox.options.length; i++) {
            selbox.options[i].selected = null;
        }
    }
    return true;
}


/*
 * Gets the value of the selected option of a select element.
 */
function getSelectedOptionValue(selectId) {

    return $(selectId).value;
}

//for theme5 indicator1 options
function enableT5I1Option(selectID){
    if(selectID == 'allsubjects'){
        $('allout').disabled = false;
        $('allin').disabled = false;
        $('mathout').disabled = true;
        $('mathin').disabled = true;
        
//        $('allout').checked = true;
//        $('allin').checked = true;
//        $('mathout').checked = false;
//        $('mathin').checked = false;
    }else if(selectID == 'mathematics'){
        $('allout').disabled = true;
        $('allin').disabled = true;
        $('mathout').disabled = false;
        $('mathin').disabled = false;
        
//        $('allout').checked = false;
//        $('allin').checked = false;
//        $('mathout').checked = true;
//        $('mathin').checked = true;
    }
}

// remove the host country from the comparison countries list
// as well as the selected countries list if it is selected as the host country
function removeHostFromComp() {
    var host = $('hostCountry').value;
    // create a clone of the selected countries list so that it can be 
    // re-populated after the host country has been changed
    var compC = $('compCountries');
    var cloneCc = compC.cloneNode(true);
    
    // reset the comparison and selected countries lists according to host 
    // country selected
    resetMultiSelect('optCountries', host, cloneC, cloneCc);
    resetMultiSelect('optRegions', host, cloneR, cloneCc);
    
    resetMultiSelect('compCountries', host, cloneCc);
    
    /* ############################
        * get the list of comparison countries after the host country
        * has been changed, so that we can reset the arrow buttons 
        * appropriately
        * basically, all sub-regions have hyphens in them, so we check
        * that against the values, then we can work out whether to
        * reset the arrow buttons or not
    /* ############################*/
    
    var orig = $('compCountries');
    origC = orig.cloneNode(true);
    if (cTag == true) {
        countries = new Array();
        var j = 0;
        for (var i = 0; i < origC.length; i++) {
            if (origC[i].value.substr(2, 1) != '-') {
                countries[j] = origC[i].text;
                j++;
            }
        }

        buttonInit('optCountries', 'compCountries', countries);
    }
    else if (rTag == true) {
        regions = new Array();
        var j = 0;
        for (var i = 0; i < origC.length; i++) {
            if (origC[i].value.substr(2, 1) == '-') {
                regions[j] = origC[i].text;
                j++;
            }
        }

        buttonInit('optRegions', 'compCountries', regions);
    }
    origC = null;
    orig = null;
}

function resetMultiSelect(id, host, clone, secClone) {
    // arrays to store the values and text of the list
    var newValue = new Array();
    var newText = new Array();
    var j = 0;
    
    // used to determine whether to add the country to the comparison country
    // list or not
    var add = true;

    // if the fourth parameter is not null, then we need to check the
    // selected countries list before re-populating the comparison countries list
    // so that we don't have any duplicates
    if (secClone != null) {
        for (var i = 0; i < clone.length; i++) {
            add = true;
            for (var k = 0; k < secClone.length; k++) {
                if (clone[i].value == secClone[k].value) {
                    add = false;
                }
            }
            // add to the array to add into the select object
            if (add) {
                if (host != clone[i].value) {
                    newValue[j] = clone[i].value;
                    newText[j] = clone[i].text;
                    j++;
                }
            }
        }
    }
    // if the fourth parameter is empty, we don't need to check for duplicates
    else {
        j = 0;
        for (var i = 0; i < clone.length; i++) {
            if (host != clone[i].value) {
                newValue[j] = clone[i].value;
                newText[j] = clone[i].text;
                j++;
            }
        }
    }
    // reset the select list that was requested
    $(id).options.length = 0;
    for (var i = 0; i < newValue.length; i++) {
        $(id).options[i] = new Option(newText[i], newValue[i]);
    }
}


function changeYear() {
	//Change the command to changeCycle and submit the form.
	var form = document.forms[0];
	form.cmd.value = "changeCycle";
	form.submit();
}
