﻿// multiLevelDropdown, Requires JQuery,
//
//  Copyright 2009 Noko Ltd (http://www.noko.co.uk/)  - ALL RIGHTS RESERVED
// 
//  $LastChangedBy: roberts $
//  $LastChangedDate: 2010-02-19 09:47:37 +0000 (Fri, 19 Feb 2010) $
//  $Rev: 1158 $
//  $HeadURL: http://svn.alias.noko.local/svn/ffw/trunk/pi2010/src/Noko.ImmediacyUtilitys/ScriptResources/Resources/custom/multiLevelDropDown.js $
//
//
// This plugin takes a dropdown containing grouped elements and makes it into 2 dropdowns
// it preserves the id/values of the lowest level dropdown allowing it to partisipate in asp.net postbacks.
// the dropdown is 100% functional without this javascript with 0 server side changes.
// children are linked to there parent via an class to value mapping.
// E.g. Children have the class "childofVALUE" where VALUE is the value of the parent element


function init_multiLevelDropdown(DropDown,childClass,customText) {
    var dd = $(DropDown+"_DDPLDDL");
    dd.hide();
    var parent = $('<select>');
    var child = $('<select>');
    parent.insertBefore(dd);
    child.insertBefore(dd);

    var valuetoselect = dd.val();
    var parentToSelect = false;
    
    dd.children().each(function() {
      
        var option = $(this);
       
        if (!option.hasClass(childClass)) {
            //is parent
            parent.append(option.clone());
            if (option.val() === valuetoselect) {
                parentToSelect = true;
            }
        }
    });
  


    parent.change(function onChange() {
        var selected = $("option:selected", parent);
        child.children().remove();
        child.append($('option[value=' + selected.val() + ']', dd).clone().text(customText));
        child.append($('.childof' + selected.val(), dd).clone());
        var selected = $("option:selected", child);
        dd.val(selected.val());
    });
    child.change(function onChange() {
        var selected = $("option:selected", child);
        dd.val(selected.val());
    });
    
    // Now preselect
    if (parentToSelect) {
        parent.val(valuetoselect);
        parent.change();
    } else {
        //  find the corect items
    var selected = $("option:selected", dd);
    var classes = selected.attr("class");
    myregexp = /childof(\d*)/gi
    var items = myregexp.exec(classes);
    if (items != null) {
        parent.val(items[1]);
        parent.change();;
    }
        
    }
}
