/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
/*
 * jqModal - Minimalist Modaling with jQuery
 *   (http://dev.iceburg.net/jquery/jqModal/)
 *
 * Copyright (c) 2007,2008 Brice Burgess <bhb@iceburg.net>
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 * 
 * $Version: 03/01/2009 +r14
 */
(function ($) {
    $.fn.jqm = function (o) {
        var p = {
            overlay: 50,
            overlayClass: 'jqmOverlay',
            closeClass: 'jqmClose',
            trigger: '.jqModal',
            ajax: F,
            ajaxText: '',
            target: F,
            modal: F,
            toTop: F,
            onShow: F,
            onHide: F,
            onLoad: F
        };
        return this.each(function () {
            if (this._jqm) return H[this._jqm].c = $.extend({
},
            H[this._jqm].c, o);
            s++;
            this._jqm = s;
            H[s] = {
                c: $.extend(p, $.jqm.params, o),
                a: F,
                w: $(this).addClass('jqmID' + s),
                s: s
            };
            if (p.trigger) $(this).jqmAddTrigger(p.trigger);
        });
    };

    $.fn.jqmAddClose = function (e) {
        return hs(this, e, 'jqmHide');
    };
    $.fn.jqmAddTrigger = function (e) {
        return hs(this, e, 'jqmShow');
    };
    $.fn.jqmShow = function (t) {
        return this.each(function () {
            t = t || window.event;
            $.jqm.open(this._jqm, t);
        });
    };
    $.fn.jqmHide = function (t) {
        return this.each(function () {
            t = t || window.event;
            $.jqm.close(this._jqm, t)
        });
    };

    $.jqm = {
        hash: {
},
        open: function (s, t) {
            var h = H[s],
                c = h.c,
                cc = '.' + c.closeClass,
                z = (parseInt(h.w.css('z-index'))),
                z = (z > 0) ? z : 3000,
            o = $('<div></div>').css({
                height: '100%',
                width: '100%',
                position: 'fixed',
                left: 0,
                top: 0,
                'z-index': z - 1,
                opacity: c.overlay / 100
            });
            if (h.a) return F;
            h.t = t;
            h.a = true;
            h.w.css('z-index', z);
            if (c.modal) {
                if (!A[0]) L('bind');
                A.push(s);
            } else if (c.overlay > 0) h.w.jqmAddClose(o);
            else o = F;

            h.o = (o) ? o.addClass(c.overlayClass).prependTo('body') : F;
            if (ie6) {
                $('html,body').css({
                    height: '100%',
                    width: '100%'
                });
                if (o) {
                    o = o.css({
                        position: 'absolute'
                    })[0];
                    for (var y in {
                        Top: 1,
                        Left: 1
                    }) o.style.setExpression(y.toLowerCase(), "(_=(document.documentElement.scroll" + y + " || document.body.scroll" + y + "))+'px'");
                }
            }

            if (c.ajax) {
                var r = c.target || h.w,
                    u = c.ajax,
                    r = (typeof r == 'string') ? $(r, h.w) : $(r),
                u = (u.substr(0, 1) == '@') ? $(t).attr(u.substring(1)) : u;
                r.html(c.ajaxText).load(u, function () {
                    if (c.onLoad) c.onLoad.call(this, h);
                    if (cc) h.w.jqmAddClose($(cc, h.w));
                    e(h);
                });
            } else if (cc) h.w.jqmAddClose($(cc, h.w));

            if (c.toTop && h.o) h.w.before('<span id="jqmP' + h.w[0]._jqm + '"></span>').insertAfter(h.o);
            (c.onShow) ? c.onShow(h) : h.w.show();
            e(h);
            return F;
        },
        close: function (s) {
            var h = H[s];
            if (!h.a) return F;
            h.a = F;
            if (A[0]) {
                A.pop();
                if (!A[0]) L('unbind');
            }
            if (h.c.toTop && h.o) $('#jqmP' + h.w[0]._jqm).after(h.w).remove();
            if (h.c.onHide) h.c.onHide(h);
            else {
                h.w.hide();
                if (h.o) h.o.remove();
            }
            return F;
        },
        params: {
}
    };
    var s = 0,
        H = $.jqm.hash,
        A = [],
        ie6 = $.browser.msie && ($.browser.version == "6.0"),
        F = false,
        i = $('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({
        opacity: 0
    }),
        f = function (h) {
        },
        e = function (h) {
        if (ie6) if (h.o) h.o.html('<p style="width:100%;height:100%"/>').prepend(i);
        else if (!$('iframe.jqm', h.w)[0]) h.w.prepend(i);
        f(h);
    },
        L = function (t) {
        $()[t]("keypress", m)[t]("keydown", m)[t]("mousedown", m);
    },
        m = function (e) {
        var h = H[A[A.length - 1]],
            r = (!$(e.target).parents('.jqmID' + h.s)[0]);
        if (r) f(h);
        return !r;
    },
        hs = function (w, t, c) {
        return w.each(function () {
            var s = this._jqm;
            $(t).each(function () {
                if (!this[c]) {
                    this[c] = [];
                    $(this).click(function () {
                        for (var i in {
                            jqmShow: 1,
                            jqmHide: 1
                        }) for (var s in this[i]) if (H[this[i][s]]) H[this[i][s]].w[i](this);
                        return F;
                    });
                }
                this[c].push(s);
            });
        });
    };
})(jQuery);

(function($) {
 
  $.fn.tweet = function(o){
    var s = {
      username: ["RobinCarnahan"],              // [string]   required, unless you want to display our tweets. :) it can be an array, just do ["username1","username2","etc"]
      list: null,                              //[string]   optional name of list belonging to username
      avatar_size: null,                      // [integer]  height and width of avatar if displayed (48px max)
      count: 1,                               // [integer]  how many tweets to display?
      intro_text: null,                       // [string]   do you want text BEFORE your your tweets?
      outro_text: null,                       // [string]   do you want text AFTER your tweets?
      join_text:  null,                       // [string]   optional text in between date and tweet, try setting to "auto"
      auto_join_text_default: "i said,",      // [string]   auto text for non verb: "i said" bullocks
      auto_join_text_ed: "i",                 // [string]   auto text for past tense: "i" surfed
      auto_join_text_ing: "i am",             // [string]   auto tense for present tense: "i was" surfing
      auto_join_text_reply: "i replied to",   // [string]   auto tense for replies: "i replied to" @someone "with"
      auto_join_text_url: "i was looking at", // [string]   auto tense for urls: "i was looking at" http:...
      loading_text: null,                     // [string]   optional loading text, displayed while tweets load
      query: null                             // [string]   optional search query
    };
    
    if(o) $.extend(s, o);
    
    $.fn.extend({
      linkUrl: function() {
        var returning = [];
        var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
        this.each(function() {
          returning.push(this.replace(regexp,"<a href=\"$1\">$1</a>"));
        });
        return $(returning);
      },
      linkUser: function() {
        var returning = [];
        var regexp = /[\@]+([A-Za-z0-9-_]+)/gi;
        this.each(function() {
          returning.push(this.replace(regexp,"<a href=\"http://twitter.com/$1\">@$1</a>"));
        });
        return $(returning);
      },
      linkHash: function() {
        var returning = [];
        var regexp = / [\#]+([A-Za-z0-9-_]+)/gi;
        this.each(function() {
          returning.push(this.replace(regexp, ' <a href="http://search.twitter.com/search?q=&tag=$1&lang=all&from='+s.username.join("%2BOR%2B")+'">#$1</a>'));
        });
        return $(returning);
      },
      capAwesome: function() {
        var returning = [];
        this.each(function() {
          returning.push(this.replace(/\b(awesome)\b/gi, '<span class="awesome">$1</span>'));
        });
        return $(returning);
      },
      capEpic: function() {
        var returning = [];
        this.each(function() {
          returning.push(this.replace(/\b(epic)\b/gi, '<span class="epic">$1</span>'));
        });
        return $(returning);
      },
      makeHeart: function() {
        var returning = [];
        this.each(function() {
          returning.push(this.replace(/(&lt;)+[3]/gi, "<tt class='heart'>&#x2665;</tt>"));
        });
        return $(returning);
      }
    });

    function parse_date(date_str) {
      // The non-search twitter APIs return inconsistently-formatted dates, which Date.parse
      // cannot handle in IE. We therefore perform the following transformation:
      // "Wed Apr 29 08:53:31 +0000 2009" => "Wed, Apr 29 2009 08:53:31 +0000"
      return Date.parse(date_str.replace(/^([a-z]{3})( [a-z]{3} \d\d?)(.*)( \d{4})$/i, '$1,$2$4$3'));
    }

    function relative_time(time_value) {
      var parsed_date = parse_date(time_value);
      var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
      var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
      var pluralize = function (singular, n) {
        return '' + n + ' ' + singular + (n == 1 ? '' : 's');
      };
      if(delta < 60) {
      return 'less than a minute ago';
      } else if(delta < (60*60)) {
      return 'about ' + pluralize("minute", parseInt(delta / 60)) + ' ago';
      } else if(delta < (24*60*60)) {
      return 'about ' + pluralize("hour", parseInt(delta / 3600)) + ' ago';
      } else {
      return 'about ' + pluralize("day", parseInt(delta / 86400)) + ' ago';
      }
    }

    function build_url() {
      var proto = ('https:' == document.location.protocol ? 'https:' : 'http:');
      if (s.list) {
        return proto+"//api.twitter.com/1/"+s.username[0]+"/lists/"+s.list+"/statuses.json?per_page="+s.count+"&callback=?";
      } else if (s.query == null && s.username.length == 1) {
        return proto+'//api.twitter.com/1/statuses/user_timeline.json?screen_name='+s.username[0]+'&count='+s.count+'&callback=?';
      } else {
        var query = (s.query || 'from:'+s.username.join(' OR from:'));
        return proto+'//search.twitter.com/search.json?&q='+escape(query)+'&rpp='+s.count+'&callback=?';
      }
    }

    return this.each(function(i, widget){
      var list = $('<ul class="tweet_list">').appendTo(widget);
      var intro = '<p class="tweet_intro">'+s.intro_text+'</p>';
      var outro = '<p class="tweet_outro">'+s.outro_text+'</p>';
      var loading = $('<p class="loading">'+s.loading_text+'</p>');

      if(typeof(s.username) == "string"){
        s.username = [s.username];
      }

      if (s.loading_text) $(widget).append(loading);
      $.getJSON(build_url(), function(data){
        if (s.loading_text) loading.remove();
        var tweets = (data.results || data);
        $.each(tweets, function(i,item){
          // auto join text based on verb tense and content
          if (s.join_text == "auto") {
            if (item.text.match(/^(@([A-Za-z0-9-_]+)) .*/i)) {
              var join_text = s.auto_join_text_reply;
            } else if (item.text.match(/(^\w+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+) .*/i)) {
              var join_text = s.auto_join_text_url;
            } else if (item.text.match(/^((\w+ed)|just) .*/im)) {
              var join_text = s.auto_join_text_ed;
            } else if (item.text.match(/^(\w*ing) .*/i)) {
              var join_text = s.auto_join_text_ing;
            } else {
              var join_text = s.auto_join_text_default;
            }
          } else {
            var join_text = s.join_text;
          };

          var from_user = item.from_user || item.user.screen_name;
          var join_template = '<span class="tweet_join"> '+join_text+' </span>';
          var join = ((s.join_text) ? join_template : ' ');
          var text = '<span class="tweet_text">' +$([item.text]).linkUrl().linkUser().linkHash().makeHeart().capAwesome().capEpic()[0]+ '</span>';

          // until we create a template option, arrange the items below to alter a tweet's display.
          list.append('<li>' + join + text + '</li>');

          list.children('li:first').addClass('tweet_first');
          list.children('li:odd').addClass('tweet_even');
          list.children('li:even').addClass('tweet_odd');
        });
        if (s.outro_text) list.after(outro);
        $(widget).trigger("loaded").trigger((tweets.length == 0 ? "empty" : "full"));
      });

    });
  };
})(jQuery);

jQuery(document).ready(function () {
	jQuery('ul#menu').superfish({ 
		delay: 0
	});
	
	jQuery('a#showPrivacy').attr('href', 'javascript:void(0);');
	jQuery('#privacyModal').jqm({
		modal: true,
		trigger: 'a#showPrivacy'
	});
	
	jQuery('a#showContact').attr('href', 'javascript:void(0);');
	jQuery('#contactModal').jqm({
		modal: true,
		trigger: 'a#showContact'
	});
	
	if(jQuery('form.sideFeature').attr('id')=='sidefeatureSignupForm') {
		jQuery('form.sideFeature').find('input').focus(function() {
			if(jQuery(this).val()==jQuery(this).attr('class')) {
				jQuery(this).val('');
			}
		});
		jQuery('form.sideFeature').find('input').blur(function() {
			if(jQuery(this).val()=='' && jQuery(this).attr('class')!=='undefined') {
				jQuery(this).val(jQuery(this).attr('class'));
			}
		});
	}
	if(jQuery('#revmsg-form').attr('id')!='undefined') {
		var url = jQuery('#revmsg-form').attr('action')+'/false/phone:';
		jQuery('#revmsg-form').attr('action', 'javascript:void(0);');
		jQuery('#revmsg-form').submit(function() {
			jQuery('#revmsg-form').css('display', 'none');
			jQuery('#revmsg-loading').css('display', 'block');
			var final_url = url+encodeURIComponent(jQuery('#revmsg-phone-number').attr('value'))+'/?jsoncallback=?';
			jQuery.getJSON(final_url, function(error) {
				if(error) {revmsg_failure();} else {revmsg_success();}
			});
		});
	}
	if(jQuery('#tweet').attr('id')!='undefined') {
		$("#tweet").tweet({
			join_text: "auto",
			avatar_size: 32,
			count: 1,
			auto_join_text_default: "",
			auto_join_text_ed: "",
			auto_join_text_ing: "",
			auto_join_text_reply: "replied to",
			auto_join_text_url: "checking out",
			loading_text: "loading tweets..."
		});
	}
});

function revmsg_success() {
     jQuery('#revmsg-loading').css('display', 'none');
     jQuery('#revmsg-success').css('display', 'block');
}
 
function revmsg_failure() {
     jQuery('#revmsg-loading').css('display', 'none');
     jQuery('#revmsg-form').css('display', 'block');
     jQuery('.revmsg-input input').css('border', '1px solid #f00');
     alert('Sorry, but there was a problem registering your phone number, please try again.');
}
