jQuery.qparam = function(name, loc) {
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var results = (new RegExp("[\\?&]"+name+"=([^&#]*)")).exec(loc ? loc.href : window.location.href);
    return results ? unescape(results[1]) : '';
}

jQuery.fn.populateFromQuery = function(params) {
    return this.each(function(){
        for (i=0; i<params.length; i++) {
            jQuery(this).find(':input[name='+params[i]+']').val(jQuery.qparam(params[i]));
        }
    });
}

jQuery.fn.tmform = function(options) {
    var opts = jQuery.extend({}, jQuery.fn.tmform.defaults, options);
    
    return this.each(function(){
        // the form submit handler creates a temporary iframe, sets the form to submit to it, and saves the callback
        jQuery(this).bind(opts.bind, function() {
            if (jQuery.fn.tmform.sevt)
                jQuery(this).children(':input[name=sevt]').val(jQuery.fn.tmform.sevt); // always submit sevt if one is present
            if (opts.type == 'refer' || opts.type == 'forward' || opts.type == 'annotate')
                jQuery(this).children(':input[name=dest]').val(opts.callback_url+'?tmsevt='+(jQuery.fn.tmform.sevt || ''));
            else
                jQuery(this).children(':input[name=dest]').val(opts.callback_url+'?tmsevt=##se.id##');
            
            if (opts.debug) {
                if (opts.callback)
                    opts.callback();
                return false;
            } else {
                var frameName = 'tmf' + Math.floor(Math.random() * 99999);
                jQuery(document.body).append('<div style="display:none;"><iframe style="display:none" src="about:blank" id="'+frameName+'" name="'+frameName+'" onload="jQuery.fn.tmform.callback(\''+frameName+'\')"></iframe></div>');
                jQuery(this).attr('target', frameName);
                jQuery('#'+frameName).data('completeCallback', opts.callback);
                return true;
            }
        });
        
        if (opts.type == 'enter' || opts.type == 'subscribe') {
            if (opts.list)
                jQuery(this).append('<input type="hidden" name="lists" value="'+opts.list+'" />');
            jQuery(this).attr('action', opts.instance.indexOf('.') == -1 ? 'http://'+opts.instance+'.taguchimail.com/public/subscriber' : 'http://'+opts.instance+'/public/subscriber');
            jQuery(this).attr('method', 'POST');
        } else if (opts.type == 'refer' || opts.type == 'forward') {
            jQuery(this).attr('action', opts.instance.indexOf('.') == -1 ? 'http://'+opts.instance+'.taguchimail.com/forward/' : 'http://'+opts.instance+'/forward/');
            jQuery(this).attr('method', 'POST');
        } else if (opts.type == 'annotate') {
            // event annotation -- don't create a new event, just append custom fields to an existing one.
            jQuery(this).attr('action', opts.instance.indexOf('.') == -1 ? 'http://'+opts.instance+'.taguchimail.com/public/annotate' : 'http://'+opts.instance+'/public/annotate');
            jQuery(this).attr('method', 'POST');
        }
        
        if (opts[opts.type].event_id)
            jQuery(this).append('<input type="hidden" name="evt" value="'+opts[opts.type].event_id+'" />');
        if (opts[opts.type].template_id)
            jQuery(this).append('<input type="hidden" name="msg" value="'+opts[opts.type].template_id+'" />');
        if (opts[opts.type].activity_id)
            jQuery(this).append('<input type="hidden" name="src" value="'+opts[opts.type].activity_id+'" />');
        
        if (opts.data)
            jQuery(this).append('<input type="hidden" name="data" value="'+opts.data+'" />');
        if (opts.campaign_id)
            jQuery(this).append('<input type="hidden" name="campaign" value="'+opts.campaign_id+'" />');
        jQuery(this).append('<input type="hidden" name="sevt" value="" />');
        jQuery(this).append('<input type="hidden" name="dest" value="" />');
    });
};

jQuery.fn.tmform.defaults = {
    instance: 'demo',
    callback_url: window.location.href.substring(0, window.location.href.lastIndexOf('/')+1)+'callback.html',
    list: null,
    campaign_id: null,
    data: 'jquery.tmpublic.js',
    debug: false,
    bind: 'submit',
    enter: {
        event_id: null,
        template_id: null,
        activity_id: null
    },
    refer: {
        event_id: null,
        template_id: null,
        activity_id: null
    },
    forward: {
        event_id: null,
        template_id: null,
        activity_id: null
    },
    subscribe: {
        event_id: null,
        template_id: null,
        activity_id: null
    },
    annotate: {
        
    }
};

jQuery.fn.tmform.sevt = jQuery.qparam('sevt');

jQuery.fn.tmform.callback = function(frame) {
    var frameElement = document.getElementById(frame);
    documentElement = frameElement.contentDocument || frameElement.contentWindow.document || window.frames[frame].document
    if (documentElement.location.href == "about:blank")
        return;
    
    jQuery.fn.tmform.sevt = jQuery.qparam('tmsevt', documentElement.location);
    
    if (typeof($(frameElement).data('completeCallback')) == 'function')
        $(frameElement).data('completeCallback')();
};
