/*global $, $$, $A, Ajax, Effect, Element, Event, Browser, SWFObject, sIFR, named, DEBUG */

/**************************************************************
 *                     SITE SPECIFIC CODE 
 **************************************************************/
/*global menuitemhover, attachMenuHandler */ 
/*members addParam, each, hide, id, name, observe, replaceElement, sCase, 
    sColor, sFlashSrc, sWmode, show, version, write
*/
var menuitemhover = false;
var DEBUG = false;

function attachMenuHandler() {
    $$('.menulink').each(function (el) {
        Event.observe(el, 'mouseover', function (e) {
            var child_id = el.id + '_child'; 
            if ($(child_id)) { 
                $(child_id).show();
            }
        });

        Event.observe(el, 'mouseout', function (e) {
            var child_id = el.id + '_child';
            if ($(child_id)) { 
                if (!menuitemhover) {
                    $(el.id + '_child').hide();
                }
            }
        });
    });
    
    $$('.child').each(function (el) {
        Event.observe(el, 'mouseover', function (e) {
            $(el).show();
            menuitemhover = true;
        });

        Event.observe(el, 'mouseout', function (e) {
            $(el).hide();
            menuitemhover = false;
        });     
    }); 
}

Event.observe(window, 'load', function () {
    var so;
    
    attachMenuHandler();

    if ($('body_besloten')) {
        so = new SWFObject("/swf/happyheader_besloten.swf", "happyheader_flash", "712", "324", "8", "#000000");
    } else {
        so = new SWFObject("/swf/happyheader.swf", "happyheader_flash", "712", "324", "8", "#000000");
    }
    // Happy Flash Header
    so.addParam("wmode", "transparent");

    if ($('banner')) {
        so.write("banner");
    }

    // Flash Font replacement
    if (typeof sIFR === 'function') {
        sIFR.replaceElement('div#login h2', named({sFlashSrc: '/swf/fonts/bryantbold.swf', sColor: '#ffffff', sWmode: 'transparent', sCase: 'upper'}));
        //sIFR.replaceElement('div#deelnemers h2', named({sFlashSrc: '/swf/fonts/bryantbold.swf', sColor: '#56267d', sWmode: 'transparent', sCase: 'upper'}));
        sIFR.replaceElement('div#tmpmenu h2', named({sFlashSrc: '/swf/fonts/bryantbold.swf', sColor: '#56267d', sWmode: 'transparent', sCase: 'upper'}));
        sIFR.replaceElement('div#info h2', named({sFlashSrc: '/swf/fonts/bryantbold.swf', sColor: '#ffffff', sWmode: 'transparent', sCase: 'upper'}));
        sIFR.replaceElement('div#stelling h2', named({sFlashSrc: '/swf/fonts/bryantbold.swf', sColor: '#d13051', sWmode: 'transparent', sCase: 'upper'}));
        sIFR.replaceElement('div#nieuwsbrief h2', named({sFlashSrc: '/swf/fonts/bryantbold.swf', sColor: '#ffffff', sWmode: 'transparent', sCase: 'upper'}));
        sIFR.replaceElement('div.datum', named({sFlashSrc: '/swf/fonts/bryantbold.swf', sColor: '#d13051', sWmode: 'transparent', sCase: 'upper'}));
        sIFR.replaceElement('.nieuwsitem h1', named({sFlashSrc: '/swf/fonts/bryantbold.swf', sColor: '#56267d', sWmode: 'transparent', sCase: 'upper'}));
        sIFR.replaceElement('.content h1', named({sFlashSrc: '/swf/fonts/bryantbold.swf', sColor: '#56267d', sWmode: 'transparent', sCase: 'upper'}));
        //sIFR.replaceElement('.nieuwsitem h1', '/swf/fonts/bryantbold.swf', '#000000', '#000000', '#FFFFFF', '#FFFFFF', 0, 0, 0, 0);
    }
});


/**************************************************************
 *                           POLL
 **************************************************************/
/*global Poll */
/*members Request, attach, checked, each, getElementsByClassName, 
    innerHTML, method, observe, onComplete, onLoading, postBody, 
    responseText, stop, value
*/
var Poll = {
    attach : function (pollForm, pollId) {
        var answers, validated, A;
        pollForm = $(pollForm);
        
        Event.observe(pollForm, 'submit', function (event) {
            Event.stop(event);      
            
            answers = $A(pollForm.getElementsByClassName('pollAnswer'));
            validated = false;
            
            answers.each(function (answer) {
                if (answer.checked) {
                    validated = answer.value;
                }
            });
    
            if (validated) {
                A = new Ajax.Request('/polls/vote/', {
                    method: 'post',
                    postBody: 'poll_id=' + pollId + '&answer_id=' + validated,
                    onLoading: function () {
                    },
                    onComplete: function (t) {
                        pollForm.innerHTML = t.responseText;
                    }
                });
            } else {
                return false;
            }
        });
    }
};


/**************************************************************
 *                      COMMENTS 
 **************************************************************/
/*global Comments, base64_encode, utf8_encode */

/*members charAt, charCodeAt, fromCharCode, join, length, replace, slice
*/
function utf8_encode ( str_data ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)        
    // *     example 1: utf8_encode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'
 
    str_data = str_data.replace(/\r\n/g,"\n");
    var tmp_arr = [], ac = 0;
 
    for (var n = 0; n < str_data.length; n++) {
        var c = str_data.charCodeAt(n);
        if (c < 128) {
            tmp_arr[ac++] = String.fromCharCode(c);
        } else if((c > 127) && (c < 2048)) {
            tmp_arr[ac++] = String.fromCharCode((c >> 6) | 192);
            tmp_arr[ac++] = String.fromCharCode((c & 63) | 128);
        } else {
            tmp_arr[ac++] = String.fromCharCode((c >> 12) | 224);
            tmp_arr[ac++] = String.fromCharCode(((c >> 6) & 63) | 128);
            tmp_arr[ac++] = String.fromCharCode((c & 63) | 128);
        }
    }
    
    return tmp_arr.join('');
}

function base64_encode( data ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Tyler Akins (http://rumkin.com)
    // +   improved by: Bayron Guevara
    // +   improved by: Thunder.m
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)        
    // -    depends on: utf8_encode
    // *     example 1: base64_encode('Kevin van Zonneveld');
    // *     returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
 
    // mozilla has this native
    // - but breaks in 2.0.0.12!
    //if (typeof window['atob'] == 'function') {
    //    return atob(data);
    //}
        
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = ac = 0, enc="", tmp_arr = [];
    data = utf8_encode(data);
    
    do { // pack three octets into four hexets
        o1 = data.charCodeAt(i++);
        o2 = data.charCodeAt(i++);
        o3 = data.charCodeAt(i++);
 
        bits = o1<<16 | o2<<8 | o3;
 
        h1 = bits>>18 & 0x3f;
        h2 = bits>>12 & 0x3f;
        h3 = bits>>6 & 0x3f;
        h4 = bits & 0x3f;
 
        // use hexets to index into b64, and append result to encoded string
        tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
    } while (i < data.length);
    
    enc = tmp_arr.join('');
    
    switch( data.length % 3 ){
        case 1:
            enc = enc.slice(0, -2) + '==';
        break;
        case 2:
            enc = enc.slice(0, -1) + '=';
        break;
    }
 
    return enc;
}

/*members Request, addClassName, attachAjax, attachDivEffects, 
    attachTableEffects, catchLinks, childNodes, commentContainer, 
    commentListContainer, cursor, each, error, handleResponse, hide, href, 
    id, innerHTML, insertBefore, location, observe, onComplete, onFailure, 
    onLoading, onSuccess, parentNode, pathname, placeMessage, 
    removeClassName, replace, responseText, setStyle, stop, title, toggle, 
    updateCommentList
*/  
var Comments = {
    commentContainer : undefined,    
    commentListContainer: undefined,
    
    attachAjax : function (commentContainer, commentListContainer) {
        if (commentContainer && $(commentContainer)) {
            if (commentListContainer && $(commentListContainer)) {
                Comments.commentContainer = $(commentContainer);
                Comments.commentListContainer = $(commentListContainer);
                Comments.catchLinks();
            } else {
                if (DEBUG) {
                    console.error('Note to programmer:\n\n\t' + (commentListContainer === undefined?'This method requires the ID of the element containing the comment list as second param.': 'Element required for Comments does not excist.\nPlease create an Element with the ID "' + commentListContainer + '"'));
                }
            }
        } else {
            if (DEBUG) {
                console.error('Note to programmer:\n\n\t' + (commentContainer === undefined?'This method requires the ID of the element containing all the comments etc. as first param.': 'Element required for Comments does not excist.\nPlease create an Element with the ID "' + commentContainer + '" containing all the comments etc.'));
            }
        }
    },
    
    catchLinks : function () {
        // catch all links who's response should replace the comment block
        $$('.comments_replace').each(function (element) {
            Event.observe(element, 'click', function (event) {
                Event.stop(event);
                Comments.handleResponse(element.href, function (sMessage) {
                    Comments.commentListContainer.innerHTML = sMessage;
                });
            });
        });

        // catch all links who's response should place a message
        $$('.comments_place_message').each(function (element) {
            Event.observe(element, 'click', function (event) {
                Event.stop(event);
                Comments.handleResponse(element.href, function (sMessage) {
                    Comments.updateCommentList(sMessage);
                });
            });
        });
    },
    
    updateCommentList : function (sMessage) {
        if (Comments.commentContainer) {
            Comments.handleResponse('/comments/showlist/page:' + base64_encode(window.location.pathname)+'/', function (sCommentList) {
                Element.replace(Comments.commentContainer, sCommentList);
                // reasign the reference to the listcontainer
                Comments.commentListContainer = $(Comments.commentListContainer.id);
                if (sMessage) {
                    Comments.placeMessage(sMessage);
                } 
            });
        } else {
            if (DEBUG) {
                console.error('Note to programmer:\n\n\tElement required for Comments does not excist.' + (Comments.commentContainer === undefined?'Please pass the ID of the element containing the comment list using Comments.attachAjax()': '\nPlease create an Element with the ID "' + Comments.commentContainer + '"'));
            }
        }
    },
// We don't catch form, because we've no time to build an AJAX file upload!
/*    catchForm : function (commentsForm) {
        var sURL, sMessage, A;
        if(commentsForm && $(commentsForm)){
            Comments.commentsForm = $(commentsForm);        
            Comments.commentsForm.observe('submit', function (event) {
                Event.stop(event);
                sURL = Comments.commentsForm.action;

                bSucces = false;
                sMessage = 'Er is iets mis gegaan... probeer het later opnieuw';
                A = new Ajax.Request(sURL, {
                    method: 'post',
                    postBody: Form.serializeElements(Comments.commentsForm.getElements(), true),
                    onLoading: function () {
                        // show spinner?
                    },
                    onSuccess: function (transport) {
                        sMessage = transport.responseText;
                        bSucces = true;
                    },
                    onComplete: function (transport) {
                        if(bSucces === true){
                            Comments.updateCommentList(sMessage);
                        } else {
                            Comments.placeMessage(sMessage);
                        }
                    }
                });
            });
        } else {
            if (DEBUG) {
                console.error('Note to programmer:\n\n\t' + (commentsForm === undefined?'This method requires the ID of the comment form as param.': 'Element required for Comments does not excist.\nPlease create an Form with the ID "' + commentsForm + '"'));
            }
        }
    },
    */
    
    placeMessage : function (sMessage) {
        if (!$('comments_message_container')) {
            if (Comments.commentListContainer) {
                //create placeholder for messages
                var messageContainer = new Element('p', {'id': 'comments_message_container'});
                messageContainer.innerHTML = ' ';
                Comments.commentListContainer.insertBefore(messageContainer, Comments.commentListContainer.childNodes[0]);
            } else {
                if (DEBUG) {
                    console.error('Note to programmer:\n\n\tElement required for Comments does not excist.' + (Comments.commentListContainer === undefined?'Please pass the ID of the element containing the comment list using Comments.attachAjax()': '\nPlease create an Element with the ID "' + Comments.commentListContainer + '"'));
                }
            }
        }       
        $('comments_message_container').innerHTML = sMessage;
    },
    
    handleResponse : function (sURL, sFunction, sSpinner) {
        var oA, bSucces, sMessage;
        
        if (typeof(sFunction) === 'function') {
            // we should always return something
            bSucces = false;
            sMessage = 'Er is iets mis gegaan... probeer het later opnieuw';
            
            oA = new Ajax.Request(sURL, {
                onLoading: function () {
                    //console.info('loading...');
                    if ($(sSpinner)) {
                        $(sSpinner).innerHTML = '<img src="/img/spinner.gif" alt="loading..." />';
                    }
                },
                onFailure: function () {
                    // error message is already set
                },
                onSuccess: function (transport) {
                    sMessage = transport.responseText;
                    bSucces = true;
                },
                onComplete: function () {
                    //wait for request to complete then run function
                    sFunction(sMessage);
                    return bSucces;
                }
            });
        } else {
            if (DEBUG) {
                console.error('Note to programmer:\n\n\tComments.handleResponse() requires a function as param.');
            }
        }
    },
    
    attachTableEffects: function () { // see happyfris.nl template for HTML example
        //TODO: code needs various checks and cleanups
        $$('#notities tr.comment_row').each(function (el) {
            $(el.id.replace('comment_', 'comment_content_')).hide();
            el.observe('mouseover', function (e) {
                el.addClassName('hover');
            });
            el.observe('mouseout', function (e) {
                el.removeClassName('hover');
            });
            el.observe('click', function (e) {
                $(el.id.replace('comment_', 'comment_content_')).toggle();
            });
        });
    },
    
    attachDivEffects: function () {
        if ($('notities')) {
            // get all titles
            $$('#notities .comment_title').each(function (element) {
                var CommentContent;
                CommentContent = $$('#' + element.parentNode.id + ' .comment_content')[0];
                // hide content
                CommentContent.toggle();
                $(element).setStyle({'cursor': 'pointer'});
                element.title = CommentContent.innerHTML;
                // watch titles for click
                element.observe('click', function (event) {
                    CommentContent.toggle();
                });
            });
        }
    }
};