/**
 * Javascript functions for IgnitionWeb Administration Site
 *
 * This file may be included by a front-end
 */
 
 function layoutButtons() {
    if(!window.in_advisor_be) return;
    
    var number_of_buttons = 3;
    var preview_button_en = $('preview-btn-en');
    var preview_button_fr = $('preview-btn-fr');
    
    // find number of buttons
    if (preview_button_en.visible()) {
        number_of_buttons = number_of_buttons + 1;
    }
    
    if (preview_button_fr.visible()) {
        number_of_buttons = number_of_buttons + 1;
    }
        
    // distribute space evenly between them
    var percentage = parseInt(100/number_of_buttons);
    
    // 
    if (preview_button_en.visible()) {
        preview_button_en.up('div').setStyle({'width': percentage + '%'});
    } else {
        preview_button_en.up('div').setStyle({'width': '0%'});
    }
    
    if (preview_button_fr.visible()) {
        preview_button_fr.up('div').setStyle({'width': percentage + '%'});
    } else {
        preview_button_fr.up('div').setStyle({'width': '0%'});
    }
    
    $$('#buttons-row div.permanent').each( function(cell) {
        cell.setStyle({'width': percentage + '%'});
    });
}


function iw_open_window(link, window_name, width, height, resizable, scrollbars) 
{ 
	return window.open(link, window_name,'toolbar=no,location=no,status=no,menubar=0,scrollbars='+scrollbars+',resizable='+resizable+',height='+height+',width='+width+',top='+(screen.height-height)/2+',left='+(screen.width-width)/2+',copyhistory=no');
}

var rib_window;
var mcb_window;
function close_browsers()
{
    // close RIB window if it's open; usually used as onunload handler
    if (typeof(rib_window) != 'undefined' && !rib_window.closed) {
        rib_window.close();
    }
    if (typeof(mcb_window) != 'undefined' && !mcb_window.closed) {
        mcb_window.close();
    }
}

/**
 * Opens a preview window of the given form.
 *
 * The URL of the preview is the second passed parameter. With
 * optional paramters added to as query data.
 *
 * e.g.
 * <input type="submit" onclick="return openPreview(this.form, '/' + this.form.language.value + '/path/to/objects?id=20')" value="Preview" />
 * 
 * @param Node form The form object
 * @param String previewURL The preview url
 * @return boolean False
 */
function openPreview(form, previewURL) {
    var oldAction = form.action;
    form.target = 'preview';
    form.action = previewURL;
    setTimeout(function () { form.action = oldAction; form.target = ''; }, 1000);
    return true;
}

/**
 * Function closes the window and, optionally submits the form.
 *
 * If a form id is passed, the function retrieves it
 * from the opening window and submits it.
 *
 * @param string formId An optional form id
 */
function closePreview(formId) {
    window.close();
    if (formId) {
        var form = window.opener.document.getElementById(formId);
        if (typeof form != 'undefined') {
            form.submit();
        }
    }
    window.opener.focus();
    return false;
} 

/**
 * The advisor form  
 */
var advisorForm = {
    form: null,
    containers: {
        en: [],
        fr: []
    },
    chk: {
        en: null,
        fr: null
    }
}
    
/**
 * Initializes the advisor profile edit page.
 *
 * @param Node form The form
 */ 
function initAdvisorForm(form) {
    if (form.constructor == String) {
        form = document.getElementById(form);
    }
    if (!form) {
        return;
    } 
    var enChk = document.getElementById('input_en_enabled');
    var frChk = document.getElementById('input_fr_enabled');
    var enContainers = new Array();
    var frContainers = new Array();
    
    var containers = form.getElementsByTagName('div');
    for (var i in containers) {
        var c = containers[i];
        if (   typeof c.className != 'undefined'
            && c.className.match(/lang/)                 
            && c.id != 'fr_enabled_cont'
            && c.id != 'en_enabled_cont')
        {
            if (c.className.match(/lang-en/)) {
                enContainers[enContainers.length] = c;
            } else {
                frContainers[frContainers.length] = c;
            }
        }
    }
    if (enChk) {    
        $(enChk).observe('click', function() {
            toggleInput(this, 'en');
            togglePicture();
            if(layoutButtons != undefined){
                layoutButtons();
            }
            return true;
        }.bind(enChk));
    }
    if (frChk) {
        $(frChk).observe('click', function() {
            toggleInput(this, 'fr');
            togglePicture();
            if(layoutButtons != undefined){
                layoutButtons();
            }
            return true;
        }.bind(frChk));
    }
    
    // populates the advisorForm with all loaded info
    advisorForm.form = form;
    advisorForm.containers.en = enContainers;
    advisorForm.containers.fr = frContainers;
    advisorForm.chk.en = enChk;
    advisorForm.chk.fr = frChk;
    
    // calls the toggler
    toggleInput(enChk, 'en');
    toggleInput(frChk, 'fr');
}

/**
 * Toggle the display of english or french input fields
 *
 * @param Node input  The checkbox
 * @param String lang The language
 */
function toggleInput(input, lang) {
    lang = lang || 'en';
    var containers = advisorForm.containers[lang];
    if (!containers) {
        return;
    }
    if (Prototype.Browser.Gecko) {
        // otherwise the rte fields become un-usable
        var position = input.checked ? 'relative' : 'absolute';
        var top      = input.checked ? '0'        : '-1000000px';
        for (var i = 0, c = containers.size(); i < c; i++) {
            containers[i].style.position   = position;        
            containers[i].style.top        = top;
        }
    } else {   
        var display = input.checked ? '' : 'none';
        for (var i = 0, c = containers.size(); i < c; i++) {
            containers[i].style.display = display;
        }
    }
    var displayParent = advisorForm.chk.en.checked || advisorForm.chk.fr.checked ? '' : 'none';
    //document.getElementById('preview-btn').style.display = displayParent;
    
    var displayParentEn = advisorForm.chk.en.checked ? '' : 'none'; 
    var displayParentFr = advisorForm.chk.fr.checked ? '' : 'none'; 
    if($('preview-btn-en') && $('preview-btn-fr')) {
        document.getElementById('preview-btn-en').style.display = displayParentEn;
        document.getElementById('preview-btn-fr').style.display = displayParentFr;
    }
    
    // hides the wrapper of all language dependant elements
    var wrap = document.getElementById('profile_profile');
    if (wrap.nodeName.toLowerCase() == 'tr') {
        var containers = advisorForm.containers.en;
        for (var i = 0, c = containers.length; i < c; i++) {
            containers[i].parentNode.parentNode.style.display = displayParent;
        }
    }
     
    wrap.style.display = displayParent;
}

/**
 * Hides a container with no visible child.
 *
 * @param Node node The node to show or hide
 */
function toggleNodeVisibility(node) {
    var children = node.childNodes;
    var visibleFound = false;
    for (var i = 0, c = children.length; i < c && !visibleFound; i++) {
        var c = children[i];
        // ignore all but elements
        if (c.nodeType != Node.ELEMENT_NODE)
            continue; 
        if (typeof c.style.display == 'undefined' || c.style.display != 'none')
            visibleFound = true;
    }
    node.style.display = visibleFound ? '' : 'none';
}

/**
 * Toggle the display of the picture fields
 *
 */
function togglePicture() {
    var enCap = $('input_en_portrait_caption');
    var frCap = $('input_fr_portrait_caption');
    var photoDiv = $('lang-en-fr');
    
    if(!photoDiv) return;
    
    if( !enCap || !frCap) return;

    if(!advisorForm.chk.en.checked && !advisorForm.chk.fr.checked) {
        photoDiv.hide();
    }
    else {
        photoDiv.show();
    }
}