/**
 * site specifc form error copy
 */

zoo.form.showReEnterIntroElement = false;
zoo.form.copy.errorTitle = 'Please check the highlighted areas below';
zoo.form.copy.fieldRequiredMessage = 'Required field';

zoo.dom.widgets.ReadMore = function() {
     $$('a.readmore').each(function(link) {
        var previousElement = link.previous('p');
        if (previousElement) previousElement.appendChild(link);
        return true;
    })    
}

zoo.articleForm = function() {
     return {  
          udpateAffiliationEntry: function(select, entry) {
               var selectedOption = select.options[select.selectedIndex];
               var defaultAffiliation = selectedOption.getAttribute('affiliation');
               if (defaultAffiliation) {
                    entry.setValue(defaultAffiliation);
               }
               return true;
          }
     }         
}()

// reg chart js
zoo.dom.widgets.FreezePaneTable = function() {
    
    var _ieHack = function(height) {
        var tbody  = this.body;
        var table  = tbody.parentNode;
        var thead  = $$('thead', table)[0];

        var theadHeight = thead.getHeight();
      
        var cloneTable = this.cloneTable || table.cloneNode(true);
                   
        var parent = $('regchart-content');
        // var parent = $('main-content');

        var clonediv = this.cloneDiv || new Element('div', {'class': 'freezepane-clone'}).update(cloneTable);
        clonediv.style.height = theadHeight + 10 + 'px';
        
        var tablediv = this.tableDiv || new Element('div', {'class': 'freezepane-original'}).update(table);
        
        tablediv.style.height = height;
        
        parent.appendChild(clonediv);           
        parent.appendChild(tablediv);
        
        this.cloneDiv   = clonediv;
        this.tableDiv   = tablediv;
        this.table      = thead.parentNode;
        this.cloneTable = cloneTable;
        this.head       = thead;
        this.cloneBody  = cloneTable.select('tbody')[0];
        this.cloneHead  = cloneTable.select('thead')[0];
    }
    
    var _freezePaneHack = function(height) {
        var tbody  = this.body;
        var table  = tbody.parentNode;
        var thead  = $(table).select('thead')[0];
        // var thead  = $(document.createElement('tbody'));

        // var cloneTable = this.cloneTable || table.cloneNode(true);
        var cloneTable = this.cloneTable || $(document.createElement('table'));
        var cloneBody  = this.cloneBody  || document.createElement('tbody');
       
        if (!this.cloneHead) {
            var cloneHead  =  thead.cloneNode(true);
            cloneTable.addClassName('freezepane reg-chart zoo');
            cloneTable.appendChild(cloneHead);
            cloneTable.appendChild(cloneBody);
        } else {
            var cloneHead  = this.cloneHead;
        }

        var parent = $('regchart-content');
        // var parent = $('main-content');

        var clonediv = this.cloneDiv || new Element('div', {'class': 'freezepane-clone'}).update(cloneTable);
        
        var theadHeight = $(thead).getHeight();
        clonediv.style.height = theadHeight + 10 + 'px';
        // clonediv.style.height = '25px';
        
        var tablediv = this.tableDiv || new Element('div', {'class': 'freezepane-original'}).update(table);
        
        tablediv.style.height = height;
        
        parent.appendChild(clonediv);           
        parent.appendChild(tablediv);
        
        this.cloneDiv   = $(clonediv);
        this.tableDiv   = $(tablediv);
        this.table      = $(thead.parentNode);
        this.cloneTable = $(cloneTable);
        this.head       = $(thead);
        
        this.cloneBody  = $(cloneBody);
        this.cloneHead  = $(cloneHead);

        /*
        this.cloneBody  = cloneTable.select('tbody')[0];
        this.cloneHead  = cloneTable.select('thead')[0];
        */
        return true;
    }
    
    var _adjustWidth = function() {
        // var w = this.table.parentNode.getWidth();
        // this.cloneTable.style.width = w + 'px';
    }
    
    var _setBodyHeight = function(height) {
        if (!Prototype.Browser.Gecko) {
            _freezePaneHack.call(this, height);
            // _ieHack.call(this, height);
        } else {
            this.body.style.height = height;
        }
        return true;
    }

    var _addScrollClass = function(body) {
        var rows = body.rows;
        var row, last, w = -999;
        for (var i=0; i<rows.length; i++) {
            // row = $$('td', rows[i]);
            row = $(rows[i]).select('td');
            last = row[row.length-1];
            last.addClassName('with-scroll');
            if (!last.parentNode.hasClassName('group')) {
                w = last.getWidth() > w ? last.getWidth() : w;
            }
        }

        if (this.cloneTable) {
            w = this.cloneTable.getWidth();
            this.cloneTable.style.width = w - 15 + 'px';
        }
        
    }
    
    var FreezePane = function() {
        var elements = $$('table[freezepane="Y"] tbody');         
        // only freezpane for now will be one per page for now
        if (!elements.length) return { error: true };
        this.body = elements[0];
        return this;
    }
    FreezePane.prototype = {
        setHeight: function() {
            var tbl = this.body.parentNode;
            var offset = this.body.cumulativeOffset();
            
            // hide table so we can determin if footer is off the page
            tbl.style.display = 'none';
            // get the page height and find out where the footer is
            var pageHeight   = document.viewport.getHeight();
            var footer = $$('.footer')[0];
            var footerOffset = footer.cumulativeOffset()[1];
            // if the footer is starts off the page... we dont care about its height
            // and the table can go to the bottom of the view port
            var footerHeight = footerOffset > pageHeight ? 0 : footer.getHeight();
            
            var bottom       = pageHeight - footerHeight;   
            var h = bottom - offset.top;

            // now add additional padding 
            h += parseInt(this.body.parentNode.getAttribute('sys-padding'))

            // table should not be smaller than 70 pixels
            h = h < 70 ? 70 : h;
            // and px suffix
            var heightPx = h + 'px';
            
            tbl.style.display = 'block';
            _setBodyHeight.call(this, heightPx);
            return this;
        },
        
        setupLastRow: function() {
            // right now IE can't handle this
            if (Prototype.Browser.Gecko) {
                if (this.cloneBody) {
                    _adjustWidth.call(this);
    
                }
                _addScrollClass.call(this, this.body);
            }
            return true;                
        },
        refresh: function() {
            zoo.dom.regChart.freezeTable.setupLastRow();
            zoo.dom.regChart.freezeTable.setHeight();
            return true;
        }
    }       
    
    return function() {
        var freezeTable = new FreezePane();
        if (freezeTable.error) return true;

        freezeTable.setHeight().setupLastRow();

        Event.observe(window, 'resize', function() {
            freezeTable.setHeight();
            return true;
        })

        zoo.dom.regChart.freezeTable = freezeTable;
        return true;
    }     
}()

zoo.dom.widgets.RegChartZoom = function() {
    
    var Zoom = function() {
        var tableContent   = $('regchart-content');
        var tableContainer = tableContent.parentNode;       
        var contentElement = $$('.content')[0];

        this.tableContent   = tableContent;
        this.tableContainer = tableContainer;
        this.layoutContent  = contentElement;
        return this;
    }   
    
    Zoom.prototype = {
        init: function() {
            var tableContent   = this.tableContent;
            var tableContainer = this.tableContainer;       
            var contentElement = this.layoutContent;
    
            // create new content container for zoom chart
            var zoomContainer = new Element('div', {
                 'className': 'content',
                 'id'       : 'regchart-zoom-content',
                 'style'    : 'display: none;'
            });
            
            var header = $$('#main-content h2')[0].cloneNode(true);
            
            zoomContainer.appendChild(header);

            var maxBtn = new Element('button', {
                'id': "min-ico"
            }).update('Minimize Chart');
            
            maxBtn.addClassName('ico');
            maxBtn.title = 'Click To Minimize Chart';
            maxBtn.observe('click', zoo.dom.regChart.zoom.toggle);
            
            zoomContainer.appendChild(maxBtn);
    
            Element.insert(contentElement, { 'before': zoomContainer } );
            
            zoo.dom.makeHoverable(maxBtn);
            
            this.zoomContainer  = zoomContainer;
            this.header         = header;
            this.initToggle();            
            return this;         
        },        
        toggle: function() {
            var zoom = zoo.dom.regChart.zoom;
            zoom[zoom.getNextToggle()]();
            if (zoo.dom.regChart.freezeTable) {
                zoo.dom.regChart.freezeTable.refresh();
            }
            return true;
        },
        max: function() {
            this.layoutContent.hide();
            $('min-ico').insert({before: $('sort-ico')});
            this.zoomContainer.appendChild($('regchart-search-container'));
            this.zoomContainer.appendChild(this.tableContent);            
            this.zoomContainer.show();
            this.setNextToggle('min');
        },
        min: function() {
            this.zoomContainer.hide();
            $('max-ico').insert({before: $('sort-ico')});            
            $(this.tableContainer).insert({before: $('regchart-search-container')});
            this.tableContainer.appendChild(this.tableContent);
            this.layoutContent.show();
            // ie6 has issue with multiclasses. so we will explicity set to visible
            $('left-sidebar').style.visibility  = 'visible';
            $('right-sidebar').style.visibility = 'visible';            
            $('main-content').style.visibility  = 'visible';           
            this.setNextToggle('max');
        },
        initToggle: function() {
            this.setNextToggle('max');
            if (zoo.dom.regChart.toggle == 'max') {
                this.toggle();
            }
            // remove js classname so that styles go back to normal
            // use to prevent js content jumping...
            $(document.body).removeClassName('js');
            $(document.body).addClassName('js-ready');            
        },
        getNextToggle: function() {
            return this.nextToggle;
        },
        setNextToggle: function(val) {
            if (this.nextToggle) {
                zoo.util.setCookie('regchart-toggle', this.nextToggle);
            }
            this.nextToggle = val;
        }
    }
    
    return function(event) {
        var zoom = zoo.dom.regChart.zoom = new Zoom();
        zoom.init();
        return true;
    }
}();

zoo.dom.regChart = {
    resetSort: function() {
        $('search-sortBy').value = '';
        $('search-sortByDirection').value = '';
        $('search-thenBy').value = '';
        $('search-thenByDirection').value = '';
        $('search-filterByJurisdiction').value = '';


        var keywordInput = $('inp-regdb-keyword');
        keywordInput.value = keywordInput.value == '[' + keywordInput.getAttribute('prompt') + ']' ?
                                            '' : keywordInput.value;
        $('frm-regchart-search').submit();
    },
    resetKeywordSearch: function() {
        $('inp-regdb-keyword').value = '';
        $('frm-regchart-search').submit();
        return false;
    },
    updateTableLinks: function() {
        $('regchart-content').observe('click', function(e) {
            var anchor = e.element(e);
            if (anchor.tagName == 'A') {
                /* check for track this item */
                if (anchor.hasClassName('regchart-track-link')) {
                    anchor.clickEvent = e;
                    zoo.dom.regChart.trackItem.ajaxPopup(anchor);
                    e.stop();
                    return false;
                /* other links are then opened in new window if external */                     
                } else {
                    var hostname = window.location.hostname;
                    hostname = hostname.replace("www.","").toLowerCase();                              
                    var href = anchor.href.toLowerCase();
                    if (href.indexOf("http://")!=-1 && href.indexOf(hostname)==-1) {
                        anchor.target = '_new';
                    }
                }                               
            }
            return true;            
        });        
    },
    
    updateTableLinkTargets: function() {                            
        var className = Prototype.Browser.Gecko ? '.freezepane' : '.freezepane-original';
        var anchors = $$('.freezepane .item-name a');
        if (anchors) {
            anchors.each(function(anchor){
               anchor.target = '_new';
            });
        }
        return true;
    },
    
    trackItemHijax: function() {
        var anchors = $$('.regchart-track-link');
        if (anchors) {
            anchors.each(function(anchor){
                $(anchor).observe('click', function(e) {
                    this.clickEvent = e;
                    zoo.dom.regChart.trackItem.ajaxPopup(this);
                    e.stop();
                    return false;
                });
                if (anchor.parentNode && anchor.parentNode.previousSibling) {
                    var previousStatusElm = anchor.parentNode.previousSibling;
                    if (previousStatusElm && previousStatusElm.nodeType == 1 && previousStatusElm.tagName == 'P') {
                        $(previousStatusElm).addClassName('beforeTrackItem');
                    }                    
                }
            });
        }
       return true;
    }
}

zoo.dom.regChart.trackItem = function() {
    var _window;         

    var _getWindow = function(anchor) {
        if (!_window) {     
            var w = _window = {
                hide: function() {
                    this.elm.style.display = 'none';
                    this.onScreen = false;
                },
                show: function() {
                    this.elm.style.display = 'block';
                    this.onScreen = true;
                },
                update: function() {
                    this.elm.update('<img style="margin: 40px" src="http://assets.zooluserver.com/zoolu/loading/bigrotation2.gif" />');                    
                },
                onScreen: false
            };
            var clickEvent = anchor.clickEvent;
            w.elm = new Element('div', {'class': 'window', 'id': 'page-regchart-track'});

            // set dimensions, cater for being close to the edge of the window
            var x = clickEvent.pointerX();
            if (x + 400 > document.viewport.getWidth()) {
                x = document.viewport.getWidth() - 450;
            }
            w.elm.style.left = x + 'px';
            
            var y = clickEvent.pointerY();
            if (y + 210 > document.viewport.getHeight()) {
                y -= 220;
            }
            w.elm.style.top = y -20 + 'px';
            document.body.appendChild(w.elm);
        }
        return _window;
    }

    return {
        ajaxPopup: function(anchor) {
            var w = _getWindow(anchor);
       
            w.update();
            w.show();
            
            this.get(anchor, w);
            return false;
        },
        
        get: function(anchor, w) {
            new Ajax.Updater(w.elm, anchor.href, {
                method: 'get',
                onComplete: function() {
                    new Draggable('page-regchart-track', {
                        handle      : $('regchart-track-window-title'),
                        starteffect : function(element) {
                            new Effect.Opacity(element, {from: 1, to: .9, duration: 0 });
                        },
                        endeffect   : function(element) {
                            new Effect.Opacity(element, {from: .9, to: 1, duration: .3 }); 
                        }
                    });
                    $('frm-regchart-track').onSuccess = zoo.dom.regChart.trackItem.hide;
                    return true;
                }
            });                      
            return;                       
        },
        
        hide: function() {
            var w = _getWindow();
            w.hide();
        }
    }
}();

zoo.dom.regChart.sort = function() {
    var _sortWindow;
    var _getWindow = function(e) {
        if (!_sortWindow) {
            _sortWindow = _init(e);
        }
        return _sortWindow;
    }
    
    var _startEffect = function(element) {
        new Effect.Opacity(element, {from: 1, to: .9, duration: 0 });
    }

    var _endEffect = function(element) {
        new Effect.Opacity(element, {from: .9, to: 1, duration: .3 }); 
    }
    
    var _directionType = {
        regulator: ['By frequency of appearance in chart', 'Alphabetically'],
        topic:     ['By frequency of appearance in chart', 'Alphabetically'],
        name:      ['Alphabetically'],
        publicationDate: ['Newest To Oldest', 'Oldest to Newest']
    }
    
    var _sortChange = function(event, elm) {
        var element = elm || Event.element(event);
        var elementName = element.name;       
        
        var label_one = $('lbl-' + elementName + 'Direction-one');
        var label_two = $('lbl-' + elementName + 'Direction-two');

        var input_one = $('inp-' + elementName + 'Direction-one');
        var input_two = $('inp-' + elementName + 'Direction-two');
        
        var sortType = element.getValue();
        if (sortType) {         
            label_one.innerHTML = _directionType[element.getValue()][0];
            
            if (_directionType[element.getValue()][1]) {
                input_two.removeClassName('hidden');
                label_two.removeClassName('hidden');
                label_two.innerHTML = _directionType[element.getValue()][1];
            } else {
                input_one.checked = true;
                input_two.addClassName('hidden');
                label_two.addClassName('hidden');
            }
        } 
    }
    
    
    var _init = function(e) {
        var w = {
            hide: function() {
                this.elm.style.display = 'none';
                this.onScreen = false;
            },
            show: function() {
                this.elm.style.display = 'block';
                this.onScreen = true;
            },
            onScreen: false
        };
        
        w.elm = new Element('div', {'class': 'regchart-sort window', 'id': 'regchart-sort-window'}).update('<img style="margin: 40px" src="http://assets.zooluserver.com/zoolu/loading/bigrotation2.gif" />');
        w.elm.style.left = document.viewport.getWidth() / 4 - 225 + 'px';
        w.elm.style.top = document.viewport.getHeight() / 4 + 'px';
        
        document.body.appendChild(w.elm);        
        new Ajax.Updater(w.elm, '/portals/public/regchart_sort', {
            method: 'get',
            parameters: {
                sortBy: $F('search-sortBy'),
                sortByDirection: $F('search-sortByDirection'),
                thenBy: $F('search-thenBy'),
                thenByDirection: $F('search-thenByDirection'),
                filterByJurisdiction: $F('search-filterByJurisdiction')
            },
            onComplete: function() {
                var inpSortBy = $('inp-sortBy');
                var inpThenBy = $('inp-thenBy');
                inpSortBy.observe('change', _sortChange);
                inpThenBy.observe('change', _sortChange);
                
                // init if we have values
                _sortChange(null, inpSortBy);
                _sortChange(null, inpThenBy);
                
                // set keyword
                var keywordInput = $('inp-regdb-keyword');
                $('inp-regdb-sort-keyword').value = keywordInput.value == '[' + keywordInput.getAttribute('prompt') + ']' ?
                                                    '' : keywordInput.value;
                
                new Draggable('regchart-sort-window', {
                    handle      : $('regchart-sort-window-title'),
                    starteffect : _startEffect,
                    endeffect   : _endEffect
                });
                return true;
            }
        });        
        return w;
    }
    
    return {
        toggle: function(e) {
            var w = _getWindow(e);
            if (w.onScreen) {
                w.hide();
            } else {
                w.show();
            }
            return true;
        }
    }       
}();

zoo.dom.regChart.toggle = function() {
    var toggleCookie = zoo.util.getCookie('regchart-toggle');
    if (toggleCookie) return toggleCookie;
    return 'min';
}();

zoo.dom.updateArticleLinks = function() {
    $$('.story-body')[0].observe('click', function(e) {
        zoo.dom.updateLinkTarget(e.findElement('a'));     
        return true;            
    });        
}
zoo.dom.updateArticleSummaryLinks = function() {
    $$('.issue-articles')[0].observe('click', function(e) {
        zoo.dom.updateLinkTarget(e.findElement('a'));     
        return true;            
    });        
}
zoo.dom.updateLinkTarget = function(anchor) {
    if (anchor.tagName == 'A') {    
        var hostname = window.location.hostname;
        hostname = hostname.replace("www.","").toLowerCase();                              
        var href = anchor.href.toLowerCase();
        if ((href.indexOf("http://" + hostname + '/files/') >= 0 || href.indexOf(hostname + '/include/') >= 0) 
            ||
            (href.indexOf("http://") != -1 && href.indexOf(hostname) == -1)) {
            anchor.target = '_new';
        }     
    }     
}

zoo.dom.updateFootnotes = function() {
    var refs = $$('a[name^="_ftnref"]');
    
    if (refs.length) {
        refs.each(function(anchor) {
            anchor.wrap(new Element('sup'));
        });
    }
    
    var fns = $$('a[name="_ftn1"]');
    if (fns.length) {    
        var footNote = fns[0];
        var footNoteDivider = footNote.up('p').previous('hr');
         
        if (footNoteDivider) {              
            var notes = footNoteDivider.nextSiblings('p');
            if (notes.length) {
                notes.each(function(container) {
                if (container.match('p')) {
                    container.addClassName('footnote');
                    container.innerHTML = container.innerHTML.replace(/\&nbsp\;/g, '');
                }                
            });
        }    
         
        footNoteDivider.wrap(
            new Element('h4', {
                'class': 'footnote'
            }).insert('<span>Footnotes</span>')
        );
    }
    }
}

zoo.dom.articleTracker = function(articleId) {
     document.write('<img src="/article/' +
                    articleId +
                    '/track?t=' + new Date() * 1 +
                    '" width="1" height="1" alt="" border="" />');
}
