/*
The following functions are basic utility functions used by other scripts in
the vanilla set.
*/

// credit for next three: Kevin Hale
// http://particletree.com/features/javascript-basics-for-prototyping/

String.prototype.trim = function() {
    return this.replace( /^\s+|\s+$/, "" );
}

function addClassName( el, className ) {
    removeClassName( el, className );
    el.className = ( el.className + " " + className ).trim();
}

function removeClassName( el, className ) {
    el.className = el.className.replace( className, "" ).trim();
}

// credit: Don Brodale, Plus Three

function nab( id ) {
	if ( document.getElementById ) {
		return document.getElementById( id );
	} else if ( document.all ) {
		return document.all[ id ];
	} else {
		return null;
	}
}

// credit: Simon Willison
// http://simon.incutio.com/archive/2004/05/26/addLoadEvent

function addLoadEvent( func ) {
	var oldonload = window.onload;
	if ( typeof window.onload != 'function' ) {
		window.onload = func;
	} else {
		window.onload = function() {
			if ( oldonload ) oldonload(); // use conditional to IE7 happy
			func();
		}
	}
}

/*
This function is used primarily to support popup video windows.
*/

function popup( p, h, w ) {
	if ( p != null ) {
		var widgets = "toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,height=" + h + ", width=" + w;
		var popupWin = window.open( p, "popupWin", widgets );
	}
}

/*
This function was originally used to pass parameters from a stub form to a full form,
prefilling the values without having to trigger processing resulting in error messages.
*/

function getParams() {
	var query = decodeURI( location.search.substring( 1 ) );
	if ( !query.length ) return;
	var params = new Array();
	var pairs = query.split( '&' );
	for ( var i = 0; i < pairs.length; i++ ) {
		var nameVal = pairs[i].split( '=' );
		params[nameVal[0]] = decodeURIComponent( nameVal[1] );
	}
	return params;
}

/*
The following functions are for those clients who refuse to follow best practices
and insist that links open in a new window. By setting the class name of links to
"newwindow", we allow javascript to do the work and avoid deprecated target parameters.
*/

// credit: Roger Johansson
// http://www.456bereastreet.com/archive/200605/using_javascript_instead_of_target_to_open_new_windows/
// code has been modified

function openInNewWindow( e ) {
	var event;
	if ( !e ) {
		event = window.event;
	} else {
		event = e;
	}

	// Abort if a modifier key is pressed
	if ( event.shiftKey || event.altKey || event.ctrlKey || event.metaKey ) {
		return true;
	} else {
		// Change "_blank" to something like "newWindow" to load all links in the same new window
	    var newWindow = window.open( this.getAttribute('href'), '_blank' );
		if ( newWindow ) {
			if ( newWindow.focus ) {
				newWindow.focus();
			}
			return false;
		}
		return true;
	}
}

function getNewWindowLinks() {
	if ( !document.getElementsByTagName && !document.createElement ) return false;
	
	// Change this to the text you want to use to alert the user that a new window will be opened
	var strNewWindowAlert = " (opens in a new window)";

	// Find all links
	var links = document.getElementsByTagName( 'a' );
	for ( var i = 0; i < links.length; i++ ) {
		var link = links[i];
		if ( /\bnewwindow\b/.test(link.className) ) {
			// Create an em element containing the new window warning text
			var objWarningText = document.createElement( "em" );
			objWarningText.appendChild( document.createTextNode( strNewWindowAlert ) );
			link.appendChild( objWarningText );
			link.onclick = openInNewWindow;
		}
	}
}

addLoadEvent(getNewWindowLinks);

/* We might need to know if someone is logged in. cookie.js is routinely loaded in 
the body of page, so let's get a value ealier. */

function hasAuthCookie() {
	var pos = document.cookie.indexOf('auth_tkt=');
	if ( pos != -1 ) {
		return true;
	} else {
		return false;
	}
}

/* The following functions get, set, and delete cookies. They were first added to
support better splash-page handling. */

// credit: http://www.echoecho.com/jscookies02.htm
// code has been modified

function getCookie( name ) {
	if (document.cookie.length > 0) {
		var begin = document.cookie.indexOf( name + '=' );
		if ( begin != -1 ) {
			begin += name.length + 1;
			var end = document.cookie.indexOf( ";", begin );
			if (end == -1) end = document.cookie.length;
			return unescape( document.cookie.substring(begin, end) );
		}
	}
	return null;
}

function setCookie( name, value, expireDays, path ) {
	var expires = new Date ();
	expires.setTime( expires.getTime() + ( expireDays * 24 * 3600 * 1000 ) );
	document.cookie = name + "=" + escape( value ) +
	  ( ( expireDays == null ) ? "" : "; expires=" + expires.toGMTString() ) +
	  ( ( path == null ) ? "" : "; path=" + path );
}

function delCookie( name ) {
	if ( getCookie( name ) ) {
		document.cookie = name + "=" +
		  "; expires=Thu, 01-Jan-70 00:00:01 GMT";
	}
}

jQuery(document).ready(function($) {

    // fade out error message bg color
    $("#messages, #comment_errors, #comment_msgs").animate({opacity: 1.0}, 3000).animate({backgroundColor: '#ffffff'}, 3000);


    // share bookmarks on thankyou pages
    vanilla.baseUrl = location.href.split('?', 1);
    $(".thankyoubookmarks").bookmark({
        icons: "/images/bookmarks.png",
        url: vanilla.baseUrl,
        sites: ["delicious", "digg", "facebook", "fark", "google", "kaboodle", "mixx", "propeller", "reddit", "stumbleupon", "technorati", "twitthis", "yahoobuzz"]
    });
    $(".thankyoubookmarks").prepend('<p><strong>Share this with your friends:</strong></p>');
    
    // share bookmarks in general
    $(".bookmarks").bookmark({
        icons: "/images/bookmarks.png",
        sites: ["delicious", "digg", "facebook", "fark", "google", "kaboodle", "mixx", "propeller", "reddit", "stumbleupon", "technorati", "twitthis", "yahoobuzz"]
    });
    $(".bookmarks ul").prepend('<li class="share">Share &#160;</li>');
    
    // opacity effect for bookmarks
    $(".hasBookmark ul a").css("opacity", ".6");
    $(".hasBookmark ul a").hover(
        function() {
            $(this).css("opacity", "1");
        },
        function() {
            $(this).css("opacity", ".6");
        }
    );

    // handlers for fields in signup stub form
    $("#signup_box_email, #signup_box_zip").focus(function() {
        vanilla.swapValue(this, false);
    });
    $("#signup_box_email, #signup_box_zip").blur(function() {
        vanilla.swapValue(this, true);
    });

    // twitter feed
    $('#sidebar .feed').twitterFeed({
        queryType: 'user',
        query: 'nukes_of_hazard',
        template: '<div class="txt"><span class="msg">#{text}</span><br /><span class="footer"><span class="date">#{createdAt}</span> (<a  href="http://twitter.com/home?status=%40#{screenName}%20&in_reply_to_status_id=#{id}&in_reply_to=#{screenName}">Reply</a>) (<a  href="http://twitter.com/home?status=RT%20%40#{screenName}%20#{encodedText}&in_reply_to_status_id=#{id}&in_reply_to=#{screenName}">RT</a>)</span></div>',
        refresh: 0,
        count: 2,
        fadeSpeed: 0,
        timeFormat: 'local'
    });
});

// CF thermometer
vanilla.addLoadEvent(function() {
    if (typeof vanilla.cf_data == 'undefined') {
        return;
    }
    
    // we delay this a bit so the user will see the entire effect
    setTimeout(function() {
        jQuery('#cf_progress #goal').html('$' + vanilla.format_number(vanilla.cf_data.goal));
        jQuery('#cf_progress #count').html(vanilla.cf_data.count + ((vanilla.cf_data.count == 1) ? ' donor' : ' donors'));
        jQuery('#cf_progress #average').html('$' + vanilla.format_number((vanilla.cf_data.raised/20).toFixed(2)));

        jQuery("#cf_progress").progressBar({
            value    : Math.round(vanilla.cf_data.raised * 100 / vanilla.cf_data.goal),
            height   : 190,
            width    : 32,
            callback : function(config) {
                var raised = 0;
                if (config.value > 0) {
                    raised = vanilla.format_number((vanilla.cf_data.raised * (config.runningValue / config.value)).toFixed(2));
                    raised = raised.replace('.00', '');
                }
                jQuery('#cf_progress #raised').html('$' + raised);
                
                if (config.runningValue == config.max) {
                    jQuery('#cf_progress').addClass('goal_reached');
                    jQuery('#cf_progress #scale').hide();
                }
                if (config.runningValue > config.max) {
                    jQuery('#cf_progress').addClass('goal_exceeded');
                    jQuery('#cf_progress #scale').hide();
                }
            }
        });
    }, 500);
});


