﻿(function($) {

    //Default Options
    var defaultopts = {
        closeClass: 'close',
        dataUrl: null,
        data: null,
        zindex: 2999,
        showOverlay: true,
        dialogClass: 'dialog',
        positionLeftOf: null,
        positionLeftOfPadding: 7
    };

    //Global Variables for our modal box and the overlay
    var overlay;
    var modal;

    //Plugin definition
    $.fn.buzzard = function(settings) {

        //Reset some defaultopts values if user did not define them in settings
        if (settings.dataUrl == undefined) {
            defaultopts.dataUrl = null;
        }
        if (settings.data == undefined) {
            defaultopts.data = null;
        }
        if (settings.dialogClass == undefined) {
            defaultopts.dialogClass = 'dialog';
        }
        if (settings.positionLeftOf == undefined) {
            defaultopts.positionLeftOf = null;
        }

        //Merge parameter settings with the default operators
        var opts = $.extend(defaultopts, settings);

        init(settings);
    }

    //Intialize all of our plugin jazz
    function init(settings) {

        if (defaultopts.showOverlay) {
            //If we have not created the overlay div then do it here
            if ($('#buzzard-overlay').length <= 0) {
                overlay = $("<div id=\"buzzard-overlay\" style=\"display:none; z-index:" + defaultopts.zindex + "; \"></div>");
                $('body').append(overlay);
            }
        }

        // We will recreate this div everytime this plugin is instantiated, and remove it when it is closed
        modal = $("<div id=\"buzzard-dialog\" class=\"" + defaultopts.dialogClass + "\" style=\"display:none;z-index:" + (defaultopts.zindex + 1) + ";\"></div>");
        $('body').append(modal);

        resetPosition();

        //Depending on which options are passed, either get the html with $.ajax
        if (defaultopts.dataUrl != null)
            retrieveContent();
        else if (defaultopts.dataUrl == null && defaultopts.data != null) //or just plug in the html
            $(modal).append(defaultopts.data);

        if (defaultopts.showOverlay) {
            $(overlay).fadeIn('normal', function() {
                $(modal).fadeIn('normal');
            });
        }
        else {
            $(modal).fadeIn('normal');
        }

        bindEvents();
    }

    //Sets the position/width of the background overlay and the modal box
    resetPosition = function() {
        if (defaultopts.showOverlay)
            setBackgroundSize();

        setModalPosition();
    }

    //Sets background overlay height and width
    setBackgroundSize = function() {
        $(overlay).css("height", ($(document).height()) + 'px');
        $(overlay).css("width", $(document).width() + 'px');
    }

    //Gets the position the modal should be at
    getPositionForModal = function() {
        var window_height = $(window).height();
        var window_width = $(window).width();

        var modal_height = $(modal).height();
        var modal_width = $(modal).width();

        return { top_percent: (((window_height - modal_height) / 3) / window_height) * 100, left_percent: (((window_width - modal_width) / 2) / window_width) * 100 };
    }

    //Place Modal in the correct position
    setModalPosition = function() {
        //Either in the center of the page
        if (!defaultopts.positionLeftOf) {
            var pos = getPositionForModal();

            $(modal).css({ "top": Math.max(pos.top_percent, 0) + '%', "left": Math.max(pos.left_percent, 0) + '%' });
        }
        else {
            //Or to the left of a specified element
            var pos = $(defaultopts.positionLeftOf).offset();
            var width = $(defaultopts.positionLeftOf).width();

            $(modal).css({ "top": pos.top + "px", "left": (pos.left + width + defaultopts.positionLeftOfPadding) + "px" });
        }
    }

    //Gets our content using $.ajax
    retrieveContent = function() {
        $.ajax({
            type: 'GET',
            url: defaultopts.dataUrl,
            success: function(data) {
                retrieveContentFinish(data);
            },
            failure: function(data) {
                retrieveContentError(data);
            }
        });
    }

    retrieveContentFinish = function(data) {
        $(modal).append(data);
    }

    retrieveContentError = function(data) {
        alert(data);
    }

    //Binds the events that the plugin uses
    bindEvents = function() {
        $(overlay).click(function() {
            hide();
        });

        $('.' + defaultopts.closeClass).live('click', function() {
            hide();
        });

        $(window).resize(function() {
            resetPosition();
        });
    }

    //Hides the overlay and modal when a closing event is raised
    hide = function() {
        $(modal).fadeOut('normal', function() {
            $(this).children().remove();
            $(this).remove();

            if (defaultopts.showOverlay)
                $(overlay).fadeOut('normal');
        });
    }

})($);
