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

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

var vanilla = {

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

	/* credit: Stephen Chapman (modified)
	   http://javascript.about.com/library/bldom08.htm */

	getElementsByClassName : function( clName ) {
		var elements = [];
		var pattern = new RegExp("\\b" + clName + "\\b");
		var els = document.getElementsByTagName('*');
		for (var i = 0; i < els.length; i++) {
			var classes = els[i].className;
			if ( pattern.test( classes ) ) elements.push( els[i] );
		}
		return elements;
	},

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

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

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

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

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

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

	popup : function( 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. */

	getParams : function() {
		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 two 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 attributes.

	   credit: Roger Johansson (modified)
	   http://www.456bereastreet.com/archive/200605/using_javascript_instead_of_target_to_open_new_windows/ */

	openInNewWindow : function( 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;
		}
	},

	getNewWindowLinks : function() {
		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 = vanilla.openInNewWindow;
			}
		}
	},

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

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

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

	   credit: http://www.echoecho.com/jscookies02.htm (modified) */

	getCookie : function( 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;
	},

	setCookie : function( name, value, expireDays, path, domain ) {
		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 ) +
			( ( domain == null ) ? "" : "; domain=" + domain );
	},

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


	/* This function enables IE Win to do state change on hover like better browsers.
	   It is used for menus set up as unordered lists. Change the nav root id 
	   if needed, and remember to add an "over" class to your stylesheet. */

	enableHover : function() {
		if ( vanilla.getElementById( "topnav" ) ) { // prevent script warning in IE
			var nodes = vanilla.getElementById( "topnav" ).getElementsByTagName( "LI" );
			for ( i = 0; i < nodes.length; i++ ) {
				var node = nodes[i];
				node.onmouseover = function() {
					vanilla.addClassName( this, "over" );
				}
				node.onmouseout = function() {
					vanilla.removeClassName( this, "over" );
				}
			}
		}
	},

	/* This function is used on dropdown menus to send users to a new URL */

	jumpTo : function( select ) {
		var url = select[select.selectedIndex].value;
		if ( !url ) return;
		window.location = url;
	},

	/* This function is called by lte and radio forms */

	setTab : function( tab ) {
		if ( tab == 'tp' ) {
			this.removeClassName( this.getElementById( 'tab-wt' ), 'show' );
			this.removeClassName( this.getElementById( 'text-wt' ), 'show' );
			this.addClassName( this.getElementById( 'tab-tp' ), 'show' );
			this.addClassName( this.getElementById( 'text-tp' ), 'show' );
		} else if ( tab == 'wt' ) {
			this.removeClassName( this.getElementById( 'tab-tp' ), 'show' );
			this.removeClassName( this.getElementById( 'text-tp' ), 'show' );
			this.addClassName( this.getElementById( 'tab-wt' ), 'show' );
			this.addClassName( this.getElementById( 'text-wt' ), 'show' );
		}
		return false;
	},

	/* This function adds three extra divs to an element in order to apply rounded
	   corners to the 'readmore' buttons. Set the class name to "readmore" and add styles for that
	   class for the unstyled appearance. The class name is changed to "roundreadmore". */

	makeRoundedButtons : function() {
		var els = vanilla.getElementsByClassName( "readmore" );

		for (var i = 0; i < els.length; i++) {
			var el = els[i];

			/* Change class name for background images */
			vanilla.removeClassName( el, "readmore" );
			vanilla.addClassName( el, "roundreadmore" );
			
			/* gather up the children */
			var children = el.childNodes;
			var childElements = new Array();
			for ( var j = 0; j < children.length; j++ ) {
				if ( children[j].nodeType == 1 ) {
					childElements.push( children[j] );
				}
			}

			/* create new divs and append */
			var div1 = document.createElement( "div" );
			var div2 = document.createElement( "div" );
			var div3 = document.createElement( "div" );

			for ( var j = 0; j < childElements.length; j++ ) {
				div3.appendChild( childElements[j] );
			}

			div2.appendChild( div3 );
			div1.appendChild( div2 );
			el.appendChild( div1 );
		}
	},



	/* This function is specific to this site. It adds an extra div to items of 
	   class 'divider' to apply some rounded corners. We can use 'this' to call 
	   other vanilla functions since we are loading it as a handler. */

	makeRoundedDividers : function() {
		var els = vanilla.getElementsByClassName( "divider" );

		for (var i = 0; i < els.length; i++) {
			var el = els[i];

			/* Change class name for background images */
			vanilla.removeClassName( el, "divider" );
			vanilla.addClassName( el, "rounddivider" );

			/* create new divs and append */
			var txt = el.childNodes[0];
			var div = document.createElement( "div" );
			div.appendChild( txt );
			el.appendChild( div );
		}
	}



}

/* enable or disable as needed */

vanilla.addLoadEvent( vanilla.getNewWindowLinks );
vanilla.addLoadEvent( vanilla.makeRoundedDividers );
vanilla.addLoadEvent( vanilla.makeRoundedButtons );
vanilla.addLoadEvent( vanilla.enableHover );

$(document).ready(function() {
    // fade form error bg
    $("#messages").animate({opacity: 1.0}, 3000).animate({backgroundColor: '#ffffff'}, 3000);

    // rounded corners 
    var roundStr = '<b class="cn tl"></b><b class="cn tr"></b><b class="cn bl"></b><b class="cn br"></b>';
    $('.round').addClass('boxc').append(roundStr);
    $('form#contribution_form h3').addClass('round').addClass('boxc').append(roundStr);

    // hollow rounded corners
    var roundStr = '<b class="cn tl"></b><b class="cn tr"></b><b class="cn bl"></b><b class="cn br"></b>';
    $('.round2').addClass('boxc2').append(roundStr);

    // set and unset values in amount fields on contribute forms
    $("input[name=amount]").not("#id_amount_other_btn").click(function() {
        $("#id_amount_other").val("");
    });
    $("#id_amount_other").blur(function() {
        if ($(this).val() == "") {
            $("#id_amount_other_btn").attr("checked", false);
        } else {
            $("#id_amount_other_btn").attr("checked", true);
        }
    });

	// hide preview bars
	$('.preview_notice a.hide_preview').click(function() {
	    $('.preview_notice').hide();
	});

    // handler for checkbox on membership pages
    $("#id_billing_info_same").change( function() {
        if ($("#id_billing_info_same").attr("checked")) {
            $("#billing_info").hide();
        } else {
            $("#billing_info").show();
        }
    });
});
