var preload_images = new Array();
var visible_menu = null;
var scroller = null;

/* Find all navigation images for a mouse over effect */
function makeMouseOver() {
    $$('img.mo').each( function( the_img ) {

        var submenu = $(the_img.getProperty('id') + '_menu');
        if (submenu) {
            submenu.addEvent('mouseleave', hideMenuLayers);
        }
        var src = the_img.getProperty('src');
        var highlighted = (src.lastIndexOf('_mo.gif') > -1);
        if  (!highlighted ){
            var extension = src.substring(src.lastIndexOf('.'),src.length);
            var mo_src = src.replace(extension,'_mo' + extension);

            // preload the image
            var pr_img = document.createElement('img');

            $(pr_img).setProperty('src',  mo_src);
            preload_images.push(pr_img);
        }
        else {
            var mo_src = src;
        }

        the_img.addEvent('mouseenter', function() { 
            the_img.setProperty('src', mo_src);
            hideMenuLayers();
            // show the sub menu ?
            if (submenu) {
                // adjust to left or right ?
                var coords = the_img.getCoordinates();
                if (document.body.dir == 'rtl') {
                    submenu.setStyle('left', coords['right'] - submenu.getSize()['size']['x'] +'px');
                }
                else {
                    submenu.setStyle('left', coords['left']+'px');
                }
                submenu.setStyle('visibility', 'visible');
                visible_menu = submenu;
            }
        });

        if (!highlighted) {
            the_img.addEvent('mouseleave', function() {
                the_img.setProperty('src',src); 
            });
        }
    });
}

function hideMenuLayers() {
    $$('div.sub-menu').setStyle('visibility', 'hidden');
}

function setupScroller() {
    var scroll_up = $$("img.scrollup");
    var scroll_down = $$("img.scrolldown");

    if (scroll_up.length && scroll_down.length) {
        // found them, since an array, let's get the 1st and only one
        scroll_down = scroll_down[0];
        scroll_up = scroll_up[0];

        // setup the scroller
        scroller = new Fx.Scroll('index_news_outer' , {
            wait: false, duration:2500, transtion: Fx.Transitions.Quad.easeOut
        });

        scroll_down.addEvents({
            'mouseenter': function(event) {
                event = new Event(event).stop();
                scroller.toBottom();
            },
            'mouseleave': function(event) {
                event = new Event(event).stop();
                scroller.stop();
            }
        });

        scroll_up.addEvents({
            'mouseenter': function(event) {
                event = new Event(event).stop();
                scroller.toTop();
            },
            'mouseleave': function(event) {
                event = new Event(event).stop();
                scroller.stop();
            }
        });
    }
}

function isEmail(str) {
	// are regular expressions supported?
	var supported = 0;
	if (window.RegExp) {
		var tempStr = "a";
		var tempReg = new RegExp(tempStr);
		if (tempReg.test(tempStr)) supported = 1;
	}
	if (!supported) 
		return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
	var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
	var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
	return (!r1.test(str) && r2.test(str));
}

function setupAdvSearchForm() {
    // make sure we have the form displayed

    var checkboxes_div = $('adv_search');

    if (!checkboxes_div) return;

    // get all checkboxes
    var boxes = checkboxes_div.getElements('input[type=checkbox]');

    boxes.each(function(item, index) {
        item.addEvent('click', function(ev) {
            var ev=new Event(ev);
            var is_all = (ev.target.getProperty('id') == 'sections_all');
            
            if (is_all) {
                boxes.each( function(item, ev_index) {
                    if (ev_index > 0 )
                        item.checked = false;
                });
            }
            else {
                boxes[0].checked = false;
            }
        });
    });
}

function setupEditor() {
    $$('textarea.htmlarea').each(function(item) {
        var fckedit = new FCKeditor(item.getProperty('id'));
        fckedit.BasePath = '/media/js/fckeditor/';
        if (item.hasClass('ltr')) {
            fckedit.Config["CustomConfigurationsPath"] = "/media/js/fck_law_ltr.js?dt=" + new Date().valueOf();
        }
        else {
            fckedit.Config["CustomConfigurationsPath"] = "/media/js/fck_law.js?dt=" + new Date().valueOf();
        }
        fckedit.ToolbarSet = 'LawToolBar';
        fckedit.Height = '350';
        fckedit.Width = '100%';
        fckedit.ReplaceTextarea();
    });
}

/**
 * sets the category image when editing it
 */
function setCategoryImage(image_name) {
    // update the input field
    $('id_image').setProperty('value',image_name);

    // update the preview image
    $('image_preview').setProperty('src', '/media' + image_name);
}

function toggleList(div_name) {
    var the_div = $(div_name ? div_name : 'elements_list');

    the_div.setStyle('display', (the_div.getStyle('display')=='none' ? 'block' : 'none'));
}

function activateTab(folder) {
    $$('a.tab_active').setProperty('class', 'tab');
    $('tab_' + folder).setProperty('class', 'tab_active');
    $$('div.folder_items').setStyle('display', 'none');
    $('folder_'+folder).setStyle('display', 'block');
}

/**
 * Set the news title to the selected folder item url
 */
function selectFolderItem(url) {
    the_title = prompt('כותרת');
    
    if (the_title) {
        the_text = '<a href="/' + url + '">' + the_title +'</a>';
        $('id_title').setProperty('value', the_text);
        toggleList();
    }
}

/**
 * Change the active stylesheet
    */
function setActiveStyleSheet(title) {
    var i, a, main;
    for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
            if(a.getAttribute("rel").indexOf("style") != -1
                            && a.getAttribute("title")) {
                    a.disabled = true;
                    if(a.getAttribute("title") == title) a.disabled = false;
            }
    }
    window.scroll(0,0);
}

/**
 * Change form elements direction according to selected lang
 */
function setElementsDirection(lang) {
    var the_dir = (lang == 'h' ? 'rtl' : 'ltr');
    var the_align = (lang == 'h' ? 'right' : 'left');
    
    //get all iframes (which should be the html editors)
    $$('iframe').each(function(item) {
        if (item.getProperty('id')) {
            // now get the inner editin iframe
            var inner_f = item.contentDocument.getElementsByTagName('iframe')[0];
            inner_f.contentWindow.document.dir = the_dir;
            inner_f.contentWindow.document.body.style.textAlign = the_align;
            inner_f.contentWindow.document.body.style.direction = the_dir;
        }
    } );
    
    // align other fields
    $$(['id_title','id_subtitle', 'id_name']).each(function(item){
        item.setStyles({direction:the_dir, 'text-align':the_align});
    });
}