function checkAll(f, act)
{
    var frameId = f.getAttribute('attr_frame_id');
    var eId = 'active' == act ? 'check_active_id' : 'check_delete_id';
    if (frameId > 0)  {
        var e = getFrameElementById(frameId, eId);
    } else {
        var e = document.getElementById(eId);
    }
    var checked = 'Click to check all' == e.title ? 0 : 1;
    checked = !checked;
    var els = document.getElementsByName(act + 'IdArr[]');
    for (var i = 0; i < els.length; i++) {
        if (!els[i].disabled) {
            els[i].checked = checked;
        }
    }
    if (checked) {
        e.title = 'Click to uncheck all';
    } else {
        e.title = 'Click to check all';
    }
}

function applyClick(f, act)
{
    if ('apply' == act || 'delete' == act) {
        var checkedItems = 0;
        var els = document.getElementsByName('deleteIdArr[]');
        for (i = 0; i < els.length; i++) {
            if (els[i].checked) {
                checkedItems++;
            }
        }
        if (checkedItems) {
            if (checkedItems == 1) {
                var ok = confirm('You are about to delete ' + checkedItems + ' item. Proceed?');
            } else {
                var ok = confirm('You are about to delete ' + checkedItems + ' items. Proceed?');
            }
            if (!ok) {
                return false;
            }
        }
    }
    if ('function' == typeof submit_click) {
        submit_click();
    }
    f.submitAction.value = act;
    f.submit();
    f.submitAction.value = '';
}

function listApply(form, action, prompt)
{
    if (!action || action == 'apply' || prompt) {
        var checkedItems = deletedItems = 0;
        for (i = 0; i < form.elements.length; i++) {
            if (form.elements[i].tagName == 'INPUT'
            && form.elements[i].type == 'checkbox'
            && form.elements[i].checked) {
                if (form.elements[i].name.substr(0, 6) == "delete") {
                    deletedItems++;
                }
                checkedItems++;
            }
        }
        if (!checkedItems) {
            alert('Please select at least one item.');
            return false;
        }
        if (deletedItems != 0) {
            var ok = confirm('You are about to delete ' + deletedItems + ' item' +
                (deletedItems == 1 ? '' : 's') + '. Proceed?');
            if (!ok) {
                return false;
            }
        } else if (checkedItems != 0 && prompt) {
            var ok = confirm(prompt.replace('%n', checkedItems));
            if (!ok) {
                return false;
            }
        }
    }
    if (action && form.submitAction) {
        form.submitAction.value = action;
    }
    form.submit();
    return true;
}

var listCheckFlag_delete = true;
var listCheckFlag_active = false;
var selCounter = new Array();

function listCheckAll(form, action)
{
    var flag = eval('listCheckFlag_' + action);
    eval('listCheckFlag_' + action + ' = !flag');
    selCounter[action] = 0;
    for (var i = 0; i < form.elements.length; i++) {
        if (form.elements[i].name.substr(0, action.length) == action) {
            form.elements[i].checked = flag;
            if (flag) selCounter[action]++;
        }
    }
    refreshSelCounter(form, action, false);
}

function modifySelCounter(form, action, ctl)
{
    if (!selCounter[action]) selCounter[action] = 0;
    var cur = parseInt(ctl.getAttribute('_status'));
    if (cur && !ctl.checked) {
        selCounter[action]--;
    } else if (!cur && ctl.checked) {
        selCounter[action]++;
    }
    ctl.setAttribute('_status', ctl.checked ? 1 : 0);
    refreshSelCounter(form, action, false);
}

function refreshSelCounter(form, action, recalc)
{
    var e = document.getElementById('sel_counter_' + action);
    if (!e) return;
    var c;
    if (recalc) {
        c = 0;
        var els = form.elements;
        for (i = 0; i < els.length; i++) {
            var el = form.elements[i];
            if (el.name.substr(0, action.length) == action && el.checked) {
                c++;
            }
        }
        selCounter[action] = c;
    } else {
        c = selCounter[action];
    }
    e.innerHTML =
        (c == 0 ? 'No' : c.toString()) + ' ' + (c == 1 ? 'item' : 'items') + ' selected.';
}

function treeExpandRow(row)
{
    while (row && row.tagName != 'TR') row = row.parentNode;
	var exp = 1-parseInt(row.getAttribute('_expanded'));
    row.setAttribute('_expanded', exp);
    var img = document.getElementById(row.id + '_img');
    if (img) {
        if (img.src.indexOf('bottom') != -1) {
            img.src = exp ? '/core/images/tree/minusbottom.gif' : '/core/images/tree/plusbottom.gif';
        } else {
            img.src = exp ? '/core/images/tree/minus.gif' : '/core/images/tree/plus.gif';
        }
    }
    st = document.getElementById(row.id + '_st');
    if (st) st.value = exp;
    if (row.style.display == 'none') return;
    var level1 = row.getAttribute('_level');
    var rexp = new Array();
    rexp[level1] = 1;
    while (1) {
    	row = row.nextSibling;
    	if (!row) break;
    	if (row.tagName != 'TR' || row.getAttribute('_level') == ''
    		|| row.getAttribute('_level') == null) continue;
    	var level2 = parseInt(row.getAttribute('_level'));
    	if (level2 <= level1) break;
        var exp1;
        if (!exp) exp1 = 0;
        else {
            rexp[level2] = parseInt(row.getAttribute('_expanded'));
            exp1 = rexp[level2-1];
        }
        row.style.display = exp1 ? '' : 'none';
    }
}

function treeExpandRows(rows)
{
    for (var i=0; i<rows.length; i++) {
        treeExpandRow(rows[i]);
    }
}

var movedRow = null, moveTarget = null, movedRowIndex = 0,  mPos = '', oldNewRG = null, movedRowCC = 1;
function selMovedRow(row, sel)
{
    rows = row.parentNode.parentNode.rows;
    rowIndex = row.rowIndex;
    while (rows[rowIndex].getAttribute('onmouseover') != '' && rows[rowIndex].getAttribute('cc') != '' && parseInt(rows[rowIndex].getAttribute('cc')) == 0){
        rowIndex--;
    }
    movedRowCC = 1;
    if (rows[rowIndex].getAttribute('cc')){
        movedRowCC = parseInt(rows[rowIndex].getAttribute('cc'));
    }
    for(var j=rowIndex; j<rowIndex+movedRowCC; j++){
        rows[j].style.backgroundColor = sel ? '#EEEEEE' : 'transparent';
        for (var i = 0; i < row.cells.length; i++) {
            rows[j].cells[i].style.backgroundColor = sel ? '#EEEEEE' : 'transparent';
        }
    }
}

function startMoving(event)
{
	if (!event) event = window.event;
    movedRow = event.target ? event.target : event.srcElement;
    moveTarget = null;
    while (movedRow && movedRow.tagName != 'TR') movedRow = movedRow.parentNode;
    if (!movedRow) return;
    oldNewRG = null;
    movedRowIndex = movedRow.rowIndex;
    selMovedRow(movedRow, 1);
    document.body.style.cursor = 'move';
    if (is_msie()) {
        document.body.attachEvent("onmouseup", endMoving);
        document.body.attachEvent("onselectstart", movingSelectStart);
    } else {
        addEventListener("mouseup", endMoving, false);
        event.preventDefault();
    }
}

function moveRow(event)
{
    if (!movedRow) {
        return;
    }
	if (!event) event = window.event;
	if (mPos == event.clientX + ' ' + event.clientY) {
	    return;
	}
	mPos = event.clientX + ' ' + event.clientY;

    var newRow = event.target ? event.target : event.srcElement;
    while (newRow && newRow.tagName != 'TR') newRow = newRow.parentNode;
    if (!newRow) {
        return;
    }
    if ('prevPageRow' == newRow.id) {
        if ('function' == typeof moveToPrevPage) {
            moveToPrevPage();
        }
        return;
    }
    if ('nextPageRow' == newRow.id) {
        if ('function' == typeof moveToNextPage) {
            moveToNextPage();
        }
        return;
    }
    if (movedRow.rowIndex == newRow.rowIndex){
        oldNewRG = null;
        return;
    }
    moveTarget = newRow;

    var rows = movedRow.parentNode.parentNode.rows;
    // RG - first rowgroup item
    var newRG = newRow.rowIndex;
    while (rows[newRG].getAttribute('onmouseover') != '' && rows[newRG].getAttribute('cc') != ''
    && parseInt(rows[newRG].getAttribute('cc')) == 0) {
        newRG--;
    }
    var movedRG = movedRow.rowIndex;
    while (rows[movedRG].getAttribute('onmouseover') != '' && rows[movedRG].getAttribute('cc') != ''
    && parseInt(rows[movedRG].getAttribute('cc')) == 0) {
        movedRG--;
    }
    if (movedRG == newRG) {
        oldNewRG = null;
        return;
    }
    if (rows[newRG] == oldNewRG || rows[newRG].getAttribute('onmouseover') == null) {
        return;
    }
    oldNewRG = rows[newRG];

    var minRow = Math.min(movedRG, newRG);
    var maxRow = Math.max(movedRG, newRG);
    var maxRowCC = 1;
    if (rows[maxRow].getAttribute('cc')) {
        var maxRowCC = parseInt(rows[maxRow].getAttribute('cc'));
    }
    var first_node = rows[minRow];
    for (j = 0; j < maxRowCC; j++) {
        if (is_msie() && is_msie() <= 6) {
            var move_id = rows[maxRow+j].id;
            var statuses = getCheckBoxStatuses(rows[maxRow+j]);
        }
        movedRow.parentNode.insertBefore(rows[maxRow+j], first_node);
        if (is_msie() && is_msie() <= 6) {
            setCheckBoxStatuses(document.getElementById(move_id), statuses);
        }
    }
    return;
}

function endMoving(event)
{
    if (!movedRow) return;
	if (!event) event = window.event;
    var table = movedRow.parentNode;
    while (null != table && table.nodeName != 'TABLE') {
        table = table.parentNode;
    }
    document.body.style.cursor = 'auto';
    if (typeof(rowMoved) == "function" && moveTarget
    && moveTarget != movedRow && movedRow.rowIndex != movedRowIndex) {
    	rowMoved(movedRow, moveTarget);
    }
    selMovedRow(movedRow, 0);
    movedRow = null;
    moveTarget = null;
    if (is_msie()) {
        document.body.detachEvent("onmouseup", endMoving);
        document.body.detachEvent("onselectstart", movingSelectStart);
    } else {
        removeEventListener("mouseup", endMoving, false);
        event.preventDefault();
    }
}

function getCheckBoxStatuses(Element)
{
    var res = new Array();
    if(!Element) return res;
    var els = Element.getElementsByTagName('input');
    for (var i = 0; i < els.length; i++) {
        if (els[i].type=='checkbox') {
            res[els[i].name] = els[i].checked;
        }
    }
    return res;
}

function setCheckBoxStatuses(Element, statuses)
{
    if(!Element) return res;
    var els = Element.getElementsByTagName('input');
    for (var i = 0; i < els.length; i++) {
        if (els[i].type=='checkbox' && statuses[els[i].name] != undefined) {
            els[i].checked = statuses[els[i].name];
        }
    }
}

function movingSelectStart()
{
	return false;
}

var tooltipCtl = null;
var curTipId = '';
function tooltip(ctl, tip_id, event, width, color)
{
	var clr = color ? color : '#FFFFE0';
    var tw = width ? (width == 'auto' ? width : width + 'px') : '200px';
    if (!tooltipCtl) {
        tooltipCtl = document.createElement('DIV');
        tooltipCtl.style.backgroundColor = clr;
        tooltipCtl.style.border = 'solid 1px #808080';
        tooltipCtl.style.padding = '4px';
        tooltipCtl.style.visibility = 'hidden';
        tooltipCtl.style.position = 'absolute';
        tooltipCtl.style.zIndex = 10000;
        tooltipCtl.onmouseout = tooltipCtl.onclick = function()
	    {
	        tooltipCtl.style.visibility = 'hidden';
	        showElements();
	        curTipId = '';
	    };
        document.body.appendChild(tooltipCtl);
    }

    if (tip_id && tooltipCtl.style.width != tw) {
        tooltipCtl.style.width = tw;
    }
    if (!tip_id) {
        if (event.clientX + getScrollLeft() > parseInt(tooltipCtl.style.left) &&
            event.clientX + getScrollLeft() < parseInt(tooltipCtl.style.left) + tooltipCtl.clientWidth &&
            event.clientY + getScrollTop() > parseInt(tooltipCtl.style.top) &&
            event.clientY + getScrollTop() < parseInt(tooltipCtl.style.top) + tooltipCtl.clientHeight)
        return;
        tooltipCtl.style.visibility = 'hidden';
        showElements();
        curTipId = '';
    } else {
        var t = document.getElementById(tip_id);
        if (t && t.innerHTML) {
            tooltipCtl.style.visibility = 'visible';
            if (curTipId != tip_id) {
                tooltipCtl.innerHTML = t.innerHTML;
                curTipId = tip_id;
            }
            var left = event.clientX + 20 + getScrollLeft(),
                top = event.clientY + 20 + getScrollTop();
            left = Math.max(Math.min(left, getClientWidth() + getScrollLeft() -
                tooltipCtl.offsetWidth), 0);

            top = Math.max(Math.min(top, getClientHeight() + getScrollTop() -
                tooltipCtl.offsetHeight), 0);
            tooltipCtl.style.left = left + 'px';
            tooltipCtl.style.top = top + 'px';
            hideElements(tooltipCtl);
        }
    }
}

var balloonContainers = new Object();
function showBalloon(id, ctl, direction, container, xofs, yofs)
{
    var parent = document.getElementById('balloon_'+id);
    if (parent) {
        parent.style.display = '';
        var container = balloonContainers[id];
        container.style.display = '';
        return;
    }
    var msie = is_msie();
    var ext = msie && msie < 7.0 ? '.gif' : '.png';
    var bw = container.offsetWidth+28, bh = container.offsetHeight+28, bx, by, x, y;
    switch (direction) {
        case 'lt': ox = 5; oy = 5; break;
        case 'lb': ox = 5; oy = ctl.offsetHeight-5; break;
        case 'rt': ox = ctl.offsetWidth-5; oy = 5; break;
        case 'rb': ox = ctl.offsetWidth-5; oy = ctl.offsetHeight-5; break;
    }
    ox += xofs ? xofs : 0;
    oy += yofs ? yofs : 0;
    var a = getControlPixelPos(ctl, ox, oy, 0, 0), x = a[0], y = a[1];
    switch (direction) {
        case 'lt': bx = x-bw-36; by = y-bh-17; break;
        case 'lb': bx = x-bw-34; by = y+17; break;
        case 'rt': bx = x+37; by = y-bh-17; break;
        case 'rb': bx = x+36; by = y+17; break;
    }
    var parent = document.createElement('DIV');
    parent.id = 'balloon_'+id;
    parent.style.position = 'absolute';
    parent.style.left = parent.style.top = parent.style.width = parent.style.height = '0px';
    document.body.appendChild(parent);
    var back = document.createElement('DIV');
    back.style.position = 'absolute'; back.style.left = bx+6+'px'; back.style.top = by+6+'px';
    back.style.width = bw-12+'px'; back.style.height = bh-12+'px';
    back.style.background = '#fffde1';
    parent.appendChild(back);
    var img = document.createElement('IMG');
    img.src = '/core/images/balloons/lt' + ext;
    img.style.position = 'absolute'; img.style.left = bx+'px'; img.style.top = by+'px';
    img.style.width = 12+'px'; img.style.height = 12+'px';
    parent.appendChild(img);
    var img = document.createElement('IMG');
    img.src = '/core/images/balloons/rt' + ext;
    img.style.position = 'absolute'; img.style.left = bx+bw-12+'px'; img.style.top = by+'px';
    img.style.width = 12+'px'; img.style.height = 12+'px';
    parent.appendChild(img);
    var img = document.createElement('IMG');
    img.src = '/core/images/balloons/lb' + ext;
    img.style.position = 'absolute'; img.style.left = bx+'px'; img.style.top = by+bh-12+'px';
    img.style.width = 12+'px'; img.style.height = 12+'px';
    parent.appendChild(img);
    var img = document.createElement('IMG');
    img.src = '/core/images/balloons/rb' + ext;
    img.style.position = 'absolute'; img.style.left = bx+bw-12+'px'; img.style.top = by+bh-12+'px';
    img.style.width = 12+'px'; img.style.height = 12+'px';
    parent.appendChild(img);
    var img = document.createElement('IMG');
    img.src = '/core/images/balloons/l' + ext;
    img.style.position = 'absolute'; img.style.left = bx+'px'; img.style.top = by+12+'px';
    img.style.width = 6+'px'; img.style.height = bh-24+'px';
    parent.appendChild(img);
    var img = document.createElement('IMG');
    img.src = '/core/images/balloons/t' + ext;
    img.style.position = 'absolute'; img.style.left = bx+12+'px'; img.style.top = by+'px';
    img.style.width = bw-24+'px'; img.style.height = 6+'px';
    parent.appendChild(img);
    var img = document.createElement('IMG');
    img.src = '/core/images/balloons/r' + ext;
    img.style.position = 'absolute'; img.style.left = bx+bw-6+'px'; img.style.top = by+12+'px';
    img.style.width = 6+'px'; img.style.height = bh-24+'px';
    parent.appendChild(img);
    var img = document.createElement('IMG');
    img.src = '/core/images/balloons/b' + ext;
    img.style.position = 'absolute'; img.style.left = bx+12+'px'; img.style.top = by+bh-6+'px';
    img.style.width = bw-24+'px'; img.style.height = 6+'px';
    parent.appendChild(img);
    container.style.position = 'absolute';
    container.style.left = bx+12+'px';
    container.style.top = by+12+'px';
    container.style.width = bw-24+'px';
    container.style.height = bh-24+'px';
    container.style.background = '#fffde1';
    container.style.zIndex = 10000;
    balloonContainers[id] = container;
    container.style.visibility = 'visible';
    var img = document.createElement('IMG');
    img.style.position = 'absolute';
    switch (direction) {
        case 'lt' :
            img.src = '/core/images/balloons/arrow_rb' + ext;
            img.style.left = x-52+'px'; img.style.top = y-36+'px';
            img.style.width = 52+'px'; img.style.height = 36+'px';
            break;
        case 'lb' :
            img.src = '/core/images/balloons/arrow_rt' + ext;
            img.style.left = x-52+'px'; img.style.top = y+'px';
            img.style.width = 52+'px'; img.style.height = 36+'px';
            break;
        case 'rt' :
            img.src = '/core/images/balloons/arrow_lb' + ext;
            img.style.left = x+'px'; img.style.top = y-36+'px';
            img.style.width = 52+'px'; img.style.height = 36+'px';
            break;
        case 'rb' :
            img.src = '/core/images/balloons/arrow_lt' + ext;
            img.style.left = x+'px'; img.style.top = y+'px';
            img.style.width = 52+'px'; img.style.height = 36+'px';
            break;
    }
    parent.appendChild(img);
}

function hideBalloon(id)
{
    var parent = document.getElementById('balloon_'+id);
    if (parent) {
        parent.style.display = 'none';
        var container = balloonContainers[id];
        container.style.display = 'none';
    }
}

var ajaxInRequest = false, ajaxQueue = new Array(), onEndAjaxEvents = new Array();
function AjaxRequest(url)
{
    if (ajaxInRequest) {
        ajaxQueue.push(url);
        return;
    }
    ajaxInRequest = true;
    var head = document.getElementsByTagName('head').item(0);
    var old = document.getElementById("AJAXScript");
    if (old) head.removeChild(old);
    var script = document.createElement("SCRIPT");
    script.src = url + "&ajaxrequest=" + Math.random().toString() +
        "&ajaxqs=" + escape(location.search);
    script.type = "text/javascript"
    script.id = "AJAXScript";
    head.appendChild(script);
}

function AjaxEndRequest()
{
    ajaxInRequest = false;
    if (ajaxQueue.length) {
        var url = ajaxQueue.shift();
        AjaxRequest(url);
    } else {
        if (typeof(hideWaitWnd) == "function") hideWaitWnd();
        if (typeof(hiddedByAjaxRefresh) == "object") {
            for (var i = 0; i < hiddedByAjaxRefresh.length; i++) {
                var ctl = hiddedByAjaxRefresh[i],
                    t = ctl.getAttribute('ajaxDisabled');
                if (t) ctl.disabled = t == 'yes';
                else ctl.disabled = false;
            }
            hiddedByAjaxRefresh = [];
        }
        for(var i = 0; i < onEndAjaxEvents.length; i++) {
        	onEndAjaxEvents[i]();
        }
        onEndAjaxEvents = [];
    }
}

function AjaxRefresh(args)
{
    var url = window.location.href;
    if (args) {
    	url += (-1 == url.indexOf('?') ? '?' : '&') + args;
    }
    AjaxRequest(url);
}

function addOnEndAjaxEvent(func) {
	if (typeof(func) == 'function') {
		onEndAjaxEvents.push(func);
	}
}

var defaultLocale = { currency_sign: '$', sign_position: 'before', thousand_sep: ',',
    decimal_sep: '.', rate: 1  };
var frameLocale = [];

function numberFormat(value, frameId)
{
    var locale = frameId && frameLocale[frameId] ? frameLocale[frameId] : defaultLocale;
    var str = (Math.round(value * 100) / 100).toFixed(2);
    var dot = str.indexOf('.'), v1, v2;
    if (dot != -1) {
        v1 = str.substring(0, dot);
        v2 = str.substring(dot + 1, str.length);
    } else {
        v1 = str;
        v2 = '00';
    }
    var rem = 0;
    var res = '';
    while (v1 >= 1000) {
        rem = v1 % 1000;
        while (rem.toString().length < 3) rem = '0' + rem;
        res = locale.thousand_sep + rem + res;
        v1 = Math.floor(v1 / 1000);
    }
    return v1 + res + locale.decimal_sep + v2;
}

function currencyFormat(value, frameId)
{
    var locale = frameId && frameLocale[frameId] ? frameLocale[frameId] : defaultLocale;
    var res = numberFormat(value*locale.rate, frameId);
    var space = locale.currency_sign.length == 3 ? ' ' : '';
    if (locale.sign_position == 'after') res += space + locale.currency_sign;
    else res = locale.currency_sign + space + res;
    return res;
}

function disableControls(form)
{
    for (var i = 0; i < form.elements.length; i++) {
        form.elements[i].disabled = true;
    }
}

preloadImages = [];
function preloadImage(url)
{
    var im = new Image;
    preloadImages.push(im);
    im.src = url;
}

var fileControlName = '';
var fileControlInfo = new Object();
function fileStoreShow(controlOrFunctionName, default_dir, type, max_width, max_height,
    max_images, single, enable_java)
{
    // max_images is used to limit number of items in fileds with multiple values
    if (type == 'image') {
        if (!max_images) max_images = 1;
        if (typeof(single) == 'undefined') single = 1;
    }
    fileControlName = controlOrFunctionName;
    fileControlInfo = { max_images: max_images, single: single };
    var f = document.getElementById(controlOrFunctionName + '[file]');
    var file_store_url = 'core/file_store/' + (type == 'image' ? 'img' : 'file') + '_store.php?' +
        'default_dir=' + escape(default_dir) +
        '&select=' + escape(f ? f.value : '') +
        '&type=' + escape(type) +
        '&max_width=' + escape(max_width ? max_width : '') +
        '&max_height=' + escape(max_height ? max_height : '')+
        '&enable_java=' + escape(typeof(enable_java) == 'undefined' ? 1 : (enable_java ? 1 : 0));

    popup_exec_url(file_store_url, null, 800, 500, false, null, 'Select ' + (type == 'image' ?'an Image':'a File'));
    popup_show_buttons(false);
}

function imageBoxRemoveImage(id)
{
    var box = document.getElementById(id);
    box.parentNode.removeChild(box);
}

function imageBoxAddImage(name, src, value, max_images, single, disabled)
{
    // Retrieve images container
    var imageset = document.getElementById(name);
    if (!imageset) {
        return false;
    }

    var num = imageset.getElementsByTagName('img').length;
    if (max_images == 1) {
        for (i = 0; i < num; i++) {
            imageset.removeChild(imageset.childNodes[i]);
        }
    } else {
        if (num >= max_images) {
            alert('Sorry, you can\'t add more than ' + max_images + ' images.');
            return false;
        }
    }

    // Define current image id and number
    var image_num = imageset.childNodes.length;
    var image_id   = name + '_' + image_num + '_pv';
    var remove_btn_id = name + '_' + image_num + '_remove';

    // Create div containing image
    var image_box = document.createElement('span');
    image_box.id = image_id;
    if (!disabled) {
	    image_box.onmouseover = function() {
	        var span = document.getElementById(remove_btn_id);
	        span.style.visibility = 'visible';
	        var box = span.parentNode.getElementsByTagName('IMG')[0];
	        span.style.left = box.offsetLeft + box.offsetWidth - 25 + 'px';
	        span.style.top = box.offsetTop + 1 + 'px';
	    };

	    image_box.onmouseout = function() {
	        var span = document.getElementById(remove_btn_id);
	        span.style.visibility = 'hidden';
	    };
    }
    image_box.className = 'box';

    var image = document.createElement('img');
    image.src = src + '&broken=1';
    image_box.appendChild(image);

    if (!disabled) {
	    // Create remove button
	    var remove_btn = document.createElement('div');
	    remove_btn.id = remove_btn_id;
	    remove_btn.className = 'imageset_add_button';
	    remove_btn.style.visibility = 'hidden';
	    remove_btn.onclick = function() { imageBoxRemoveImage(image_id); };
	    remove_btn.innerHTML = 'X';
	    image_box.appendChild(remove_btn);
    }

    // Create hidden form element
    var hidden = document.createElement('input');
    hidden.type = 'hidden';
    hidden.value = value;
    hidden.name = single ? name : name + '[]';
    hidden.id = name + '_' + image_num;
    image_box.appendChild(hidden);

    imageset.insertBefore(image_box, document.getElementById(name + '_add'));
    imageset.insertBefore(document.createTextNode(' '), document.getElementById(name + '_add'));
}

searchFormInfo = {};
function searchFormClear(name)
{
    var visctl = document.getElementById('sf_vis_' + name);
    document.getElementById(name).value = '';
    document.getElementById('sf_id_' + name).value = '';
    document.getElementById(name + '_c').value = '';
    document.getElementById('sf_id_' + name + '_c').value = '';
    visctl.innerHTML = '';
    visctl.innerHTML = '<div name="_empty_">&lt;' + searchFormInfo[name].empty_value +
        '&gt;</div>';
}

function searchFormChange(ctl)
{
    if (ctl.type == 'checkbox') {
        var cbs = document.getElementsByName(ctl.name);
        var sel = false;
        for (var i = 0; i < cbs.length; i++) {
            if ((cbs[i].value == 'selected' || cbs[i].value == 'all_except_selected')
            && cbs[i].checked) {
                sel = true;
                break;
            }
        }
    } else {
        sel = ctl.value == 'selected' || ctl.value == 'all_except_selected';
    }
    var list = document.getElementById('sf_list_'+ctl.name);
    if (list) list.style.display = sel ? '' : 'none';
    var list1 = document.getElementById('sf_add_'+ctl.name);
    if (list1) list1.style.display = sel ? '' : 'none';
}

function showSearchForm(name)
{
    if (typeof popup_exec_url == 'function') {
        popup_exec_url(searchFormInfo[name].url, null, 500, 500, true,
        	searchFormInfo[name]['onClose'] ? searchFormInfo[name]['onClose'] : null,
            searchFormInfo[name].title, searchFormInfo[name].mode == 'multi' ? 'Apply' : 'Close');
    } else {
        var size = "width=500,height=500,scrollbars=yes,resizable=yes";
        window.open(searchFormInfo[name].url, "search_form", size);
    }
}
/**
 * @param name - form name
 * @param mode - p|c
 * @param ids  - array of ids to add
 * @param items - items array to get title and code
 * @param status - mode, true to select, false to deselect
 * @param page_id
 */
function searchFormMassSelect(name, mode, ids, items, status, page_id)
{
    if (ids.length == 0) return;

    var prod_id;
    if (mode == 'p') {
        prod_id = searchFormInfo[name].key_field;
    } else {
        prod_id = searchFormInfo[name].cat_key_field;
    }

    if (searchFormInfo[name].mode == 'single') {
        var item = items[ids[0]];
        searchFormSelect(name, mode, item[prod_id], item['title'], item['code'], status, page_id);
        return;
    }

    var ctl = null, idctl = null, snp = null;
    if (mode == 'p') {
        ctl = document.getElementById(name);
        idctl = document.getElementById('sf_id_' + name);
    } else {
        ctl = document.getElementById(name + '_' + mode);
        idctl = document.getElementById('sf_id_' + name + '_' + mode);
        snp = document.getElementById(name + '_nested_panel');
    }
    var visctl = document.getElementById('sf_vis_' + name);
    if (!ctl || !idctl || !visctl) return;

    var img = '';
    if (mode == 'p') {
        img = '<img src="/core/images/tree/leaf.gif" width="20" height="20" align="absmiddle" border="0"/>';
    } else if (mode == 'c') {
        img = '<img src="/core/images/tree/folder.gif" width="20" height="20" align="absmiddle" border="0"/>';
    }

    var ev = searchFormInfo[name].empty_value;

    var current_list = ctl.value.split(',');
    var actual_list = new Array();
    // keep only checked items
    if (status) { // add
        actual_list = current_list.concat(ids);
        array_unique(actual_list);
    } else { // substract
        while(current_list.length > 0) {
            var value = current_list.pop();
            var found = false;
            for (var i=0; i < ids.length; i++) {
                if (ids[i] == value) {found = true;break;}
            }
            if (found) continue;
            actual_list.push(value);
        }
    }

    visctl.innerHTML = '';
    inner_html = '';
    for(var i = 0; i < actual_list.length; i++) {
        var item = items[actual_list[i]]
        if (!item) continue;
        title = img + (searchFormInfo[name]['onDisplay'] ?
    	window[searchFormInfo[name]['onDisplay']](actual_list[i], item['title'], item['code']) : item['title']);
        inner_html += '<div name="'+mode+'_'+actual_list[i]+'">'+title+'</div>';
    }
    visctl.innerHTML = inner_html;
    if (actual_list.length == 0)
        visctl.innerHTML = '<div name="_empty_">&lt;'+ev+'&gt;</div>';

    var s = '';
    for (var i = 0; i < actual_list.length; i++)
        if (actual_list[i]) s+= ','+actual_list[i];
    idctl.value = ctl.value = s.substr(1);

    if (snp) snp.style.display = ctl.value ? '' : 'none';
}

function searchFormSelect(name, mode, id, title, code, status, page_id)
{
    var ctl = null, idctl = null, snp = null;
    if (mode == 'p') {
        ctl = document.getElementById(name);
        idctl = document.getElementById('sf_id_' + name);
    } else {
        ctl = document.getElementById(name + '_' + mode);
        idctl = document.getElementById('sf_id_' + name + '_' + mode);
        snp = document.getElementById(name + '_nested_panel');
    }
    var visctl = document.getElementById('sf_vis_' + name);
    if (!ctl || !idctl || !visctl) return;

    var img = '';
    if (mode == 'p') {
        img = '<img src="/core/images/tree/leaf.gif" width="20" height="20" align="absmiddle" border="0"/>';
    } else if (mode == 'c') {
        img = '<img src="/core/images/tree/folder.gif" width="20" height="20" align="absmiddle" border="0"/>';
    }
    title = img + (searchFormInfo[name]['onDisplay'] ?
    	eval(searchFormInfo[name]['onDisplay']+'(id, title, code)') : title);

    if (searchFormInfo[name].mode == 'single') {
        if (mode == 'p') {
            ctl.value = eval(searchFormInfo[name].key_field);
        } else {
            ctl.value = eval(searchFormInfo[name].cat_key_field);
            if (snp) snp.style.display = ctl.value ? '' : 'none';
        }
        if (id) {
            visctl.innerHTML = title;
        } else {
            visctl.innerHTML = '&lt;' + searchFormInfo[name].empty_value + '&gt;';
        }
        idctl.value = id;
    }

    if (searchFormInfo[name].mode == 'multi') {
        var ctl_id = name;
        var ev = searchFormInfo[name].empty_value;
        var prod_id;
        if (mode == 'p') {
            prod_id = eval(searchFormInfo[name].key_field);
        } else {
            prod_id = eval(searchFormInfo[name].cat_key_field);
        }

        var list = ctl.value.split(',');
        var idlist = idctl.value.split(',');
        var idx = -1;
        for (var i=0; i<idlist.length; i++)
            if (idlist[i] == id)
            {
                idx = i;
                break;
            }
        var ectl = null, pctl = null;
        for (var i=0; i<visctl.childNodes.length; i++) {
            if (visctl.childNodes[i].getAttribute('name') == '_empty_') {
                ectl = visctl.childNodes[i];
            }
            else if (visctl.childNodes[i].getAttribute('name') == mode+'_'+id) {
                pctl = visctl.childNodes[i];
            }
        }
        if (status && idx == -1)
        {
            idlist[list.length] = id;
            list[list.length] = prod_id;
            if (ectl) visctl.removeChild(ectl);
            if (visctl)
                visctl.innerHTML = visctl.innerHTML+
                    '<div name="'+mode+'_'+id+'">'+title+'</div>';
        }
        else if (!status && idx != -1)
        {
            idlist[idx] = '';
            list[idx] = '';
            if (pctl) visctl.removeChild(pctl);
            if (visctl && visctl.innerHTML == '')
                visctl.innerHTML = '<div name="_empty_">&lt;'+ev+'&gt;</div>';
        }
        var s = '';
        for (var i=0; i<list.length; i++)
            if (list[i])
                s += ','+list[i];
        ctl.value = s.substr(1);
        s = '';
        for (var i=0; i<idlist.length; i++)
            if (idlist[i])
                s += ','+idlist[i];
        idctl.value = s.substr(1);
        if (snp) snp.style.display = ctl.value ? '' : 'none';
    }
}

function searchFormAfterLoad(name, w)
{
    if (!searchFormInfo[name]) return;
    if (searchFormInfo[name].mode == 'multi') {
    	var sxa = new Array('p', 'c');
        var np = 0, nc = 0;
        for (var j=0; j<sxa.length; j++) {
            var sx = sxa[j];
            var idctl, idctl_dis;
            if (sx == 'p') {
                idctl = document.getElementById('sf_id_'+name);
                idctl_dis = document.getElementById('sf_dis_ids_'+name);
            } else {
                idctl = document.getElementById('sf_id_'+name+'_'+sx);
                idctl_dis = document.getElementById('sf_dis_ids_'+name+'_'+sx);
            }
            if (!idctl) continue;

            var list = idctl.value.split(',');
            var c = 0;
            for (var i=0; i<list.length; i++) {
                if (list[i]) {
                    var cb = w.document.getElementById(sx+'_check_'+list[i]);
                    if (cb) cb.checked = true;
                    c++;
                }
            }
            if (sx == 'p') np = c;
            if (sx == 'c') nc = c;

            if (idctl_dis) {
            	var list = idctl_dis.innerHTML.split(',');
	            for (var i=0; i<list.length; i++) {
	                if (list[i]) {
	                    var cb = w.document.getElementById(sx+'_check_'+list[i]);
	                    if (cb) cb.disabled = true;
	                }
	            }
            }
        }
        w.sf_set_numbers(np, nc);
    } else {
	    var idctl_dis = document.getElementById('sf_dis_ids_'+name+'_c');
        if (idctl_dis) {
	    	var list = idctl_dis.innerHTML.split(',');
	        for (var i=0; i<list.length; i++) {
	            if (list[i]) {
	                var tr = w.document.getElementById('cr_'+list[i]);
	                if (tr) {
		                var a = tr.getElementsByTagName('a');
		                if (a[0]) {
		                	var span = document.createElement('span');
		                	span.innerHTML = a[0].innerHTML;
		                	a[0].parentNode.appendChild(span);
		                	a[0].parentNode.removeChild(a[0]);
		                }
	                }
	            }
	        }
        }
    }
}

dialogWindow = null;
function showDialog(id, fade, position)
{
    // position - to force position to fix editor dropdowns position
    hideDialog();
    var ctl = document.getElementById(id);
    if (ctl) {
        ctl.style.visibility = 'hidden';
        ctl.style.display = '';
        if (is_msie()) {
            ctl.style.position = 'absolute';
        } else {
            ctl.style.position = 'fixed';
        }
        if (position) ctl.style.position = position;
        var isAbs = ctl.style.position == 'absolute';
        ctl.style.left = (getClientWidth() - ctl.offsetWidth) / 2 +
            (isAbs ? getScrollLeft() : 0) + 'px';
        ctl.style.top = (getClientHeight() - ctl.offsetHeight) / 2 +
            (isAbs ? getScrollTop() : 0) + 'px';
        ctl.style.visibility = 'visible';
        dialogWindow = ctl;
        hideElements(ctl, ctl);
        ctl.onmousedown = function (event) { (event || window.event).cancelBubble = true; };
        if (!fade) dialogAttachEvents();
        enableDialogDragging(dialogWindow);
        disableScroll(dialogWindow);
        if (fade) popup_fade_background(true, hideDialog);
    }
}

function hideDialog()
{
	popup_fade_background(false);
    if (typeof hide_popup == 'function') hide_popup();
    var ctl = dialogWindow;
    if (ctl) {
        ctl.style.display = 'none';
        ctl.style.visibility = 'hidden';
        dialogWindow = null;
        showElements();
        disableDialogDragging(ctl);
    }
    enableScroll();
}

function moveDialog()
{
    var ctl = dialogWindow;
    if (ctl) {
        ctl.style.top = (getClientHeight() - ctl.offsetHeight) / 2 +
            (is_msie() ? getScrollTop() : 0) + 'px';
    }
}

dialogEventsAttached = false;
function dialogAttachEvents()
{
    if (!dialogEventsAttached) {
        dialogEventsAttached = true;
        addHandler(document.body, 'mousedown', hideDialog);
    }
}

function enableDialogDragging(dialogWindow)
{
	dialogWindow.draggingStarted = false;
	var divs = dialogWindow.getElementsByTagName('DIV');
	var dialogHeader = null, closeButton = null;
	for (var i = 0; i < divs.length; i++) {
		if (divs[i].className == 'PopupHeader') {
			dialogHeader = divs[i];
		}
		if (divs[i].id == 'PopupCloseDiv' || divs[i].className == "PopupCloseButton") {
			closeButton = divs[i];
		}
		if (is_msie())
			divs[i].setAttribute('unselectable', 'on');
	}
	if (!dialogHeader) return;

	var upperLayer = document.createElement('DIV');
	upperLayer.className = 'dragLayer';
	dialogWindow.appendChild(upperLayer);
	dialogWindow.upperLayer = upperLayer;

	dialogHeader.onmousedown = function(event) {
		event = event || window.event;
		dialogWindow.draggingStarted = true;
		dialogWindow.deltaX = event.clientX - parseInt(dialogWindow.style.left);
		dialogWindow.deltaY = event.clientY - parseInt(dialogWindow.style.top);
		upperLayer.style.zIndex = '100';
	};
	upperLayer.onmousemove = dialogHeader.onmousemove = dialogWindow.onmousemove = function(event) {
        if (is_msie() && closeButton) {
            closeButton.className = '';
            closeButton.className = 'PopupCloseButton';
        }
        if (!dialogWindow.draggingStarted) return;
		event = event || window.event;
		dialogWindow.style.top = event.clientY - dialogWindow.deltaY;
		dialogWindow.style.left = event.clientX - dialogWindow.deltaX;
	};
	upperLayer.onmouseup = dialogHeader.onmouseup = dialogWindow.onmouseup = function() {
		if (dialogWindow)
			dialogWindow.draggingStarted = false;
		dialogWindow.upperLayer.style.zIndex = '-1';
	};

	addHandler(document.body, 'mousemove', dialogWindow.onmousemove);
}

function disableDialogDragging(dialogWindow)
{
	dialogWindow.removeChild(dialogWindow.upperLayer);
	dialogWindow.upperLayer = null;
	removeHandler(document.body, 'mousemove', dialogWindow.onmousemove);
}

// disable scroll event bubbling
function disableScroll(dialogWindow)
{
    document.body.style.overflow = 'hidden';
}
function enableScroll()
{
	document.body.style.overflow = 'auto';
}
var blackShadowsApplied = false;
function setBlackShadows() {
    if (blackShadowsApplied) return;
    blackShadowsApplied = true;
    var link = document.createElement('link');
    link.setAttribute('rel', 'stylesheet');
    link.setAttribute('href', '/core/wf_getcss.php?css=core/css/dialog_dark.css');
    document.getElementsByTagName('head')[0].appendChild(link);
};

function turnPage(pageUrl, frame_id)
{
    var result = true;
    if (typeof(doExtraCheck) == 'function') {
        result = doExtraCheck(frame_id);
    }
    if (result)
        setLocation(pageUrl);
}

function _putHelpLabel(label, header, descr) {
    if (el = document.getElementById('help_description_' + label)) {
        try {
            el.innerHTML = '<div style="font-weight: bold; font-size: 10pt; color: #808080; margin-bottom: 10pt">' + header + '</div><div>' + descr + '</div>';
        } catch (e) {}
    }
}

function showRatingStars(id, rating, showEmpty, isAverage, item_id, item_label, title, reviews)
{
	var el = typeof(id) == 'string' ? document.getElementById(id) : id;
	if (!el) return;
	var html = '';
    var intRating, isFirst = true;
    if (rating >= 1 && rating <= 5) {
        intRating = parseInt(rating);
        for (var i = 0; i < intRating; i++) {
            html += '<img src="/core/images/stars/yellow.png" ' +
            	(!isFirst ? 'style="margin-left: 3px;"' : '') + ' />';
            if (isFirst) isFirst = false;
        }
        if (intRating != rating) {
          html += '<img src="/core/images/stars/half.png" ' +
          	(!isFirst ? 'style="margin-left: 3px;"' : '') + ' />';
          if (isFirst) isFirst = false;
          intRating++;
        }
        for (var i = 0; i < (5-intRating); i++) {
          html += '<img src="/core/images/stars/gray.png" ' +
          	(!isFirst ? 'style="margin-left: 3px;"' : '') + ' />';
          if (isFirst) isFirst = false;
        }
    } else if (showEmpty) {
    	for(var i = 0; i < 5; i++) {
    		html += '<img src="/core/images/stars/gray.png" ' +
    			(!isFirst ? 'style="margin-left: 3px;"' : '') + ' />';
    		if (isFirst) isFirst = false;
    	}
    }

    if (item_id) {
	    if (reviews) {
	    	el.style.cursor = "pointer";
	        el.style.whiteSpace = "nowrap";
	        el.title = "Read "+reviews+" Review" + (reviews > 1 ? "s" : "");
	        el.onclick = new Function("showReviews('"+item_id+"', '"+item_label+"', '"+title.replace('\'','\\\'')+"', 1);");
	    } else if (showEmpty) {
	    	el.title = "0 Reviews";
	    }
    }
    if (isAverage) {
    	// add zeros after dot:
    	var dotInd = rating.toString().indexOf('.');
    	if (dotInd == -1) {
    		rating += ".00";
    	} else {
    		var len = rating.length - dotInd - 1;
    		if (len == 1) rating += "0";
    	}
    	el.title += (el.title ? ", " : "") + "Average Rating: " + rating;
    }
    el.innerHTML = html;
}

// Shows frame with review list.
// Use item_id=-1 for all reviews, item_id=-2 for unapproved reviews.
// Set title if you want to change title of the frame.
// Page is a page number in the review list.
function showReviews(item_id, item_label, title, page)
{
	var url = document.location.href;
	url = url.replace(/f[a-z]+items?/,"freviews")+'&popup=1';
	if (page == 0) page = 1;
	url = url+'&item='+item_id+'&reviewsPage='+page;
	popup_exec_url(url, null, 700, 500, true, typeof(refreshList) == 'function' ? 'refreshList' : null,
		item_label + " Reviews: " + title, "Close");
}

function resetEditorContent(name)
{
	if (typeof(editorExtraParams) == 'undefined' || !editorExtraParams[name]) return;
	var defVal = editorExtraParams[name]['defValue'];
	if (typeof(defVal) == 'undefined') return;

	if (confirm("Are you sure you want to discard your customized field content?")) {
		editor_set_text(name, defVal);
	}
}
