


jQuery.fn.popper = function(args) {
    args = args || {}
    var width = args.width || null
    var height = args.height || null
    var cellStyle = args.cellStyle || null
    var content = args.content || null
    var img = args.img || null
    var c
    
    this.each(function() {
        try {
            var label = $($(this).children()[0])
        }
        catch(e) {
            var label = $(this)
        }

        var label = $(this)        
        
        
        var o = label.offset()
        var start_width = label.width()
        var start_height = label.height()


        if(start_width > 500)
            start_width = 100
        if(start_height > 500)
            start_height = 100
        
        var pos = {
            left: o.left, 
            top: o.top,
            width: start_width,
            height: start_height}
            

        var onloadd = function() {
            // remove the 'load' listener
            c.unbind()
            var shadow = c.shadowbox(cellStyle).appendTo(document.body)
            if(img) {
                shadow.css('line-height', '1px')
            }
            var width = width || c.width() || parseInt(c.css('width'))
            var height = height || c.height() || parseInt(c.css('height'))

            shadow.css({
                left: pos.left - 10,
                top: pos.top + 10
            })
            var fr = {
                width: pos.width,
                height: pos.height,
                opacity: 0
            }
            var to = {
                width: width, 
                height: height,            
                opacity: 0.7
            }
            var close = function() {
                shadow.find('.close').remove();
                c.css('opacity', 0.7).animate(fr, {easing: 'easeInQuart', duration: 400, complete: function() {
                    shadow.remove()
                }})
            }

            var self = this
            c.css(fr).show().animate(to, {
                    easing: 'easeOutSine', // easeInOutQuart,700
                    duration: 400,
                    complete: function() {
                        c.css('opacity', 1)
                        $('<div class="close"/>').appendTo(shadow.find('.content')).click(close)
                        // Note: A js error here causes this method to call itself in an endless loop
                        if(img) {
                            c.click(close)
                            c.css('cursor', 'pointer')
                        }
                    }
                }
            )            
        }        
        
        if(img) {
    		// Preload image
    		c = $('<img/>').bind('load', onloadd)    		
    		c[0].src = img
		}
		else {
            c = content || $(this).children('.popper')
            onloadd()
        }

    }) // end this.each(..)
    return c
}

jQuery.fn.emailpopper = function(args) {
    var link = args.link
    var recipient = args.recipient
    var name = args.name
    var action = args.action
    var cellStyle = args.cellStyle
    var _ = {
        'My email': 'Min e-post',
        'Message': 'Meddelande',
        'What is 7 added to 2?': 'Vad är sju plus två?',
        'Send to': 'Skicka till', 
        'Sending to': 'Skickar till',         
        'An error has occurred': 'Ett fel har uppstått',
        'name': name,
        'recipient': recipient,
        'Your email has been sent to': 'Ditt meddelande har skickats till',
        'You have entered an invalid email address': 'Du har angivit en felaktig e-postadress',
        'You have not entered any message': 'Du har glömt skriva ett meddelande',
        'Answer the question with a numeric character': 'Svara på frågan med en siffra',
        'You have answered the question incorrectly': 'Du har svarat fel på frågan'
        
    }

    var t = jQuery.fn.emailpopper._tpl
    $.each(_, function(key, val) {
        t = t.replace('{' + key + '}', val)
    })
    
    
    this.each(function() {
        var div = $(this).popper({content: $(t), cellStyle: cellStyle})
        
        
        var form = div.find('form')
        var submit = form.find('.submit')
        
        
        form.ajaxForm({
            dataType: 'json',
            clearForm: true,
            async: true,
            timeout: 20000,
            beforeSubmit: function(data, form, options) {
                var err = false
                d = {}
                $.each(data, function() {
                    d[this.name] = this.value
                })
                
                if(!d.email || d.email.indexOf('@') === -1) {
                    err = _['You have entered an invalid email address']
                }
                else if(!d.message) {
                    err = _['You have not entered any message']
                }
                else if(!parseInt(d.question)) {
                    err = _['Answer the question with a numeric character']
                }
                else if(parseInt(d.question) != 9) {
                    err = _['You have answered the question incorrectly']
                }
                
                if(err) {
                    alert(err)
                    return false
                }

                submit.toggleClass('busy')
                submit.html(_['Sending to'] + ' ' + _['name'] + '..')
            },
            success: function() {
                alert(_['Your email has been sent to'] + ' ' + _['name'])
            },
            error: function(xmlHttp, errMsg, except) {
                alert(_['An error has occurred'] + ':\n' + xmlHttp.responseText)
            },
            complete: function() {
                submit.toggleClass('busy')
                submit.html(_['Send to'] + ' ' + _['name'])
            }
        })
        submit.click(function() { form.submit() }) // form.submit
        
    })
    
}
jQuery.fn.emailpopper._tpl = [
    '<div class="popper emailpopper">',
        '<form action="/popper/send" method="post">',
            '<input type="hidden" name="recipient" value="{recipient}"/>',
            '<p>{My email}<br/>',
                '<input class="email" type="text" style="width: 200px;" name="email"/>',
            '</p>',
            '<p>{Message}<br/>',
                '<textarea class="message" name="message" style="width: 200px; height: 130px"></textarea>',
            '</p>',
            '<p>{What is 7 added to 2?} &nbsp; <input type="text" class="question" name="question"/></p>',
            '<p style="text-align: right">',
                '<div class="submit">{Send to} {name}</div>',
            '</p>',
        '</form>',
    '</div>'
].join('')


jQuery.fn.shadowbox = function(cellStyle) {
    var box;
    this.each(function() {
        box = jQuery.fn.shadowbox._tpl.clone(true).appendTo(document.body)
        var content = box.find('.content')
        if(cellStyle) {
            content.css(cellStyle)
        }
        
        $(this).appendTo(content)        
        return false
    })
    return box;
}
jQuery.fn.shadowbox._tpl = $([
'<table class="shadowbox">',
    '<tbody>',
        '<tr>',
            '<td class="top-lft">&nbsp;</td>',
            '<td><div class="content"></div></td>',            
            '<td class="top-rgt">&nbsp;</td>',
        '</tr>',
        '<tr height="30">',
            '<td class="bot-lft">&nbsp;</td>',
            '<td class="bot-mid">&nbsp;</td>',
            '<td class="bot-rgt">&nbsp;</td>',
        '</tr>',        
    '</tbody>',
'</table>'].join(''))
    
