(function() {

  // Localize jQuery variable
  var jQuery;

  function create_js_tag(url) {
    var script_tag = document.createElement('script');
    script_tag.setAttribute("type","text/javascript");
    script_tag.setAttribute("src", url);
    return script_tag;
  }

  function add_js_tag(script_tag) {
    // Try to find the head, otherwise default to the documentElement
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
  }

  /******** Load jQuery if not present *********/
  if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') {
    // create jquery script tag
    var script_tag = create_js_tag("http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js");
    script_tag.onload = scriptLoadHandler;
    script_tag.onreadystatechange = function () { // Same thing but for IE
      if (this.readyState == 'complete' || this.readyState == 'loaded') {
        scriptLoadHandler();
      }
    };
    add_js_tag(script_tag);
  } else {
    // The jQuery version on the window is the one we want to use
    jQuery = window.jQuery;
    main();
  }

  /******** Called once jQuery has loaded ******/
  function scriptLoadHandler() {
    // Restore $ and window.jQuery to their previous values and store the
    // new jQuery in our local jQuery variable
    jQuery = window.jQuery.noConflict(true);
    main();
  }

  /******** Our main function ********/
  function main() {
    // required files (plugins, etc)
    // MyBlanket
(function($) {
  $.fn.myBlanket = function(html, options) {
    var e = this.eq(0);
    var offset = e.offset();
    var options = $.extend({}, $.fn.myBlanket.options, options);
    offset.top = Math.round(offset.top)
    offset.left = Math.round(offset.left)
    var id = options.id_attr || options.class_attr + '_' + offset.top + '_' + offset.left;

    $('body').prepend('<div id="' + id + '" class="' + options.class_attr + '">' + html + '</div>');
    var blanket = $('#' + id);
    blanket.css({
      left: offset.left + 'px',
      position: 'absolute',
      top: offset.top + 'px'
    })
      .width(e.outerWidth() - blanket.outerWidth())
      .height(e.outerHeight() - blanket.outerHeight());
    return this;
  };

  $.fn.myBlanket.options = {
    class_attr: 'blanket'
  };
})(jQuery);

//////////////////////////////////////////////////

// jquery.jsonp 2.1.2 (c)2010 Julian Aubourg | MIT License
// http://code.google.com/p/jquery-jsonp/
(function(e,b){function d(){}function t(C){c=[C]}function m(C){f.insertBefore(C,f.firstChild)}function l(E,C,D){return E&&E.apply(C.context||C,D)}function k(C){return/\?/.test(C)?"&":"?"}var n="async",s="charset",q="",A="error",r="_jqjsp",w="on",o=w+"click",p=w+A,a=w+"load",i=w+"readystatechange",z="removeChild",g="<script/>",v="success",y="timeout",x=e.browser,f=e("head")[0]||document.documentElement,u={},j=0,c,h={callback:r,url:location.href};function B(C){C=e.extend({},h,C);var Q=C.complete,E=C.dataFilter,M=C.callbackParameter,R=C.callback,G=C.cache,J=C.pageCache,I=C.charset,D=C.url,L=C.data,P=C.timeout,O,K=0,H=d;C.abort=function(){!K++&&H()};if(l(C.beforeSend,C,[C])===false||K){return C}D=D||q;L=L?((typeof L)=="string"?L:e.param(L,C.traditional)):q;D+=L?(k(D)+L):q;M&&(D+=k(D)+escape(M)+"=?");!G&&!J&&(D+=k(D)+"_"+(new Date()).getTime()+"=");D=D.replace(/=\?(&|$)/,"="+R+"$1");function N(S){!K++&&b(function(){H();J&&(u[D]={s:[S]});E&&(S=E.apply(C,[S]));l(C.success,C,[S,v]);l(Q,C,[C,v])},0)}function F(S){!K++&&b(function(){H();J&&S!=y&&(u[D]=S);l(C.error,C,[C,S]);l(Q,C,[C,S])},0)}J&&(O=u[D])?(O.s?N(O.s[0]):F(O)):b(function(T,S,U){if(!K){U=P>0&&b(function(){F(y)},P);H=function(){U&&clearTimeout(U);T[i]=T[o]=T[a]=T[p]=null;f[z](T);S&&f[z](S)};window[R]=t;T=e(g)[0];T.id=r+j++;if(I){T[s]=I}function V(W){(T[o]||d)();W=c;c=undefined;W?N(W[0]):F(A)}if(x.msie){T.event=o;T.htmlFor=T.id;T[i]=function(){T.readyState=="loaded"&&V()}}else{T[p]=T[a]=V;x.opera?((S=e(g)[0]).text="jQuery('#"+T.id+"')[0]."+p+"()"):T[n]=n}T.src=D;m(T);S&&m(S)}},0);return C}B.setup=function(C){e.extend(h,C)};e.jsonp=B})(jQuery,setTimeout);

//////////////////////////////////////////////////

/* Copyright (c) 2010 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (MIT_LICENSE.txt)
 * and GPL Version 2 (GPL_LICENSE.txt) licenses.
 *
 * Version: 1.1.1
 * Requires jQuery 1.3+
 * Docs: http://docs.jquery.com/Plugins/livequery
 */
(function(a){a.extend(a.fn,{livequery:function(e,d,c){var b=this,f;if(a.isFunction(e)){c=d,d=e,e=undefined}a.each(a.livequery.queries,function(g,h){if(b.selector==h.selector&&b.context==h.context&&e==h.type&&(!d||d.$lqguid==h.fn.$lqguid)&&(!c||c.$lqguid==h.fn2.$lqguid)){return(f=h)&&false}});f=f||new a.livequery(this.selector,this.context,e,d,c);f.stopped=false;f.run();return this},expire:function(e,d,c){var b=this;if(a.isFunction(e)){c=d,d=e,e=undefined}a.each(a.livequery.queries,function(f,g){if(b.selector==g.selector&&b.context==g.context&&(!e||e==g.type)&&(!d||d.$lqguid==g.fn.$lqguid)&&(!c||c.$lqguid==g.fn2.$lqguid)&&!this.stopped){a.livequery.stop(g.id)}});return this}});a.livequery=function(b,d,f,e,c){this.selector=b;this.context=d;this.type=f;this.fn=e;this.fn2=c;this.elements=[];this.stopped=false;this.id=a.livequery.queries.push(this)-1;e.$lqguid=e.$lqguid||a.livequery.guid++;if(c){c.$lqguid=c.$lqguid||a.livequery.guid++}return this};a.livequery.prototype={stop:function(){var b=this;if(this.type){this.elements.unbind(this.type,this.fn)}else{if(this.fn2){this.elements.each(function(c,d){b.fn2.apply(d)})}}this.elements=[];this.stopped=true},run:function(){if(this.stopped){return}var d=this;var e=this.elements,c=a(this.selector,this.context),b=c.not(e);this.elements=c;if(this.type){b.bind(this.type,this.fn);if(e.length>0){a.each(e,function(f,g){if(a.inArray(g,c)<0){a.event.remove(g,d.type,d.fn)}})}}else{b.each(function(){d.fn.apply(this)});if(this.fn2&&e.length>0){a.each(e,function(f,g){if(a.inArray(g,c)<0){d.fn2.apply(g)}})}}}};a.extend(a.livequery,{guid:0,queries:[],queue:[],running:false,timeout:null,checkQueue:function(){if(a.livequery.running&&a.livequery.queue.length){var b=a.livequery.queue.length;while(b--){a.livequery.queries[a.livequery.queue.shift()].run()}}},pause:function(){a.livequery.running=false},play:function(){a.livequery.running=true;a.livequery.run()},registerPlugin:function(){a.each(arguments,function(c,d){if(!a.fn[d]){return}var b=a.fn[d];a.fn[d]=function(){var e=b.apply(this,arguments);a.livequery.run();return e}})},run:function(b){if(b!=undefined){if(a.inArray(b,a.livequery.queue)<0){a.livequery.queue.push(b)}}else{a.each(a.livequery.queries,function(c){if(a.inArray(c,a.livequery.queue)<0){a.livequery.queue.push(c)}})}if(a.livequery.timeout){clearTimeout(a.livequery.timeout)}a.livequery.timeout=setTimeout(a.livequery.checkQueue,20)},stop:function(b){if(b!=undefined){a.livequery.queries[b].stop()}else{a.each(a.livequery.queries,function(c){a.livequery.queries[c].stop()})}}});a.livequery.registerPlugin("append","prepend","after","before","wrap","attr","removeAttr","addClass","removeClass","toggleClass","empty","remove","html");a(function(){a.livequery.play()})})(jQuery);

    jQuery(function($) {
      var widget_container = $('#mc_t2g_1408hvrI3tybP_widget_container');

      // insert widget
      widget_container.html("<div class=\'t2gwidget\'>\n<noscript>\nYou must have JavaScript enabled to use this giving widget\n<\/noscript>\n<div class=\'t2gwidget-header\'>\n<h1 class=\'title\'>Make a Donation<\/h1>\n<\/div>\n<div class=\'t2gwidget-logo\'>\n<table>\n<tr>\n<td><img alt=\"2011 Campaign\" src=\"http://t2g.assets.mobilecause.com.s3.amazonaws.com/campaigns/logos/1408hvrI3tybP/widget_uw logo.bmp?1307039758\" /><\/td>\n<\/tr>\n<\/table>\n<\/div>\n<div class=\'t2gwidget-right_col\'>\n<style type=\'text/css\'>\n.t2gwidget-meter .inner {\n  width: 224px; }\n  .t2gwidget-meter .inner .casing .filled {\n    width: 0.448px; }\n\n<\/style>\n<div class=\'t2gwidget-meter\'>\n<div class=\'info\'>\n$10 of $5000 raised\n<\/div>\n<div class=\'inner\'>\n<div class=\'casing\'>\n<div class=\'filled\'><\/div>\n<\/div>\n<div class=\'numbers\'>\n<div class=\'numbers_inner\'>\n<div>\n$1,250\n<\/div>\n<div>\n$2,500\n<\/div>\n<div>\n$3,750\n<\/div>\n<div>\n$5,000\n<\/div>\n<\/div>\n<div class=\'clear\'><\/div>\n<\/div>\n<\/div>\n<\/div>\n\n<form accept-charset=\"UTF-8\" action=\"http://t2g-widget.mobilecause.com/campaigns/1408hvrI3tybP/donations\" class=\"new_t2g_donation\" id=\"new_t2g_donation_for_campaign_1408hvrI3tybP\" method=\"post\"><div style=\"margin:0;padding:0;display:inline\"><input name=\"utf8\" type=\"hidden\" value=\"&#x2713;\" /><input name=\"authenticity_token\" type=\"hidden\" value=\"JFRRZO3u8Q+Ypn8KOwENt7edJBIXtgk2zsYntwbiiHo=\" /><\/div>\n<input id=\"t2g_donation_opt_in_url_for_campaign_1408hvrI3tybP\" name=\"t2g_donation[opt_in_url]\" type=\"hidden\" />\n<div class=\'input_box\'>\n<label for=\'t2g_donation_phone_number_for_campaign_1408hvrI3tybP\'>Enter mobile number to make a donation<\/label>\n<input id=\"t2g_donation_phone_number_for_campaign_1408hvrI3tybP\" name=\"t2g_donation[phone_number]\" size=\"30\" type=\"text\" value=\"\" />\n<\/div>\n<div class=\'check_box\'>\n<input id=\'agree_for_campaign_1408hvrI3tybP\' type=\'checkbox\'>\n<label for=\'agree_for_campaign_1408hvrI3tybP\'>\nDonate\n<span class=\'donation_amount\'>\n$10\n<\/span>\nand agree to\n<\/label>\n<a href=\"http://igfn.org/t\" class=\"terms_link_popup\">Terms and Conditions<\/a>\n<\/div>\n<ul class=\'t2gwidget-msgs-container\'><\/ul>\n<button type=\'submit\'>\n<span class=\'inner1\'>\n<span class=\'inner2\'>\nDonate\n$10\nNow\n<\/span>\n<\/span>\n<\/button>\n<\/form>\n<div class=\'t2gwidget-compliance-text\'>\n<p>\n<span class=\'first-sentence\'>\nA one-time donation of\n$10\nwill be added to your mobile phone bill or deducted from your prepaid balance.\n<\/span>\nMsg&amp;Data Rates May Apply. All charges are billed by and payable to your mobile service provider. Service is available on AT&amp;T, Verizon Wireless, and Sprint. All donations must be authorized by mobile account holder.\n<strong>\nTo stop text STOP to\n85944,\nfor help text HELP to\n85944.\n<\/strong>\n<br>\n<a href=\"http://igfn.org/t\" class=\"terms_link_popup\">Full Terms<\/a>\n|\n<a href=\"http://clients.mobilecause.com/privacy-policy\" class=\"terms_link_popup\">Privacy Policy<\/a>\n<\/p>\n<\/div>\n\n<\/div>\n<div class=\'clear\'><\/div>\n<\/div>\n");

      // run widget script
      var app = $('.t2gwidget');
// if(widget_container.length > 0) {
//   app = widget_container.find('.t2gwidget');
// } else {
//   app = $('.t2gwidget');
// }
var current_phone_number = '';

//////////////////////////////////////////////////

function enable_loading(element) {
  element.data('loader_id', ('blanket_' + ($('.blanket .loading').size() + 1)));
  element.myBlanket('<div class="loading"><span class="text">Loading...</span></div>', {
    id_attr: element.data('loader_id')
  });
}

function disable_loading(element) {
  $('#' + element.data('loader_id')).remove();
}

function display_messages(msgs) {
  var msgs_element = app.find('.t2gwidget-right_col .t2gwidget-msgs-container');

  if(msgs_element.length > 0) {
    msgs_element.fadeOut(function() {
      msgs_element.html('');
      $.each(msgs, function(index, value) {
        msgs_element.append('<li>' + value + '</li>');
      });
      msgs_element.fadeIn();
    });
  } else {
    app.find('.t2gwidget-right_col').prepend($('<ul class="t2gwidget-msgs-container">'));
    display_messages(msgs);
  }
}

function display_message(msg) {
  display_messages([msg]);
}

function update_widget(html) {
  app.find('.t2gwidget-right_col').html(html);
}

function display_confirmation_screen() {
  $.jsonp({
    url: 'http://t2g-widget.mobilecause.com/campaigns/1745/donations/confirmation.js',
    callbackParameter: "callback",
    beforeSend: function(xOptions) {
      enable_loading(app);
    },
    error: function(xOptions, textStatus) {
      display_message("An error occurred while processing your request. Please try again shortly.");
    },
    success: function(json, textStatus) {
      update_widget(json.confirmation_html);
    },
    complete: function(XMLHttpRequest, textStatus) {
      disable_loading(app);
    }
  });
}

function accepted_donation_polling(donation_id) {
  var continue_polling = true;
  var check_donation_status = function() {
    if(continue_polling) {
      $.jsonp({
        url: 'https://text2give.mobilecause.com/api/v1.0/donations/' + donation_id + '.js',
        data: {campaign_id: '1408hvrI3tybP'},
        callbackParameter: "callback",
        error: function(xOptions, textStatus) {
          continue_polling = false;
          display_message("An error occurred while processing your request. Please try again shortly.");
        },
        success: function(json, textStatus) {
          if(json.donation.status == 'UserAccepted' || json.donation.status == 'BillingSent') {
            continue_polling = false;
            display_confirmation_screen();
          } else {
            continue_polling = true;
          }
        }
      });
    }
    setTimeout(check_donation_status, 10000);
  };

  // start polling to check for status of donation
  check_donation_status();

  $('a.button').click(function() {
    continue_polling = false;
  });
}

function donation_polling(phone_number) {
  var continue_polling = true;
  var check_for_donation = function() {
    if(continue_polling) {
      $.jsonp({
        url: 'https://text2give.mobilecause.com/api/v1.0/donations/latest_donation_id.js',
        data: {campaign_id: '1408hvrI3tybP', phone_number: phone_number}, // need phone number
        callbackParameter: "callback",
        error: function(xOptions, textStatus) {
          continue_polling = true;
        },
        success: function(json, textStatus) {
          continue_polling = false;
          accepted_donation_polling(json.donation_id);
        }
      });

      setTimeout(check_for_donation, 2000);
    }
  };

  // start polling to check for received donation
  check_for_donation();

  $('a.button').click(function() {
    continue_polling = false;
  });
}

//////////////////////////////////////////////////

app.find('form').livequery(function() {
  var form = $(this);
  var phone_number = form.find('input#t2g_donation_phone_number_for_campaign_1408hvrI3tybP');
  var opt_in_url = form.find('input#t2g_donation_opt_in_url_for_campaign_1408hvrI3tybP');

  // prefill some fields
  if(phone_number.val() == '') {
    phone_number.val(current_phone_number);
  }
  opt_in_url.val(document.URL);

  // ajaxify form
  form.submit(function() {
    $.jsonp({
      url: 'http://t2g-widget.mobilecause.com/campaigns/1408hvrI3tybP/donations/js_create.js',
      data: form.serialize(),
      callbackParameter: "callback",
      beforeSend: function(xOptions) {
        var pn = phone_number.val();
        var input_box = form.find('.input_box');
        var check_box = form.find('.check_box');
        var validation_errors = [];

        if(!(pn.length > 9 && pn.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/))) {
          validation_errors[validation_errors.length] = "Please enter a valid US phone number.";
          input_box.addClass('invalid');
        } else {
          input_box.removeClass('invalid');
        }

        if(form.find('input#agree_for_campaign_1408hvrI3tybP')[0].checked == false) {
          validation_errors[validation_errors.length] = "Please agree to the terms before proceeding.";
          check_box.addClass('invalid');
        } else {
          check_box.removeClass('invalid');
        }

        if(validation_errors.length > 0) {
          display_messages(validation_errors);
          return false;
        } else {
          enable_loading(app);
        }
      },
      error: function(xOptions, textStatus) {
        display_message("An error occurred while processing your request. Please check the phone number and/or try again shortly.");
      },
      success: function(json, textStatus) {
        current_phone_number = json.phone_number;
        update_widget(json.pending_confirmation_html);
        donation_polling(json.phone_number);
      },
      complete: function(XMLHttpRequest, textStatus) {
        disable_loading(app);
      }
    });

    return false;
  });
});

// These links are shown on the pending confirmation page.
app.find('a.t2gwidget-new_donation').livequery(function() {
  var link = $(this);
  link.click(function() {
    $.jsonp({
      url: 'http://t2g-widget.mobilecause.com/campaigns/1408hvrI3tybP/donations/new.js',
      callbackParameter: "callback",
      error: function(xOptions, textStatus) {
        display_message("An error occurred while processing your request. Please try again shortly.");
      },
      success: function(json, textStatus) {
        update_widget(json.donation_form);
      },
      complete: function(XMLHttpRequest, textStatus) {
        disable_loading(app);
      }
    });
    return false;
  });
});

/////////////////////////////////////////////////////////////////////////

app.find('a.terms_link_popup').livequery(function() {
  var link = $(this);
  link.click(function() {
    window.open(link.attr('href'), '_blank');
    return false;
  });
});



      // add stylesheet link
      var css_link = $("<link>", {
        rel: "stylesheet",
        type: "text/css",
        href: "http://t2g-widget.mobilecause.com/stylesheets/widget.css?1306524074"
      });
      css_link.appendTo('head');
    });
  }

})(); // We call our anonymous function immediately

