/**
 * Pickers for related models
 */

function initPicker(nodeSrcName, nodeDestName, data, mainModel, childModel, toToggle) {

	
    // Create anchors
    nodeSrcName  = '#' + nodeSrcName;
    nodeDestName = '#' + nodeDestName;
		
    var nodeSrc = $(nodeSrcName); // #LocationCountryId
    var nodeDest = $(nodeDestName); // #LocationStateId
    var destFirstOption = $(nodeDestName + ' option:last');
    var preselected;
    //var data = data;

    // Return if unable to locate the required nodes.
    if ((nodeSrc === null) || (nodeDest === null)) {
        return;
    }

    /**
	 * Shows node and its associated label.
	 */
    function showInput(node) {
        node.show();
        node.prev('label').show();
    }

    /**
	 * Hides node and its associated label.
	 */
    function hideInput(node) {
        node.hide();
        node.prev('label').hide();
    }

    /**
	 * Populates destination field with given items.
	 */
    function populateSelect(items) {
        var options = '<option value="">(Select one)</option>';
        var itemCount = 0;
        for(var i in items){
            options += '<option value="' + items[i].id + '">' + items[i].name + '</option>';
            itemCount++;

        }

        nodeDest.html(options);
		
        // Preselect option if only one present.
        if (itemCount == 1) {
            $(nodeDestName + ' option:last').attr('selected','selected');
        } else {
            $(nodeDestName + ' option[value=' + preselected + ']').attr('selected','selected');
        }
    }

    /**
	 * Toggles fields according to current selection.
	 */	
    function toggleFields() {
        switch(nodeSrc.val()) {
            case '':
                hideInput(nodeDest);
                break;
            default:
                showInput(nodeDest);
        }
    }

    /**
	 * Fetches a list of states in JSON format.
	 */
    function fetchData() {

        var value = nodeSrc.val();
        var ind=0;
        for(var i=0; i<data.length; i++){
            if(eval('data[i].'+mainModel+'.id') == value ){
                ind = i;
                break;
            }
        }
		
        var childData = eval('data[ind].'+ childModel);
        if(value!=""){
            populateSelect(childData ? childData : []);
        }else{
            populateSelect({}); //Set empty
        }
        if(toToggle==true){
            toggleFields();
        }
		
    }

    nodeSrc.live('change', fetchData);

    // Init
    preselected = nodeDest.val();
    fetchData();
}




/**
 * Location picker.
 */
function initLocationPicker(nodeSrcName, nodeDestName, nodeAltName, data, mainModel, childModel) {
//    console.log(data);
    OTHER_COUNTRY = '1';

    // Create anchors
    nodeSrcName  = '#' + nodeSrcName;
    nodeDestName = '#' + nodeDestName;
    nodeAltName  = '#' + nodeAltName;
	
    var nodeSrc = $(nodeSrcName); // #LocationCountryId
    var nodeDest = $(nodeDestName); // #LocationStateId
    var destFirstOption = $(nodeDestName + ' option:last');
    var nodeAlt = $(nodeAltName); // #LocationOtherCountry
    var preselected;

    // Return if unable to locate the required nodes.
    if ((nodeSrc == null) || (nodeDest == null) || (nodeAlt == null)) {
        return;
    }

    /**
	 * Shows node and its associated label.
	 */
    function showInput(node) {
        node.show();
        node.prev('label').show();
    }

    /**
	 * Hides node and its associated label.
	 */
    function hideInput(node) {
        node.hide();
        node.prev('label').hide();
    }

    /**
	 * Populates destination field with given items.
	 */
    function populateSelect(items) {
        var options = '<option value="">(Select one)</option>';
        var itemCount = 0;
        for(var i in items){
            options += '<option value="' + items[i].id + '">' + items[i].name + '</option>';
            itemCount++;

        }

        nodeDest.html(options);
		
        // Preselect option if only one present.
        if (itemCount == 1) {
            $(nodeDestName + ' option:last').attr('selected','selected');
        } else {
            $(nodeDestName + ' option[value=' + preselected + ']').attr('selected','selected');
        }
    }

    /**
	 * Toggles fields according to current selection.
	 */	
    function toggleFields() {
        switch(nodeSrc.val()) {
            case '':
                hideInput(nodeDest);
                hideInput(nodeAlt);
                break;
            case OTHER_COUNTRY:
                hideInput(nodeDest);
                showInput(nodeAlt);
                break;
            default:
                showInput(nodeDest);
                hideInput(nodeAlt);
        }
    }

    /**
	 * Fetches a list of states in JSON format.
	 */
    function fetchData() {

        value = nodeSrc.val();
        ind=0;
        for(var i=0; i<data.length; i++){
            if(data[i][mainModel].id == value ){
                ind = i;
                break;
            }
        }
	
      //  childData = eval('data[ind].'+ childModel);
      childData = data[ind][childModel];
        populateSelect(childData ? childData : []);
        toggleFields();
    }


    nodeSrc.live('change', fetchData);

    // Init
    preselected = nodeDest.val();
    fetchData();
}


function initAffiliationPicker(mainName, firstChildName, secondChildName, data) {
    mainName = "#"+mainName;
    firstChildName = "#"+firstChildName;
    secondChildName = "#"+secondChildName;
    
    $(mainName).live('change', function() {
        changeMainInput(mainName, firstChildName, secondChildName, data);
    });
    
    $(firstChildName).live('change', function() {
        changeFirstChildInput(mainName, firstChildName, secondChildName, data);
    });
    
//    console.log('initAffiliationPicker');
}

function changeMainInput(mainName, firstChildName, secondChildName, data) {
    var firstOption = "<option value=''>(None)</option>";
    var mainNameSel = $(mainName).val();
    if (mainNameSel == '') {
        hideSetVal(firstChildName, firstOption);
        hideSetVal(secondChildName, firstOption);
    } else if (isset(data[mainNameSel]['AffiliationDivision'])){
        var option = '';
        $.each(data[mainNameSel].AffiliationDivision, function(k, v) {
            option += "<option value='"+v.id+"'>"+v.name+"</option>";
        });
        $(firstChildName).html(firstOption);
        $(firstChildName).append(option);
        $(firstChildName).parent().show();
        hideSetVal(secondChildName, firstOption);
    } else {
        hideSetVal(firstChildName, firstOption);
        hideSetVal(secondChildName, firstOption);
    }
//    console.log('changeMainInput');
} 

function changeFirstChildInput(mainName, firstChildName, secondChildName, data) {
    var firstOption = "<option value=''>(None)</option>";
    var mainNameSel = $(mainName).val();
    var firstChildNameSel = $(firstChildName).val();
    if (mainNameSel == '') {
        hideSetVal(firstChildName, firstOption);
        hideSetVal(secondChildName, firstOption);
    } else if (firstChildNameSel == "") {
        $(secondChildName).html(firstOption);
        $(secondChildName).parent().hide();
    } else if(isset(data[mainNameSel]['AffiliationDivision'][firstChildNameSel].AffiliationRegion)){
        var option = '';
        $.each(data[mainNameSel]['AffiliationDivision'][firstChildNameSel].AffiliationRegion, function(k, v) {
            option += "<option value='"+v.id+"'>"+v.name+"</option>";
        });
        $(secondChildName).html(firstOption);
        $(secondChildName).append(option);
        $(secondChildName).parent().show();
    } else {
        hideSetVal(secondChildName, firstOption);
    }
//    console.log('changefirstChildInput');
} 


function isset(variable) {
    return typeof(variable) != "undefined" && variable !== null;
}

function hideSetVal (elementId, elementVal) {
    $(elementId).html(elementVal);
    $(elementId).parent().hide();
}
