/* determines if form was submited - needed to prevent multiple submits of this same data*/
var submit_was_called = false;

function getSelectedRadio(buttonGroup) {
    // returns the array number of the selected radio button or -1 if no button is selected
    if (buttonGroup[0]) { // if the button group is an array (one button is not an array)
        for (var i=0; i<buttonGroup.length; i++) {
            if (buttonGroup[i].checked) {
                return i
            }
        }
    } else {
        if (buttonGroup.checked) { return 0; } // if the one button is checked, return zero
    }
    // if we get to this point, no radio button is selected
    return -1;
} // Ends the "getSelectedRadio" function

function selectRadioByValue(buttonGroup, val) {
    if (buttonGroup[0]) { // if the button group is an array (one button is not an array)
        for (var i=0; i<buttonGroup.length; i++) {
            if (buttonGroup[i].value == val) {
                buttonGroup[i].checked = true;
                return i;
            }
        }
    } else {
        if (buttonGroup.value == val) {
            buttonGroup.checked = true;
            return -1;
        } // if the one button is checked, return zero
    }
}

function getSelectedRadioValue(buttonGroup) {
    // returns the value of the selected radio button or "" if no button is selected
    var i = getSelectedRadio(buttonGroup);
    if (i == -1) {
        return '';
    } else {
        if (buttonGroup[i]) { // Make sure the button group is an array (not just one button)
            return buttonGroup[i].value;
        } else { // The button group is just the one button, and it is checked
            return buttonGroup.value;
        }
    }
} // Ends the "getSelectedRadioValue" function


function checkSelected(buttonGroup) {
    var i = getSelectedRadio(buttonGroup);
    if (i == -1) {
        return false;
    } else {
        return true;
    }
}

function formCheckSelectedRadio(buttonGroup, text) {
    if (!checkSelected(buttonGroup)) {
        alert(text);
        submit_was_called = false;
        return false;
    } else {
        return true;
    }
}

/**
* Submit the admin form
* @todo delete checkonsubmit - it is unneccessary now since onsubmit is run automaticaly
*/
function submitform(formname, pressbutton, action, checkonsubmit){
    if (!submit_was_called) {

        /* check if there is a form to submit */
        if (!document || !document.forms || !document.forms[formname]) {
            /*
            *there is no form to submit
            *witch means that we just have to follow the link
            *so we must return true to activate the link
            */
            return true;
        }

        // remeber that form was submited
        submit_was_called = true;
        document.forms[formname].action     = action;
        document.forms[formname].task.value = pressbutton;
        if (typeof document.forms[formname]['onsubmit'] == 'function') {
            try {
                if (checkonsubmit) {
                    if (!document.forms[formname].onsubmit()) {
                        return false;
                    }
                }
            } catch(e) {
                return false;
            }
        }
        document.forms[formname].submit();
        return false;
    } else {
        // form was submited - do nothing
        return false;
    }
}

function countdown_clock(year, month, day, hour, minute, second, format)
{
    //I chose a div as the container for the timer, but
    //it can be an input tag inside a form, or anything
    //who's displayed content can be changed through
    //client-side scripting.
    html_code = '<span id="countdown"></span>';
    document.write(html_code);
    countdown(year, month, day, hour, minute, second, format);
}

function countdown(year, month, day, hour, minute, second, format)
{
    Today = new Date();
    Todays_Year  = Today.getFullYear() - 2000;
    Todays_Month = Today.getMonth() + 1;

    //Convert both today's date and the target date into miliseconds.
    Todays_Date = (new Date(Todays_Year, Todays_Month, Today.getDate(),
    Today.getHours(), Today.getMinutes(), Today.getSeconds())).getTime();
    Target_Date = (new Date(year, month, day, hour, minute, second)).getTime();

    //Find their difference, and convert that into seconds.
    Time_Left = Math.round((Target_Date - Todays_Date) / 1000);

    if (Time_Left < 0) {
        Time_Left = 0;
    }

    countdown_div = document.getElementById('countdown');

    switch (format) {
        case 0:
        //The simplest way to display the time left.
        countdown_div.innerHTML = Time_Left + ' seconds';
        break;
        case 1:
        //More datailed.
        days = Math.floor(Time_Left / (60 * 60 * 24));
        Time_Left %= (60 * 60 * 24);
        hours = Math.floor(Time_Left / (60 * 60));
        Time_Left %= (60 * 60);
        minutes = Math.floor(Time_Left / 60);
        Time_Left %= 60;
        seconds = Time_Left;

        dps = 's'; hps = 's'; mps = 's'; sps = 's';
        //ps is short for plural suffix.
        if(days == 1) dps ='';
        if(hours == 1) hps ='';
        if(minutes == 1) mps ='';
        if(seconds == 1) sps ='';

        countdown_div.innerHTML  = days    + ' day'    + dps + ' ';
        countdown_div.innerHTML += hours   + ' hour'   + hps + ' ';
        countdown_div.innerHTML += minutes + ' minute' + mps + ' and ';
        countdown_div.innerHTML += seconds + ' second' + sps;
        break;

        case 2:
        //More datailed.
        Time_Left %= (60 * 60 * 24);
        hours = Math.floor(Time_Left / (60 * 60));
        Time_Left %= (60 * 60);
        minutes = Math.floor(Time_Left / 60);
        if (minutes < 10) minutes = '0' + minutes;
        Time_Left %= 60;
        seconds = Time_Left;
        if (seconds < 10) seconds = '0' + seconds;

        countdown_div.innerHTML  = '';
        if (hours > 0) countdown_div.innerHTML += hours   + ':';
        countdown_div.innerHTML += minutes + ':';
        countdown_div.innerHTML += seconds;
        if (hours == '0' && minutes == '00' && seconds == '00') {
            window.location.replace('?m=panel&a=after_login');
        }
        break;

        default:
        countdown_div.innerHTML = Time_Left + ' seconds';
    }

    //Recursive call, keeps the clock ticking.
    setTimeout('countdown(' + year + ',' + month + ',' + day + ',' + hour + ',' + minute + ',' + second + ',' + format + ');', 1000);
}

/*
name - name of the cookie
[path] - path of the cookie (must be same as path used to create cookie)
[domain] - domain of the cookie (must be same as domain used to
create cookie)
path and domain default if assigned null or omitted if no explicit
argument proceeds
*/
function deleteCookie(name, path, domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

/*
name - name of the desired cookie
return string containing value of specified cookie or null
if cookie does not exist
*/
function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else
    begin += 2;
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    end = dc.length;
    return unescape(dc.substring(begin + prefix.length, end));
}

/*
name - name of the cookie
value - value of the cookie
[expires] - expiration date of the cookie
(defaults to end of current session)
[path] - path for which the cookie is valid
(defaults to path of calling document)
[domain] - domain for which the cookie is valid
(defaults to domain of calling document)
[secure] - Boolean value indicating if the cookie transmission requires
a secure transmission
* an argument defaults when it is assigned null as a placeholder
* a null placeholder is not required for trailing omitted arguments
*/

function setCookie(name, value, expires, path, domain, secure) {
    var curCookie = name + "=" + escape(value) +
    ((expires) ? "; expires=" + expires.toGMTString() : "") +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    ((secure) ? "; secure" : "");
    document.cookie = curCookie;
}

function testCookie() {
    document.getElementById('cookiewarning').style.display = (document.cookie ? 'none' : '');
}

function loginOnLoad() {
    //    document.getElementById('loginsubmitbutton').type = 'button';
    document.getElementById('login').focus();
    testCookie();
}

//get width of text element
function widthEl(span){

    if (document.layers){
        w=document.layers[span].clip.width;
    } else if (document.all && !document.getElementById){
        w=document.all[span].offsetWidth;
    } else if(document.getElementById){
        w=document.getElementById(span).offsetWidth;
    }
    return w;
}

//get height of text element
function heightEl(span){

    if (document.layers){
        h=document.layers[span].clip.height;
    } else if (document.all && !document.getElementById){
        h=document.all[span].offsetHeight;
    } else if(document.getElementById){
        h=document.getElementById(span).offsetHeight;
    }
    return h;
}
var alreadySelected = '';
/*select row*/
function sr(rid, document_form_id) {
    if (!document.getElementById) {
        return;
    }

    if (!document_form_id) {
        document_form_id = document.form.id;
    }

    /*unselect already selected*/
    if (alreadySelected) {
        E = document.getElementById(alreadySelected);
        E.className = 'withborder';
        /*select second selected row*/
        E = document.getElementById(alreadySelected +'_second_row');
        if (E) {
            E.className = 'withborder';
        }
    }

    /*select selected row*/
    E = document.getElementById(rid);
    E.className = 'selected';

    /*select second selected row*/
    E = document.getElementById(rid +'_second_row');
    if (E) {
        E.className = 'selected';
    }

    /*select radio*/
    selectRadioByValue(document_form_id, rid);
    alreadySelected = getSelectedRadioValue(document_form_id);
}
/*onmouseover and onmouseout rows hightlight*/
function highlightrows(id){
    if (!document.getElementById) {
        return;
    }
    var i, E = document.getElementById(id), tr;
    if (E && E.tagName == 'TABLE') {
        tr = E.getElementsByTagName('TR');
        for (i = 0; i <tr.length ; i++) {
            tr[i].onmouseover = function() {
                if (this.className != 'selected') this.className = 'listover';
                idstr = this.id;
                start = idstr.indexOf('_second_row');
                if (start > 0) {
                    idstr = idstr.substring(0, start);
                } else {
                    idstr = idstr + '_second_row';
                }

                EE = document.getElementById(idstr);
                if (EE) {
                    if (EE.className != 'selected') EE.className = 'listover';
                }
            }
            tr[i].onmouseout = function() {
                if (this.className != 'selected') this.className = 'withborder';
                idstr = this.id;
                start = idstr.indexOf('_second_row');
                if (start > 0) {
                    idstr = idstr.substring(0, start);
                } else {
                    idstr = idstr + '_second_row';
                }
                EE = document.getElementById(idstr);
                if (EE) {
                    if (EE.className != 'selected') EE.className = 'withborder';
                }
            }
        }
    }
}

function selectFirstRow() {
    tab_ = $('tab');
    tr = tab_.getElementsByTagName('TR');
    for (i = 0; i <tr.length ; i++) {
        if (tr[i].onclick) {
            tr[i].onclick();
            return;
        }
    }
}

/* disable and enable forma action buttons depending on choosen node (user or group)*/
function activateUserTreeFunctions(id,current_user,type,has_children) {
    au = $('form_action_add_user');
    eg = $('form_action_edit_group');
    dg = $('form_action_delete_group');
    eu = $('form_action_edit_user');
    du = $('form_action_delete_user');
    fa = $('form_action_functions_access');
    da = $('form_action_data_access');
    re = $('form_action_regenerate');
    if (type == 'User') {
        // off
        if (au) au.style.display = 'none';
        if (eg) eg.style.display = 'none';
        if (dg) dg.style.display = 'none';
        // on
        if (eu) eu.style.display = '';
        if (re) re.style.display = '';
        if (du && !has_children && !current_user) {
            du.style.display = '';
        } else {
            du.style.display = 'none';
        }
    } else {
        // group
        // on
        if (au) au.style.display = '';
        if (eg) eg.style.display = '';
        if (dg && !has_children) {
            dg.style.display = '';
        } else {
            dg.style.display = 'none';
        }

        // off
        if (eu) eu.style.display = 'none';
        if (du) du.style.display = 'none';
        if (re) re.style.display = 'none';
    }
    if (current_user) {
        if (fa) fa.style.display = 'none';
        if (da) da.style.display = 'none';
        if (re) re.style.display = 'none';
    } else {
        if (fa) fa.style.display = '';
        if (da) da.style.display = '';
    }
}


/* disable and enable forma action buttons depending on choosen node (user or group)*/
function activateSiteMapTreeFunctions(id,type,has_children,has_grid,visible) {
    //    ap = $('form_action_add_page');
    e = $('form_action_enable');
    d = $('form_action_disable');
    iv = $('form_action_view');
    ie = $('form_action_edit');
    el = $('form_action_edit_link');
    dl = $('form_action_delete_link');
    ep = $('form_action_edit_page');
    eg = $('form_action_edit_grid');
    dp = $('form_action_delete_page');
    if (type == 'page') {
        // off
        if (el) el.style.display = 'none';
        if (dl) dl.style.display = 'none';
        // on
        if (ep) ep.style.display = '';
        if (iv) iv.style.display = '';
        if (ie) ie.style.display = '';

        if (dp && !has_children) {
            if (dp) dp.style.display = '';
        } else {
            if (dp) dp.style.display = 'none';
        }
    } else {
        // link
        // on
        //        if (ap) ap.style.display = '';
        if (el) el.style.display = '';
        if (dl && !has_children) {
            if (dl) dl.style.display = '';
        } else {
            if (dl) dl.style.display = 'none';
        }

        // off
        if (ep) ep.style.display = 'none';
        if (dp) dp.style.display = 'none';
        if (iv) iv.style.display = 'none';
        if (ie) ie.style.display = 'none';
    }
    if (id == '1') {
        if (ep) ep.style.display = 'none';
        if (dp) dp.style.display = 'none';
        if (el) el.style.display = 'none';
        if (dl) dl.style.display = 'none';
        if (iv) iv.style.display = 'none';
        if (ie) ie.style.display = 'none';
        if (d)  d.style.display  = 'none';
        if (e)  e.style.display  = 'none';
    }
    if (eg && has_grid) {
        if (eg) eg.style.display = '';
    } else {
        if (eg) eg.style.display = 'none';
    }

    if (id != '1') {
        if (d) d.style.display = visible ? '' : 'none';
        if (e) e.style.display = visible ? 'none' : '';
    }
}

/* disable and enable forma action buttons depending on choosen node (user or group)*/
function activateDownloadTreeFunctions(id, visible) {
    //    ap = $('form_action_add_page');
    e = $('form_action_enable');
    d = $('form_action_disable');

    if (d) d.style.display = visible ? '' : 'none';
    if (e) e.style.display = visible ? 'none' : '';
}

/* hide form action buttons - used when highlight rows has no rows*/
function hideEnableAndDisableActionButtons() {
    e = $('form_action_enable');
    d = $('form_action_disable');

    if (d) d.style.display = 'none';
    if (e) e.style.display = 'none';
}

/********************** grid *********************/
var id = 0;
var grid_step = 5;
var confirmation_string = '';
var obj = new Array;

function save_nodes(form) {
    fname = form.name;
    var str = '';

    grid_ = $('grid');
    str   = str + ':grid:' + grid_.style.width + ':' + grid_.style.height + ':' + grid_.offsetTop + ':' + grid_.offsetLeft + '|';

    if (obj && obj.length) {
        for (i = 0; i < obj.length; i++) {
            if (obj[i].deleted && obj[i].InstanceId) {
                str = str + obj[i].InstanceId + ':deleted::::|';
            } else {
                if (!obj[i].deleted) {
                    o = $(obj[i].type +'_f'+i);
                    inst = o.getAttribute('instanceId');
                    inst = inst ? inst : '';
                    str = str + inst + ':' + obj[i].type + ':' + o.style.width + ':' + o.style.height + ':' + o.offsetTop + ':' + o.offsetLeft + '|';
                }
            }
        }
    }
    document.forms[fname].gridcomposition.value = str;
    return true;
}

function delete_node(id_) {
    o    = $(obj[id_].type+'_f'+id_);
    inst = o.getAttribute('instanceId');
    inst = inst ? inst : '';
    obj[id_].InstanceId = inst;
    obj[id_].id.destroy();
    Element.remove(o);
    obj[id_].deleted = 1;
}

function increase_grid(px) {
    $('grid').style.height = $('grid').clientHeight+px+'px';
}
function decrease_grid(px) {
    $('grid').style.height = $('grid').clientHeight-px+'px';
}
function add_node(type) {
    div = document.createElement('div');
    div.id = type+'_f'+id;
    bar = document.createElement('div');
    bar.id = type+'_b'+id;
    Element.setStyle(bar, {background:'#B1FFAF', width: '100%', top: 0, position: 'absolute', cursor: 'move'});
    //    Element.setStyle(bar, {background: '#ee0000'});
    bar.innerHTML = '<span style="float: right; cursor: pointer;" onclick="if (confirm(\''+confirmation_string+'\')) delete_node('+id+');" title="'+ type + id +'"><strong><font color="red">X&nbsp;&nbsp;&nbsp;</font></strong></span>';

    div.appendChild(bar);
    Element.setStyle(div, {	width: '100px', height: '100px', border:'1px solid #B1FFAF', background: '#eee', position: 'absolute', top: grid_step+'px', left: grid_step+'px', overflow:'hidden'});
    $('grid').appendChild(div);
    obj[id] = {type: type, id: new Draggable(type+'_f'+id, {handle: type+'_b'+id,snap: function(x,y,draggable) {
        function constrain(n, lower, upper, snapto) {
            if (n > upper) return upper;
            else if (n < lower) return lower;
            else return (n % snapto) ? (n - (n % snapto)) : n;
        }

        element_dimensions = Element.getDimensions(draggable.element);
        parent_dimensions = Element.getDimensions(draggable.element.parentNode);
        return[
        constrain(x, 0, parent_dimensions.width  - element_dimensions.width, grid_step),
        constrain(y, 0, parent_dimensions.height - element_dimensions.height, grid_step)];
    }})};
    new Resizeable(type+'_f'+id, {resizeStepY: grid_step, resizeStepX: grid_step, left:0, top:0});
    id = id + 1;
    //    Element.setOpacity(div, 0.5);
}
function init_grid(txt) {
    confirmation_string = txt;
    gh = $('grid').style.height;
    gw = $('grid').style.width;
    // instead of getting elements by tag name
    //divs = $('grid').getElementsByTagName('DIV');
    //we scan only divs witch are first childs of grid element
    divs = $('grid').childNodes;
    len  = divs.length;
    divs_ = new Array();
    counter = 0;

    for (i = 0; i < len; i++) {
        if (divs[i].nodeName == 'div' || divs[i].nodeName == 'DIV')
        divs_[divs_.length] = divs[i];
    }
    divs = divs_;
    len  = divs.length;

    for (i = 0; i < len; i++) {
        // this is probably no longer necessary when we scan only divs witch are first childs of grid element
        //j = i*2;
        j=i;

        // create bar element
        over_ = document.createElement('span');
        bar  = document.createElement('div');
        type = divs[j].id;
        type = type.split('_');
        type = type[0];
        Element.setStyle(divs[j], {background:'#FFFFAA'});

        bar.id = type+'_b'+i;
        Element.setStyle(bar, {background:'lightblue', width: '100%', top: 0, position: 'absolute', cursor: 'move'});
        Element.setOpacity(bar, 0.5);
        bar.innerHTML = '<span style="float: right; cursor: pointer;" onclick="if (confirm(\''+confirmation_string+'\')) delete_node('+i+');" title="'+ type +'"><strong><font color="red">X&nbsp;&nbsp;&nbsp;</font></strong></span>';

        divs[j].insertBefore(bar, divs[j].firstChild);

        obj[i] = {type: type, id: new Draggable(type+'_f'+i, {handle: type+'_b'+i,snap: function(x,y,draggable) {
            function constrain(n, lower, upper, snapto) {
                if (n > upper) return upper;
                else if (n < lower) return lower;
                else return (n % snapto) ? (n - (n % snapto)) : n;
            }

            element_dimensions = Element.getDimensions(draggable.element);
            parent_dimensions  = Element.getDimensions(draggable.element.parentNode);
            return[
            constrain(x, 0, parent_dimensions.width  - element_dimensions.width, grid_step),
            constrain(y, 0, parent_dimensions.height - element_dimensions.height, grid_step)];
        }
        })};
        new Resizeable(type+'_f'+i, {resizeStepY: grid_step, resizeStepX: grid_step, left:0, top:0});
    }
    id = len;
    return false;
}

function switchPreviewAndEditMode() {
    if (typeof EDITMODE == "undefined") {
        EDITMODE = true;
    }
    if (EDITMODE) {
        EDITMODE = false;
    } else {
        EDITMODE = true;
    }

    v = $('form_action_view');
    e = $('form_action_edit');
    g = $('form_action_edit_grid');
    enableDisableGridButton(0, '');

    // off/on buttons
    if (e) e.style.display = EDITMODE ? 'none' : '';
    if (g) g.style.display = EDITMODE ? 'none' : '';
    if (v) v.style.display = EDITMODE ? '' : 'none';
    return false;
}

function switchPreviewAndEditGridMode(deleteConfirm, grid_background) {
    enableDisableGridButton(true, grid_background);

    v = $('form_action_view');
    e = $('form_action_edit');
    g = $('form_action_edit_grid');
    c = $('form_action_cancel');

    // off/on buttons
    if (e) e.style.display = EDITMODE ? 'none' : 'none';
    if (g) g.style.display = EDITMODE ? 'none' : 'none';
    if (v) v.style.display = EDITMODE ? 'none' : 'none';
    if (c) c.style.display = EDITMODE ? 'none' : 'none';
    init_grid(deleteConfirm);
    return false;
}

/* disable and enable form action buttons depending on choosen field type*/
function activateFormNextFunctions(type) {
    fa = $('form_action_next');
    if (type) {
        if (fa) fa.style.display = 'none';
    } else {
        if (fa) fa.style.display = '';
    }
}

function enableDisableGridButton(ENABLE, grid_background)
{
    buttons = new Array('add_link','add_imagelink','add_text','add_textarea','add_image','add_colorbar',
    'increse','decrese','apply','save','save_as','cancel_grid','add_plugin');
    for (i = 0; i < buttons.length; i++) {
        button = $('form_action_'+buttons[i]);
        if (button) button.style.display = ENABLE ? '' : 'none';
    }
    if (ENABLE && $('grid')) {
        $('grid').style.background =  'url('+grid_background+') repeat';
    }
}

function resizeGrid() {
    divs = document.getElementById('grid').getElementsByTagName('DIV');
    len  = divs.length
    max_ = 0;
    for (i = 0; i < len; i++) {
        top_ = divs[i].style.top;
        if (typeof top_ == 'string') {
            top_ = top_.replace('px','');
            top_ = top_ * 1;
        }
        height_ = divs[i].offsetHeight;
        if (typeof height_ == 'string') {
            height_ = height_.replace('px','');
            height_ = height_ * 1;
        }
        m_ = top_+height_
        max_ = (max_ >= m_) ? max_ : m_;
        jQuery.noConflict();
        jQuery('#grid').height(max_);
    }
}
