// This file is included by all pages.

// Evil globals
var HIGHLIGHT_COLOR = "#FC3";

// Preload images.
jQuery.preloadImages = function()
{
  for(var i = 0; i<arguments.length; i++){
    jQuery("<img>").attr("src", arguments[i]);
  }
}

$(function(){
	jQuery.preloadImages('/img/busy_big.gif', '/img/busy.gif');
	
	// IE6 is really acting up in the left sidebar. For some reason,
	// the first LI with a hyperlink refuses to accept a background
	// color and if one gets set (on rollover or because it's selected)
	// it causes other LI elements to get funky (borders disappear on
	// some, icons disappear on all).
	//
	// The only effective workaround I've found is to put a fake item
	// at the top of the list. By moving it offscreen, we can eliminate
	// the odd rollover effect when the user mouses around, but it's
	// still in the tabbing order, and I can't seem to get it to take 
	// up less vertical space. Floating or absolute positioning solves 
	// the spacing problem but removes the cure.
	//
	// For now, IE6 users will just have to live with a navbar that's
	// a bit lower than it should be.
	
	if ($.browser.msie && parseInt($.browser.version.substr(0,1)) <= 6) {
		$("#leftCol ul").prepend('<li style="position:relative; left:-10000px; height:1px; width:1px; overflow:hidden;"><a href="/alerts/" tabindex="0" style=""><span class="itemcount"></span></a></li>');
	}	
});


// Generate a unique (for life of script) ID 
var uniqId = (function(){
	var id=0;
	return function(){
		return id++ ;
	};
})();

function in_array(needle, haystack, strict) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
 
    var found = false;
	var key;
	
	// Convert to true boolean
	strict = !!strict;
 
    for (key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
            found = true;
            break;
        }
    } 
    return found;
}

function number_format( number, decimals, dec_point, thousands_sep ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // *     example 1: number_format(1234.5678, 2, '.', '');
    // *     returns 1: 1234.57     
 
    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? "." : dec_point;
    var t = thousands_sep == undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

function date ( format, timestamp ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
    // +      parts by: Peter-Paul Koch (http://www.quirksmode.org/js/beat.html)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: MeEtc (http://yass.meetcweb.com)
    // +   improved by: Brad Touesnard
    // +   improved by: Tim Wiel
    // *     example 1: date('H:m:s \\m \\i\\s \\m\\o\\n\\t\\h', 1062402400);
    // *     returns 1: '09:09:40 m is month'
    // *     example 2: date('F j, Y, g:i a', 1062462400);
    // *     returns 2: 'September 2, 2003, 2:26 am'
 
    var a, jsdate=((timestamp) ? new Date(timestamp*1000) : new Date());
    var pad = function(n, c){
        if( (n = n + "").length < c ) {
            return new Array(++c - n.length).join("0") + n;
        } else {
            return n;
        }
    };
    var txt_weekdays = ["Sunday","Monday","Tuesday","Wednesday",
        "Thursday","Friday","Saturday"];
    var txt_ordin = {1:"st",2:"nd",3:"rd",21:"st",22:"nd",23:"rd",31:"st"};
    var txt_months =  ["", "January", "February", "March", "April",
        "May", "June", "July", "August", "September", "October", "November",
        "December"];
 
    var f = {
        // Day
            d: function(){
                return pad(f.j(), 2);
            },
            D: function(){
                t = f.l(); return t.substr(0,3);
            },
            j: function(){
                return jsdate.getDate();
            },
            l: function(){
                return txt_weekdays[f.w()];
            },
            N: function(){
                return f.w() + 1;
            },
            S: function(){
                return txt_ordin[f.j()] ? txt_ordin[f.j()] : 'th';
            },
            w: function(){
                return jsdate.getDay();
            },
            z: function(){
                return (jsdate - new Date(jsdate.getFullYear() + "/1/1")) / 864e5 >> 0;
            },
 
        // Week
            W: function(){
                var a = f.z(), b = 364 + f.L() - a;
                var nd2, nd = (new Date(jsdate.getFullYear() + "/1/1").getDay() || 7) - 1;
 
                if(b <= 2 && ((jsdate.getDay() || 7) - 1) <= 2 - b){
                    return 1;
                } else{
 
                    if(a <= 2 && nd >= 4 && a >= (6 - nd)){
                        nd2 = new Date(jsdate.getFullYear() - 1 + "/12/31");
                        return date("W", Math.round(nd2.getTime()/1000));
                    } else{
                        return (1 + (nd <= 3 ? ((a + nd) / 7) : (a - (7 - nd)) / 7) >> 0);
                    }
                }
            },
 
        // Month
            F: function(){
                return txt_months[f.n()];
            },
            m: function(){
                return pad(f.n(), 2);
            },
            M: function(){
                t = f.F(); return t.substr(0,3);
            },
            n: function(){
                return jsdate.getMonth() + 1;
            },
            t: function(){
                var n;
                if( (n = jsdate.getMonth() + 1) == 2 ){
                    return 28 + f.L();
                } else{
                    if( n & 1 && n < 8 || !(n & 1) && n > 7 ){
                        return 31;
                    } else{
                        return 30;
                    }
                }
            },
 
        // Year
            L: function(){
                var y = f.Y();
                return (!(y & 3) && (y % 1e2 || !(y % 4e2))) ? 1 : 0;
            },
            //o not supported yet
            Y: function(){
                return jsdate.getFullYear();
            },
            y: function(){
                return (jsdate.getFullYear() + "").slice(2);
            },
 
        // Time
            a: function(){
                return jsdate.getHours() > 11 ? "pm" : "am";
            },
            A: function(){
                return f.a().toUpperCase();
            },
            B: function(){
                // peter paul koch:
                var off = (jsdate.getTimezoneOffset() + 60)*60;
                var theSeconds = (jsdate.getHours() * 3600) +
                                 (jsdate.getMinutes() * 60) +
                                  jsdate.getSeconds() + off;
                var beat = Math.floor(theSeconds/86.4);
                if (beat > 1000) beat -= 1000;
                if (beat < 0) beat += 1000;
                if ((String(beat)).length == 1) beat = "00"+beat;
                if ((String(beat)).length == 2) beat = "0"+beat;
                return beat;
            },
            g: function(){
                return jsdate.getHours() % 12 || 12;
            },
            G: function(){
                return jsdate.getHours();
            },
            h: function(){
                return pad(f.g(), 2);
            },
            H: function(){
                return pad(jsdate.getHours(), 2);
            },
            i: function(){
                return pad(jsdate.getMinutes(), 2);
            },
            s: function(){
                return pad(jsdate.getSeconds(), 2);
            },
            //u not supported yet
 
        // Timezone
            //e not supported yet
            //I not supported yet
            O: function(){
               var t = pad(Math.abs(jsdate.getTimezoneOffset()/60*100), 4);
               if (jsdate.getTimezoneOffset() > 0) t = "-" + t; else t = "+" + t;
               return t;
            },
            P: function(){
                var O = f.O();
                return (O.substr(0, 3) + ":" + O.substr(3, 2));
            },
            //T not supported yet
            //Z not supported yet
 
        // Full Date/Time
            c: function(){
                return f.Y() + "-" + f.m() + "-" + f.d() + "T" + f.h() + ":" + f.i() + ":" + f.s() + f.P();
            },
            //r not supported yet
            U: function(){
                return Math.round(jsdate.getTime()/1000);
            }
    };
 
    return format.replace(/[\\]?([a-zA-Z])/g, function(t, s){
        if( t!=s ){
            // escaped
            ret = s;
        } else if( f[s] ){
            // a date function exists
            ret = f[s]();
        } else{
            // nothing special
            ret = s;
        }
 
        return ret;
    });
}

function consoleLog() {
	console.log(arguments);
}

// TODO: make a plugin
function positionDialog(dlg,bAdjustHoriz) {
	var w = $(window);
	var dlgSize = {
		h: dlg.outerHeight(),
		w: dlg.outerWidth()
	};
	var vwSize = {
		h: w.height(),
		w: w.width()
	};
	var pos = {
		x: Math.round((vwSize.w - dlgSize.w) / 2) + w.scrollLeft(),
		y: Math.round((vwSize.h - dlgSize.h) / 4) + w.scrollTop()
	};
	// Currently we only adjust top
	dlg.css({
		top: pos.y
	});
	if (bAdjustHoriz) {
		dlg.css({
			left: pos.x
		});
	}
}



// BOO-YEAH, my first jQuery plug-in!
// Core provides attr(name), which gets the named attribute
// from the first matched element. What if you want you to
// get an array of that attribute's values from ALL matched
// elements? That's what multiAttr does.
(function($){
	$.fn.multiAttr = function(name, options) {	
		var a = [];
	 	this.each(function() {
		    a.push(this.getAttribute(name));
		});
		return a;
	}
})(jQuery);

// My second jQuery plug-in
(function($){
	$.fn.toggleFocusBlur = function(options) {
		
		var defaults = {
			prompt: '',
			promptColor: '#CCC',
			foreground: '#000',
			background: '#FFF',
			overwriteExisting: false
  		}
		var opts = $.extend(defaults, options);
		
	 	return this.each(function() {
			$this = $(this);
			$this.unbind('focus')
				.focus(function(){
				if ($this.val() == opts.prompt) {
					$this.val("");
				}
				$this.css("color", opts.foreground);
				$this.css("backgroundColor", opts.background);
			}).unbind('blur')
				.blur(function(){
				$this.css("backgroundColor", "");
				if ($this.val() === "" || $this.val() == opts.prompt) {
					$this.css("color", opts.promptColor);
					$this.val(opts.prompt);
				}
				else {
					$this.css("color", opts.foreground);
				}
			});
			if (opts.overwriteExisting || $this.val() == "") {
				$this.val(opts.prompt).css("color",opts.promptColor);
			}
		});
	}
})(jQuery);


// Common JS for all subscriber pages

// Header
$(function(){
	$(document).keydown( function(e) {
	   if (e.which == 27) {  // escape, close box
	   		$("div.jqmWindow").jqmHide();
	   }
	 });

	$("#mainTabs li").bind("mouseenter", function(evt) {
		var $this = $(this);
		if (!$this.hasClass("selected")) {
			$this.addClass("selected2");
		}
	}).bind("mouseleave", function(evt) {
		$(this).removeClass("selected2");
	});
	
	$("#lnkHeaderFeedback").click(sendFeedback);
	$("#lnkInviteEmail").click(inviteEmail);
	$("#lnkShareFeed1").click(showMegaTracklet);
	$("#lnkShowAutoInviteLink").click(showAutoInviteLink);
	$("#lnkReferralInfo").click(referralinfo);

});

$(function() {
	// Using each as an 'if' and containing stuff inside a private namespace.
	$('#recentActivity').each(function() {
		var $this = $(this);
		
		var totalHeight = $this.height();

			// Set up the rotator.
			var currentHeadline = 0, oldHeadline = 0;
			var hiddenPosition = totalHeight   + 10;
			$('div.streamItem:eq(' + currentHeadline + ')').css('top','2px');
			var headlineCount = $('div.streamItem').length;
			var headlineTimeout;
			var rotateInProgress = false;
			
			// Rotator function.
			var headlineRotate = function() {
				if (!rotateInProgress) {
					rotateInProgress = true;
					headlineTimeout = false;
					
					currentHeadline = (oldHeadline + 1) % headlineCount;
					$('div.streamItem:eq(' + oldHeadline + ')')
					.animate({top: -hiddenPosition}, 'slow', function() {
						$(this).css('top',hiddenPosition);
					});
					$('div.streamItem:eq(' + currentHeadline + ')')
					.animate({top: '2px'},'slow', function() {
						rotateInProgress = false;
						if (!headlineTimeout) {
							headlineTimeout = setTimeout(headlineRotate, 5000);
						}
					});
					oldHeadline = currentHeadline;
				}
			};
			headlineTimeout = setTimeout(headlineRotate,5000);
			
			// On hover, clear the timeout and reset headlineTimeout to 0.
			$('#recentActivity').hover(function() {
					clearTimeout(headlineTimeout);
					headlineTimeout = false;
				}, function() {
				// Start the rotation soon when the mouse leaves.
				if (!headlineTimeout) {
					headlineTimeout = setTimeout(headlineRotate, 250);
				}
			}); //end .hover()
	//	}); // end $.get()
	}); //end .each() for #news-feed
});


// Footer
$(function(){
	$("#lnkFeedback").click(sendFeedback);
	$("#lnkHeaderFeedback").click(sendFeedback);
});

function sendFeedback(evt){
	var dlg = $('<div id="dlgFeedback" class="jqmWindow"><img src="/img/busy_big.gif" alt="Loading..."></div>');
	dlg.jqm({
		overlay:50, 
		toTop:true, 
		ajax:"/about/feedback/",
		
		// When Ajax content is loaded and before window is shown
		onLoad: function(o) {
			
			var dlg = o.w;

			// Cancel button
			dlg.find("div.hd a.btnCancel").click(function(){dlg.jqmHide();return false;});

			dlg.draggable({
				handle:dlg.find("div.hd"),
				containment:'document'
			});

			dlg.find("form").ajaxForm({
				dataType: "json",
				success: function (ajaxResponse) {
					if (ajaxResponse.success) {
						$("#dlgFeedback").html("<p style='padding:1em'>Thanks for your feedback!</p>");
						setTimeout(function(){
							$("#dlgFeedback").fadeOut().jqmHide();
						},3000);
					}
					else {
						
					}
				}
			});
		},

		// Show the dialog
		onShow:function(o){ 
			o.w.show(); 
			positionDialog(o.w);
		},

		// Hide the dialog and remove from the DOM
		onHide:function(o) { 
			o.w.remove(); 
			o.o.fadeOut('500', function() { 
				if (o.o) {
					o.o.remove();
				} 
			});
		}

	}).jqmShow();

	return false;
}

function inviteEmail(evt){
	var dlg = $('<div id="dlgInviteEmail" class="jqmWindow"><img src="/img/busy_big.gif" alt="Loading..."></div>');

	dlg.jqm({
		overlay:50, 
		toTop:true, 
		ajax:"/invite/friends",
		
		// When Ajax content is loaded and before window is shown
		onLoad: function(o) {
			
			var dlg = o.w;

			// Cancel button
			dlg.find("div.hd a.btnCancel").click(function(){dlg.jqmHide();return false;});

			dlg.draggable({
				handle:dlg.find("div.hd"),
				containment:'document'
			});
		},

		// Show the dialog
		onShow:function(o){ 
			o.w.show(); 
			positionDialog(o.w);
		},

		// Hide the dialog and remove from the DOM
		onHide:function(o) { 
			o.w.remove(); 
			o.o.fadeOut('500', function() { 
				if (o.o) {
					o.o.remove();
				} 
			});
		}

	}).jqmShow();

	return false;
}

function showAutoInviteLink(evt){
	var dlg = $('<div id="dlgShowAutoInviteLink" class="jqmWindow"><img src="/img/busy_big.gif" alt="Loading..."></div>');

	dlg.jqm({
		overlay:50, 
		toTop:true, 
		ajax:"/invite/geturl",
		
		// When Ajax content is loaded and before window is shown
		onLoad: function(o) {
			
			var dlg = o.w;

			// Cancel button
			dlg.find("div.hd a.btnCancel").click(function(){dlg.jqmHide();return false;});

			dlg.draggable({
				handle:dlg.find("div.hd"),
				containment:'document'
			});
		},

		// Show the dialog
		onShow:function(o){ 
			o.w.show(); 
			positionDialog(o.w);
		},

		// Hide the dialog and remove from the DOM
		onHide:function(o) { 
			o.w.remove(); 
			o.o.fadeOut('500', function() { 
				if (o.o) {
					o.o.remove();
				} 
			});
		}

	}).jqmShow();

	return false;
}
function showMegaTracklet(evt){
       var dlg = $('<div id="dlgNewsLetter" class="jqmWindow" style="margin-left:-470px;margin-top:-130px;width:950px;"></div>');
	//$("body").append(dlg);
	dlg.jqm({
                overlay:60,
                toTop:true,
               	ajax:"/subscription/news-letter",
			ajaxText:'<img src="/img/busy_big.gif" alt="Loading...">',
                // When Ajax content is loaded and before window is shown
                onLoad: function(o) {

                        var dlg = o.w;

                        // Cancel button
                        dlg.find("div.hd a.btnCancel").click(function(){dlg.jqmHide();return false;});

                        dlg.draggable({
                                handle:dlg.find("div.hd"),
                                containment:'document'
                        });
                },
		

                // Show the dialog
                onShow:function(o){
                        o.w.show();
                        positionDialog(o.w);
                },

                // Hide the dialog and remove from the DOM
                onHide:function(o) {
                        o.w.remove();
                        o.o.fadeOut('500', function() {
                                if (o.o) {
                                        o.o.remove();
                                }
                        });
                }

        }).jqmShow();

        return false;
}
function referralinfo(evt){
        var dlg = $('<div id="dlgReferralInfo" class="jqmWindow"><img src="/img/busy_big.gif" alt="Loading..."></div>');

        dlg.jqm({
                overlay:80,
                toTop:true,
                ajax:"/about/referralinfo/",

                // When Ajax content is loaded and before window is shown
                onLoad: function(o) {

                        var dlg = o.w;

                        // Cancel button
                        dlg.find("div.hd a.btnCancel").click(function(){dlg.jqmHide();return false;});

                        dlg.draggable({
                                handle:dlg.find("div.hd"),
                                containment:'document'
                        });
                },

                // Show the dialog
                onShow:function(o){
                        o.w.show();
                        positionDialog(o.w);
                },

                // Hide the dialog and remove from the DOM
                onHide:function(o) {
                        o.w.remove();
                        o.o.fadeOut('500', function() {
                                if (o.o) {
                                        o.o.remove();
                                }
                        });
                }

        }).jqmShow();

        return false;
}

