/*globals $, document, window, tb, tbd, navigator, self, jQuery
 */
$(document).ready(function () {
    $('.simBox').click(function (e) {
        e.preventDefault();
        if (window.webdecalendar.eventView === 0) {
            $.simBox({url: $(this).attr('href'), title: $(this).attr('title'), style: {height: tb.height, width: tb.width}});
        } else {
            $.simBox({url: $(this).attr('href'), title: $(this).attr('title'), style: {height: tbd.height, width: tbd.width}});
        }
    });
    $('.simBoxFlow').click(function (e) {
        e.preventDefault();
        $.simBox({url: $(this).attr('href'), title: $(this).attr('title'), style: {}, name: $(this).attr('id')});
    });
});

(function ($) {
    /* Private functions */
    function showOverlay(elemName) {
        var OLStyle = 'background-color: ' + $.simBox[elemName].settings.OLColor + '; ' +
                      'z-index: ' + ($.simBox[elemName].style['z-index'] - 1) + '; ' +
                      'height: 100%; width: 100%; left: 0; top: 0; display: block; position: fixed;' +
                      'filter: alpha(opacity=' + ($.simBox[elemName].settings.OLOpac * 100) + ');' + 
                      'position: absolute;';
        //because IE is stupid
        if (navigator.appName === 'Microsoft Internet Explorer') {
            OLStyle += 'opacity: ' + ($.simBox[elemName].settings.OLOpac * 100) + '%;';
        } else {
            OLStyle += 'opacity: ' + ($.simBox[elemName].settings.OLOpac) + ';';
        }
        $('#simBoxOverlay').attr('style', OLStyle);
        $('#simBoxOverlay').show();
    }

    // getPageScroll() by quirksmode.com
    function getPageScroll() {
        var xScroll, yScroll;
        if (self.pageYOffset) {
            yScroll = self.pageYOffset;
            xScroll = self.pageXOffset;
        } else if (document.documentElement && document.documentElement.scrollTop) {   // Explorer 6 Strict
            yScroll = document.documentElement.scrollTop;
            xScroll = document.documentElement.scrollLeft;
        } else if (document.body) {// all other Explorers
            yScroll = document.body.scrollTop;
            xScroll = document.body.scrollLeft;
        }
        return [xScroll, yScroll];
    }

    // Adapted from getPageSize() by quirksmode.com
    function getPageHeight() {
        var windowHeight;
        if (self.innerHeight) { // all except Explorer
            windowHeight = self.innerHeight;
        } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
            windowHeight = document.documentElement.clientHeight;
        } else if (document.body) { // other Explorers
            windowHeight = document.body.clientHeight;
        }
        return windowHeight;
    }

    //much easier then making some array copy function...
    function getDefStyle() {
        return {
            'width' : '450px',
            'z-index' : 1000,
            'left' : '500px',
            'top' : '100px',
            'background-color' : '#FFF',
            'display' : 'none',
            'position' : 'absolute'
        };
    }

    function getDefSett() {
        return {
            'OLshow' : true,
            'OLOpac' : '.40',
            'OLColor' : '#000',
            'content' : 'Testing...',
            'AJAX' : false
        };
    }

    function init(config, elemName) {
        if ($.simBox.firstCall === undefined) {
            $(window).resize(function () {
                    $('#simBox').css({top : getPageScroll()[1] + (getPageHeight() / 10), left: $(window).width() / 2 - ($('#simBox').width() / 2)});
                });
            $.simBox.firstCall = false;
        }
        $.simBox[elemName] = {};
        $.simBox[elemName].style = getDefStyle();
        $.simBox[elemName].settings = getDefSett();
        $.simBox[elemName].name = elemName;
        $.simBox[elemName].url = config.url;
        $.simBox[elemName].title = config.title;
        
        for (var styleKey in config.style) {
            $.simBox[elemName].style[styleKey] = config.style[styleKey];
        }
        $.simBox[elemName].style.display = 'none'; //make sure they dont try to display it right away

        for (var setKey in config.settings) {
            $.simBox[elemName].settings[setKey] = config.settings[setKey];
        }
        if ($('#simBoxOverlay').length === 0) {
            $('body').append('<div id="simBoxOverlay" />');
        
            $('#simBoxOverlay').click(function () {
                $.simBox.hide();
            });
        }
        return true;
    }

    /* Public functions */
    $.simBox = function (config) {
        if (config.name === undefined || config.name === '') {
            config.name = 'globalName';
        }
        init(config, config.name);
        $.simBox.show(config.name);
    };

    $.fn.simBox = function (config) {
        if (config.name === undefined || config.name === '') {
            config.name = 'globalName';
        }
        var elemName = config.name;
        $(this).click(function () {
            $.simBox.show(elemName);
        });
        init(config, elemName);
    };

    $.extend($.simBox, {
        //default styles for a popup window...
        def: {
            style: getDefStyle(), 
            settings: getDefSett() 
        },
        avail: true,
        show: function (elemName) {
            if ($.simBox.avail === false) {
                return;
            }
    
            if ($('#simBox').length === 0) {
                $('body').append('<div id="simBox" style="display: none;">Some error occured and the desired content could not be loaded.</div>');
            }
    
            //check if existing simBox is simBox being asked for now
            //if not, redo styles + conten
            /*
            var styleStr = '';
            for (var key in $.simBox[elemName].style) {
                styleStr += key + ": " + $.simBox[elemName].style[key] + "; ";
            }
            $('#simBox').attr('style', styleStr);
            */
            $('#simBox').css($.simBox[elemName].style);
            if (typeof($.simBox[elemName].url) !== 'undefined') {
                $.ajax({
                    type: 'GET',
                    url: $.simBox[elemName].url,
                    success: function (oHTML) {
                        //lets compute the height for oHTML ... 27 is the height of the title, 1 is for the border, 10 for the padding (5 top + 5 bottom)
                        //TOFIX: what if no height was specified... ie simBoxFlow
                        var elemH = $('#simBox').css('height').replace(/px/, '');
                        if (!isNaN(elemH)) {
                            elemH = elemH - 27 - 1 - 10;
                            //oHTML does not return a root node, lets surround it with one and set the height.
                            oHTML = "<div style='height: " + elemH + "px; padding: 5px;'>" + oHTML + "</div>";
                        } else {
                            oHTML = "<div style='padding: 5px;'>" + oHTML + "</div>";
                        }

                        var dispHTML = '<div><div id="eTitle">';
                        if ($.simBox[elemName].title) { //thickbox compatibility
                            dispHTML += "<div style='float:left; padding: 5px 0 5px 5px; ' id='titleName'>" + $.simBox[elemName].title + "</div>";
                        } else if ($('#eventName', oHTML).val()) { //look into the actual form to find the title of the page
                            dispHTML += "<div style='float:left; padding: 5px 0 5px 5px; ' id='titleName'>" + $('#eventName', oHTML).val() + "</div>";
                        }
                        dispHTML += '<div id="eTitleClose"><a id="eTitleCloseButton" onclick="javascript:$.simBox.hide()" href="#" >X</a></div></div>' + oHTML + '</div>';
                        $('#simBox').html(dispHTML);
                        $('#simBox').css({top : getPageScroll()[1] + (getPageHeight() / 10), left: $(window).width() / 2 - ($('#simBox').width() / 2)});
                        $('#simBox').attr('name', elemName);
                        showOverlay(elemName);
                        $('#simBox').show();

                        //lets look through the return html and add simBox click events when applicable
                        $('.simBoxFlow', '#simBox').click(function (e) {
                            e.preventDefault();
                            $.simBox.newBox({url: $(this).attr('href'), title: $(this).attr('title'), style: {}});
                        });
                        $('.simBox', '#simBox').click(function (e) {
                            e.preventdefault();
                            if (window.webdecalendar.eventView === false) {
                                $.simBox({url: $(this).attr('href'), title: $(this).attr('title'), style: {height: tb.height, width: tb.width}});
                            } else {
                                $.simBox({url: $(this).attr('href'), title: $(this).attr('title'), style: {height: tbd.height, width: tbd.width}});
                            }
                        });
                    },
                    failure: function (oHTML) {
                        $('#simBox').attr('name', elemName);
                        showOverlay(elemName);
                        $('#simBox').show();
                    }
                });
            }
            $(document).bind('keydown.simBox', function (e) {
                if (e.keyCode === 27) { 
                    $.simBox.hide(elemName); 
                }
                return true;
            });
            $.simBox.avail = false;
        },
        hide: function () {
            $('#simBox').attr('style', '');
            $('#simBox').hide();
            $('#simBoxOverlay').hide();
            $.simBox.avail = true;
        },
        resize: function (size) {
            if (typeof(size.height) === 'undefined' || typeof(size.width) === 'undefined') {
                return false;
            }
            $('#simBox').attr('style', 'height: ' + size.height + '; width: ' + size.width + ';');
        },
        newBox: function (config) {
            if (config.name === undefined || config.name === '') {
                config.name = 'globalName';
            }
            //means there is not an open simBox already, this function is inappropriate in this case
            if ($.simBox.avail) {
                return false;
            }
            $.simBox.avail = true;

            init(config, config.name);
            $('#simBox').hide();
            $.simBox.show(config.name);
        }
    });

}(jQuery));
