/**
 * @version $Id: scriptaculous.js,v 1.16 2006/07/28 09:26:38 mikedeboer Exp $
 */

var Zoom = {
    Version: '1.5_pre4',
    folded: new Array(),
    connector: null,
    method: 'post',
    state: 'new',
    treenode: null,
    treeObj: null,
    req_uri: '',
    site_uri: '',
    uid: '0',
    activeCat: '0',
    activeSubcat: '0',
    lightboxActive: false,
    votingActive: false,
    votingMedium: null,
    
    require :
    function(libraryName) {
        // inserting via DOM fails in Safari 2.0, so brute force approach
        document.write('<script type="text/javascript" src="'+libraryName+'"></script>');
    },
    
    load :
    function() {
        if((typeof Prototype=='undefined') ||
          parseFloat(Prototype.Version.split(".")[0] + "." +
                     Prototype.Version.split(".")[1]) < 1.4)
          throw("script.aculo.us requires the Prototype JavaScript framework >= 1.4.0");
        var scriptTags = document.getElementsByTagName("script");
        for(var i=0;i<scriptTags.length;i++) {
            if(scriptTags[i].src && scriptTags[i].src.match(/scriptaculous\.js(\?.*)?$/)) {
                var path = scriptTags[i].src.replace(/scriptaculous\.js(\?.*)?$/,'');
                this.require(path + 'util.js');
                this.require(path + 'button.js');
                this.require(path + 'effects.js');
                this.require(path + 'dtree.js');
                this.require(path + 'dragdrop.js');
                this.require(path + 'mm.js');
                this.require(path + 'tjpzoom.js');
                break;
            }
        }
    },
    
    getGalleryTree :
    function(elmnt) {
        this.treenode = elmnt;
        var params = 'uid=' + this.uid + '&id=' + id + '&task=catsmgr_getlist';
        this.connector = new Ajax.Request(this.req_uri, {
            method: this.method, parameters: params,
            onSuccess: this.buildTree});
    },
    
    buildTree : 
    function(callback) {
        Zoom.treeObj = new dTree('Zoom.treeObj');
        Zoom.treeObj.config.iconPrefix = siteUrl + '/' + Zoom.treeObj.config.iconPrefix
        Zoom.treeObj.add('root', '-1', 'Galleries');
        Zoom.treeObj.add('new', 'root', LANG_NEW_TITLE, 'javascript:resetFormValues();');
        var nodes = callback.responseXML.getElementsByTagName('zoom');
        for (var i = 0; i < nodes[0].childNodes.length; i++)
            Zoom.buildTreeNodes(nodes[0].childNodes[i], 'root', Zoom.treeObj);
        var tree = $(Zoom.treenode);
        tree.innerHTML = Zoom.treeObj.toString();
        var nodes = document.getElementsByClassName('dTreeNode');
        var mayDrag, mayDrop;
        for (var i = 0; i < nodes.length; i++) {
        	mayDrag = mayDrop = true;
        	mayDrag = (nodes[i].firstChild.id.indexOf('treeObj0') < 0);
        	if (nodes[i].firstChild.nextSibling.id) {
        		if (nodes[i].firstChild.nextSibling.id.indexOf('treeObj1') > 0)
        			mayDrag = mayDrop = false;
        	}
        	if (mayDrag)
        		new Draggable(nodes[i], {revert: true, constraint: 'vertical'});
        	if (mayDrop) {
        		Droppables.add(nodes[i], {hoverclass: 'dTreeNodeOnDrop',
        			onDrop: function(draggable, droppable, event) {
        				var drag_gallery = Zoom.getGalleryFromElement(draggable);
        				var drop_gallery = Zoom.getGalleryFromElement(droppable);
        				Zoom.resortGallery(drag_gallery, drop_gallery);
        			}});
        	}
        }
    },
    
    resortGallery :
    function(gallery, target) {
    	showMe();
        var params = 'uid=' + this.uid + '&id=' + id + '&catid=' + gallery[0] + '&target=' + target[0] + '&task=catsmgr_resort';
        this.connector = new Ajax.Request(this.req_uri, {
            method: this.method, parameters: params,
            onSuccess: function(callback) {
            	Zoom.getGalleryTree('cats_tree');
            	Zoom.setFormFields(callback);
            }});
    },
    
    getGalleryFromElement :
    function(element) {
    	var a = element.getElementsByTagName('a');
    	if (a.length > 0) {
			var a_pointer = a[a.length - 1].href.substr(31, (a[a.length - 1].href.length - 33)).replace(/\'/gi, '');
			return a_pointer.split(',');
    	}
    	return [0, 0, 0, 0];
    },
    
    buildTreeNodes :
    function(node, parent, tree) {
        var id = node.getAttribute('id');
        var pos = node.getAttribute('pos');
        var published = node.getAttribute('published');
        var shared = node.getAttribute('shared');
        var uid = node.getAttribute('uid');
        tree.add(id, parent, node.getAttribute('name'), 'javascript:Zoom.ongalleryclick(\'' + id + '\',\'' + 
            pos + '\',\'' + published + '\',\'' + 
            shared + '\',\'' + uid + '\');',
            '', '', tree.config.iconPrefix + tree.icon.folder, tree.config.iconPrefix + tree.icon.folderOpen, '',
            'Zoom.ongalleryhover(\'' + id + '\',\'' + pos + '\',\'' + published + '\',\'' + shared + '\',\'' + uid + '\');', 'return nd();');
        for (var i = 0; i < node.childNodes.length; i++)
            this.buildTreeNodes(node.childNodes[i], id, tree);
    },
    
    ongalleryclick :
    function(catid, pos, published, shared, uid) {
        showMe();
        var params = 'uid=' + this.uid + '&id=' + id + '&catid=' + catid + '&task=catsmgr_editform';
        this.connector = new Ajax.Request(this.req_uri, {
            method: this.method, parameters: params,
            onSuccess: Zoom.setFormFields });
    },
    
    getNewDir :
    function() {
    	var params = 'uid=' + this.uid + '&id=' + id + '&task=catsmgr_newdir';
        this.connector = new Ajax.Request(this.req_uri, {
            method: this.method, parameters: params,
            onSuccess: function(callback) {
            	var nodes = callback.responseXML.getElementsByTagName('newdir');
            	if (nodes.length >= 1) {
            		document.catsmgr.elements['catdir'].value = nodes[0].firstChild.nodeValue;
            	}
            }});
    },
    
    setFormFields :
    function(callback) {
    	//alert(callback.responseText);
        var msg;
        hideMe();
        Zoom.getToolbar('catsmgr_editform');
        Zoom.getParentOptions();
        var result = callback.responseXML.getElementsByTagName('result');
        if (result[0].firstChild.nodeValue == "KO") {
            msg = callback.responseXML.getElementsByTagName('reason');
            if (msg[0] && msg[0].firstChild.nodeValue != "none") alert(msg[0].firstChild.nodeValue);
        } else if (result[0].firstChild.nodeValue == "OK") {
            msg = callback.responseXML.getElementsByTagName('msg');
            if (msg[0] && msg[0].firstChild.nodeValue != "none") {
                alert(msg[0].firstChild.nodeValue);
                Zoom.getGalleryTree('cats_tree');
            }
            
            var galleries = callback.responseXML.getElementsByTagName('gallery');
            var gallery = galleries[0];
            if (gallery) {
                this.state = 'edit';
                var members = gallery.getElementsByTagName('members');
                members = members[0].firstChild.nodeValue;
                Zoom.activeCat = gallery.getAttribute('id');
                Zoom.activeSubcat = gallery.getAttribute('subcat_id');
                setFormValues(Zoom.activeCat, gallery.getAttribute('name'), gallery.getAttribute('dir'), 
                    gallery.getAttribute('password'), gallery.getAttribute('keywords'), gallery.lastChild.nodeValue,
                    Zoom.activeSubcat, gallery.getAttribute('pos'), members,
                    gallery.getAttribute('hide_msg'), gallery.getAttribute('published'), gallery.getAttribute('shared'));
            } else {
                this.state = 'new';
                resetFormValues();
            }
        }
    },
    
    ongalleryhover :
    function(id, pos, published, shared, uid) {
        var html = '<img src="' + siteUrl;
        if (published == "1") {
            html += '/components/com_zoom/www/images/publish_g.png" alt="" border="0" />&nbsp;' +
                LANG_PUBLISHED + ': <b>' + LANG_YES + '</b>';
        } else {
            html += '/components/com_zoom/www/images/publish_x.png" alt="" border="0" />&nbsp;' +
                LANG_PUBLISHED + ': <b>' + LANG_NO + '</b>';
        }
        html += '<br /><img src="' + siteUrl;
        if (shared == "1") {
            html += '/components/com_zoom/www/images/share_u.png" alt="" border="0" />&nbsp;' +
                LANG_SHARED + ': <b>' + LANG_YES + '</b>';
        } else {
            html += '/components/com_zoom/www/images/share_l.png" alt="" border="0" />&nbsp;' +
                LANG_SHARED + ': <b>' + LANG_NO + '</b>';
        }
        overlib(html);
    },
    
    getToolbar :
    function(action) {
        var buttons;
        if (typeof action == "undefined") action = "catsmgr";
        var params = 'uid=' + this.uid + '&id=' + id + '&action=' + action + '&task=get_toolbar';
        this.connector = new Ajax.Request(this.req_uri, {
            method: this.method, parameters: params,
            onSuccess: this.buildToolbar});
    },
    
    buildToolbar :
    function(callback) {
        buttons = callback.responseXML.getElementsByTagName('button');
        var toolbar = $('toolbar'), name;
        toolbar.innerHTML = "";
        for (var i = 0; i < buttons.length; i++) {
            name = buttons[i].getAttribute('type');
            new Zoom.Button(name, '', toolbar, {
                width: 32,
                height: 32,
                group: buttons[i].getAttribute('caption'),
                classEnter: 'zmg_tb_btn_' + name + '_hover',
                classLeave: 'zmg_tb_btn_' + name,
                onEnter: function(button) {
                    overlib(button.options.group);
                },
                onLeave : function(button) {
                    nd();
                },
                onLeftClick: function(button) {
                    Zoom.dispatch(button.getId());
                }
            });
        }
    },
    
    getParentOptions :
    function() {
        var params = 'uid=' + this.uid + '&id=' + id + '&task=get_galleries';
        this.connector = new Ajax.Request(this.req_uri, {
            method: this.method, parameters: params,
            onSuccess: this.setParentOptions});
    },
    
    setParentOptions :
    function(callback) {
        var oParent = document.catsmgr.elements['parent'];
        var sel = "0";
        
        var options = callback.responseXML.getElementsByTagName('gallery');
        var option;
        
        oParent.innerHTML = "";
        for (var j = 0; j < options.length; j++) {
            var option = document.createElement('option');
            option.value = options[j].getAttribute('id');
            option.innerHTML = options[j].firstChild.nodeValue;
            if (option.value == Zoom.activeSubcat)
                option.selected = true;
            oParent.appendChild(option);
        }
    },
    
    dispatch :
    function(action) {
        showMe();
        var descr = getEditorContent();
        if (descr == null)
            descr = $F('catdescr');
        var form = document.catsmgr;
        var oParent = form.elements['parent'];
        var sParent = "0";
        for (var i = 0; i < oParent.childNodes.length; i++)
            if (oParent.childNodes[i].selected) sParent = oParent.childNodes[i].value;
        var params = 'uid=' + this.uid + '&id=' + id + '&catid=' + $F('catid') + '&task=catsmgr_' + action + '&parent=' + sParent +
            '&name=' + encodeURIComponent($F('catname')) + '&dir=' + encodeURIComponent($F('catdir')) +
            '&password=' + encodeURIComponent($F('catpassword')) + '&keywords=' + encodeURIComponent($F('catkeywords')) +
            '&descr=' + encodeURIComponent(descr) + '&hide_msg=' + ((form.elements['hidemsg'].checked) ? "1" : "0") +
            '&published=' + ((form.elements['published'].checked) ? "1" : "0") + '&shared=' + ((form.elements['shared'].checked) ? "1" : "0");
        params += '&' + Form.Element.serialize($('members_sel'));
        this.connector = new Ajax.Request(this.req_uri, {
            method: this.method, parameters: params,
            onSuccess: Zoom.setFormFields });
    },
    
    PSR_star_over :
    function(obj, star_number) {
        var psr = obj.parentNode;
        var as = psr.getElementsByTagName('label');
        for (i=0;i<star_number;++i) {
            as[i].lastClass = as[i].className;
            as[i].className = 'PSR_full_star';
        }
        for (;i<as.length;++i) {
            as[i].lastClass = as[i].className;
        }
    },
    
    PSR_star_out :
    function(obj) {
        var as=obj.getElementsByTagName('label');
        for (i=0;i<as.length;++i) {
            if (as[i].lastClass) {
                as[i].className = as[i].lastClass;
            }
        }
    },
    
    PSR_save_vote :
    function(imgid, vote) {
        if (!this.votingActive) {
            var params = 'uid=' + this.uid + '&id=' + id + '&task=view_vote&imgid=' + imgid + '&vote=' + vote;
            this.votingMedium = imgid;
            this.votingActive = true;
            this.connector = new Ajax.Request(this.req_uri, {
                method: 'post', parameters: params,
                onSuccess: this.PSR_update_vote });
        }
    },
    
    PSR_update_vote :
    function(callback) {
        Zoom.votingActive = false;
        var msgContainer = $('PSR_form_' + Zoom.votingMedium).parentNode;
        var result = callback.responseXML.getElementsByTagName('result');
        if (result[0].firstChild.nodeValue == 'KO') {
            msg = callback.responseXML.getElementsByTagName('reason');
            if (msg[0] && msg[0].firstChild.nodeValue != 'none') msgContainer.innerHTML = msg[0].firstChild.nodeValue;
        } else if (result[0].firstChild.nodeValue == 'OK') {
            msg = callback.responseXML.getElementsByTagName('msg');
            if (msg[0] && msg[0].firstChild.nodeValue != 'none') msgContainer.innerHTML = msg[0].firstChild.nodeValue;
        }
    },
    
    lightboxAdd :
    function(imgid, type, image) {
        if (!this.lightboxActive) {
            var params = 'uid=' + this.uid + '&id=' + id + '&task=view_lightbox&imgid=' + imgid + '&type=' + type;
            this.lightboxObj = image;
            image.src = Zoom.site_uri + '/components/com_zoom/www/images/indicator.gif';
            this.connector = new Ajax.Request(this.req_uri, {
                method: 'post', parameters: params,
                onSuccess: this.lightboxResult });
        }
        
    },
    
    lightboxResult :
    function(callback) {
        Zoom.lightboxActive = false;
        var result = callback.responseXML.getElementsByTagName('result');
        if (result[0].firstChild.nodeValue == 'KO') {
            msg = callback.responseXML.getElementsByTagName('reason');
            Zoom.lightboxObj.src = Zoom.site_uri + '/components/com_zoom/www/images/delete.png';
            if (msg[0] && msg[0].firstChild.nodeValue != 'none') Zoom.lightboxObj.parentNode.onmouseover = function(){return overlib(msg[0].firstChild.nodeValue, CAPTION, lb_title);};
        } else if (result[0].firstChild.nodeValue == 'OK') {
            msg = callback.responseXML.getElementsByTagName('msg');
            Zoom.lightboxObj.src = Zoom.site_uri + '/components/com_zoom/www/images/priv_yes.png';
            if (msg[0] && msg[0].firstChild.nodeValue != 'none') Zoom.lightboxObj.parentNode.onmouseover = function(){return overlib(msg[0].firstChild.nodeValue, CAPTION, lb_title);};
        }
    },
    
    slide :
    function(what, siteUrl) {
        var theImage = "";
        if (Zoom.folded[what] == 1) {
          new Effect.SlideDown($(what + 'Body'));
          Zoom.folded[what] = 0;
          theImage = siteUrl + "/components/com_zoom/www/images/blocks/arrow_up_white.png";
        } else {
          new Effect.SlideUp($(what + 'Body'));
          Zoom.folded[what] = 1;
          theImage = siteUrl + "/components/com_zoom/www/images/blocks/arrow_down_white.png";
        }
        MM_swapImage(what + 'Image', '', theImage, 1);
    },
    
    toggleDisplay :
    function(what, siteUrl) {
        var theImage;
        if (Zoom.folded[what] == 1) {
          new Element.show($(what + 'Body'));
          Zoom.folded[what] = 0;
          theImage = "/components/com_zoom/www/images/blocks/arrow_up_white.png";
          MM_swapImage(blockImage, '', theImage, 1);
        } else {
          new Element.hide($(what + 'Body'));
          Zoom.folded[what] = 1;
          theImage = siteUrl + "/components/com_zoom/www/images/blocks/arrow_down_white.png";
        }
        MM_swapImage(what + 'Image', '', theImage, 1);
    },
    
    changeArrow :
    function(what, color, siteUrl) {
        var theImage = "";
        var direction = "";
        if (Zoom.folded[what] == 1) {
            direction = "down";
        } else {
            direction = "up";
        }
        theImage = siteUrl + "/components/com_zoom/www/images/blocks/arrow_" + direction + "_" + color + ".png";
        MM_swapImage(what + 'Image', '', theImage, 1);
    },

    emoticon :
    function(text) {
        var txtarea = document.post.comment;
        text = ' ' + text + ' ';
        if (txtarea.createTextRange && txtarea.caretPos) {
        	var caretPos = txtarea.caretPos;
        	caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? caretPos.text + text + ' ' : caretPos.text + text;
        	txtarea.focus();
        } else {
        	txtarea.value  += text;
        	txtarea.focus();
        }
    },
    
    storeCaret :
    function(textEl) {
        if (textEl.createTextRange) textEl.caretPos = document.selection.createRange().duplicate();
    },
    
    
    getWindowSize :
    function (win) {
    	if (typeof win == "undefined")
    		win = window;
     	if (win.innerHeight != null)
     		return {width: win.innerWidth, height:  win.innerHeight};
    	if (win.document.documentElement && win.document.documentElement.clientHeight)
    		return this.getElementSize(win.document.documentElement);
    	if (win.clientHeight != null)
    		return {width: win.clientWidth, height: win.clientHeight};
    	return this.getElementSize(win.document.body);
    },
    
    getElementSize :
    function (el) {
     	if (el.offsetHeight)
     		return {width: el.offsetWidth, height: el.offsetHeight};
    	if (el.style && el.style.width && el.style.height)
     		return {width: parseInt(el.style.width), height: parseInt(el.style.height)};
    	if (el.clientHeight)
     		return {width: el.clientWidth, height: el.clientHeight};
    	return {width: -1, height: -1};
    }
}

Zoom.load();
