/*
 * Treeview 1.4 - jQuery plugin to hide and show branches of a tree
 * 
 * http://bassistance.de/jquery-plugins/jquery-plugin-treeview/
 * http://docs.jquery.com/Plugins/Treeview
 *
 * Copyright (c) 2007 Jörn Zaefferer
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.treeview.js 4684 2008-02-07 19:08:06Z joern.zaefferer $
 *
 */

;(function($) {

	$.extend($.fn, {
		swapClass: function(c1, c2) {
			var c1Elements = this.filter('.' + c1);
			this.filter('.' + c2).removeClass(c2).addClass(c1);
			c1Elements.removeClass(c1).addClass(c2);
			return this;
		},
		replaceClass: function(c1, c2) {
			return this.filter('.' + c1).removeClass(c1).addClass(c2).end();
		},
		hoverClass: function(className) {
			className = className || "hover";
			return this.hover(function() {
				$(this).addClass(className);
			}, function() {
				$(this).removeClass(className);
			});
		},
		heightToggle: function(animated, callback) {
			animated ?
				this.animate({ height: "toggle" }, animated, callback) :
				this.each(function(){
					jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ]();
					if(callback)
						callback.apply(this, arguments);
				});
		},
		heightHide: function(animated, callback) {
			if (animated) {
				this.animate({ height: "hide" }, animated, callback);
			} else {
				this.hide();
				if (callback)
					this.each(callback);				
			}
		},
		prepareBranches: function(settings) {
			if (!settings.prerendered) {
				// mark last tree items
				this.filter(":last-child:not(ul)").addClass(CLASSES.last);
				// collapse whole tree, or only those marked as closed, anyway except those marked as open
				this.filter((settings.collapsed ? "" : "." + CLASSES.closed) + ":not(." + CLASSES.open + ")").find(">ul").hide();
			}
			// return all items with sublists
			return this.filter(":has(>ul)");
		},
		applyClasses: function(settings, toggler) {
			this.filter(":has(>ul):not(:has(>a))").find(">span").click(function(event) {
				toggler.apply($(this).next());
			}).add( $("a", this) ).hoverClass();
			
			if (!settings.prerendered) {
				// handle closed ones first
				this.filter(":has(>ul:hidden)")
						.addClass(CLASSES.expandable)
						.replaceClass(CLASSES.last, CLASSES.lastExpandable);
						
				// handle open ones
				this.not(":has(>ul:hidden)")
						.addClass(CLASSES.collapsable)
						.replaceClass(CLASSES.last, CLASSES.lastCollapsable);
						
	            // create hitarea
				this.prepend("<div class=\"" + CLASSES.hitarea + "\"/>").find("div." + CLASSES.hitarea).each(function() {
					var classes = "";
					$.each($(this).parent().attr("class").split(" "), function() {
						classes += this + "-hitarea ";
					});
					$(this).addClass( classes );
				});
			}
			
			// apply event to hitarea
			this.find("div." + CLASSES.hitarea).click( toggler );
		},
		treeview: function(settings) {
			
			settings = $.extend({
				cookieId: "treeview"
			}, settings);
			
			if (settings.add) {
				return this.trigger("add", [settings.add]);
			}
			
			if ( settings.toggle ) {
				var callback = settings.toggle;
				settings.toggle = function() {
					return callback.apply($(this).parent()[0], arguments);
				};
			}
		
			// factory for treecontroller
			function treeController(tree, control) {
				// factory for click handlers
				function handler(filter) {
					return function() {
						// reuse toggle event handler, applying the elements to toggle
						// start searching for all hitareas
						toggler.apply( $("div." + CLASSES.hitarea, tree).filter(function() {
							// for plain toggle, no filter is provided, otherwise we need to check the parent element
							return filter ? $(this).parent("." + filter).length : true;
						}) );
						return false;
					};
				}
				// click on first element to collapse tree
				$("a:eq(0)", control).click( handler(CLASSES.collapsable) );
				// click on second to expand tree
				$("a:eq(1)", control).click( handler(CLASSES.expandable) );
				// click on third to toggle tree
				$("a:eq(2)", control).click( handler() ); 
			}
		
			// handle toggle event
			function toggler() {
				$(this)
					.parent()
					// swap classes for hitarea
					.find(">.hitarea")
						.swapClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
						.swapClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea )
					.end()
					// swap classes for parent li
					.swapClass( CLASSES.collapsable, CLASSES.expandable )
					.swapClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
					// find child lists
					.find( ">ul" )
					// toggle them
					.heightToggle( settings.animated, settings.toggle );
				if ( settings.unique ) {
					$(this).parent()
						.siblings()
						// swap classes for hitarea
						.find(">.hitarea")
							.replaceClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
							.replaceClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea )
						.end()
						.replaceClass( CLASSES.collapsable, CLASSES.expandable )
						.replaceClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
						.find( ">ul" )
						.heightHide( settings.animated, settings.toggle );
				}
			}
			
			function serialize() {
				function binary(arg) {
					return arg ? 1 : 0;
				}
				var data = [];
				branches.each(function(i, e) {
					data[i] = $(e).is(":has(>ul:visible)") ? 1 : 0;
				});
				$.cookie(settings.cookieId, data.join("") );
			}
			
			function deserialize() {
				var stored = $.cookie(settings.cookieId);
				if ( stored ) {
					var data = stored.split("");
					branches.each(function(i, e) {
						$(e).find(">ul")[ parseInt(data[i]) ? "show" : "hide" ]();
					});
				}
			}
			
			// add treeview class to activate styles
			this.addClass("treeview");
			
			// prepare branches and find all tree items with child lists
			var branches = this.find("li").prepareBranches(settings);
			
			switch(settings.persist) {
			case "cookie":
				var toggleCallback = settings.toggle;
				settings.toggle = function() {
					serialize();
					if (toggleCallback) {
						toggleCallback.apply(this, arguments);
					}
				};
				deserialize();
				break;
			case "location":
				var current = this.find("a").filter(function() { return this.href.toLowerCase() == location.href.toLowerCase(); });
				if ( current.length ) {
					current.addClass("selected").parents("ul, li").add( current.next() ).show();
				}
				break;
			}
			
			branches.applyClasses(settings, toggler);
				
			// if control option is set, create the treecontroller and show it
			if ( settings.control ) {
				treeController(this, settings.control);
				$(settings.control).show();
			}
			
			return this.bind("add", function(event, branches) {
				$(branches).prev()
					.removeClass(CLASSES.last)
					.removeClass(CLASSES.lastCollapsable)
					.removeClass(CLASSES.lastExpandable)
				.find(">.hitarea")
					.removeClass(CLASSES.lastCollapsableHitarea)
					.removeClass(CLASSES.lastExpandableHitarea);
				$(branches).find("li").andSelf().prepareBranches(settings).applyClasses(settings, toggler);
			});
		}
	});
	
	// classes used by the plugin
	// need to be styled via external stylesheet, see first example
	var CLASSES = $.fn.treeview.classes = {
		open: "open",
		closed: "closed",
		expandable: "expandable",
		expandableHitarea: "expandable-hitarea",
		lastExpandableHitarea: "lastExpandable-hitarea",
		collapsable: "collapsable",
		collapsableHitarea: "collapsable-hitarea",
		lastCollapsableHitarea: "lastCollapsable-hitarea",
		lastCollapsable: "lastCollapsable",
		lastExpandable: "lastExpandable",
		last: "last",
		hitarea: "hitarea"
	};
	
	// provide backwards compability
	$.fn.Treeview = $.fn.treeview;
})(jQuery);

function createModal(_callerID, _duckCallerLink) {
  $.getJSON('/remote/RemoteUOService.cfc?method=getDuckCaller&returnFormat=json&callerid=' + _callerID + '&queryFormat=column',        function(data) { 
	
	  /* Parse JSON and create html */
	  $('#basicModalContent').empty();
	    var duckCaller = data.DATA;
	
  	  var html = '<div id="student-detail">';
				 	html += '<div id="student-detail-left">';
	  				html +=	'<img src="/images/public/' + duckCaller['IMAGE_SRC'][0] + '&w=259&h=282" alt="' + duckCaller['FIRST_NAME'][0] + ' ' + duckCaller['LAST_NAME'][0] + '" />';
	  				html += '<br />';						
	  				html += '<br />';
						html += '<p class="float"><a id="close-modal" onclick="closeModal(); return false" href="">close window</a></p>';
						html += '<p class="float-right">';
						if (duckCaller['PREVIOUS_CALLER_ID'][0] != null) {
						  html += '<a class="' + duckCaller['PREVIOUS_CALLER_ID'][0] + '" id="prev-caller" onclick="prevModal(); return false" href=""><span>prev</span></a>';
					  }
						if (duckCaller['NEXT_CALLER_ID'][0] != null) {
						  html += '<a class="' + duckCaller['NEXT_CALLER_ID'][0] + '" id="next-caller" onclick="nextModal(); return false" href=""><span>next</span></a>';
					  }
						html += '</p>';
						html += '<div class="clear"></div>';
	  			html += '</div>';
	  			html += '<div id="student-detail-right">';
	  				html += '<h3>' + duckCaller['FIRST_NAME'][0] + ' ' + duckCaller['LAST_NAME'][0] + '</h3>';
	  				if (duckCaller['CLASS_YEAR'][0] != null) {
	  				  html += '<p><span>Class of ' + duckCaller['CLASS_YEAR'][0] + '</span></p>';
	  				}
	  				html += '<h5>Major: <span>' + duckCaller['MAJOR'][0] + '</span></h5>';
	  				html += '<h5>Hometown: <span>' + duckCaller['HOMETOWN'][0] + '</span></h5>';
	  				if (duckCaller['QUESTION_2'][0] != null) {
							html += '<h5>' + (duckCaller['QUESTION_1'][0]).replace("'", "\\'") + ':</h5>';
							html += '<p>' + (duckCaller['ANSWER_1'][0]).replace("'", "\\'") + '</p>';
						}
	  				if (duckCaller['QUESTION_2'][0] != null) {
	  				  html += '<h5>' + duckCaller['QUESTION_2'][0] + ':</h5>';
	  				  html += '<p>' + duckCaller['ANSWER_2'][0] + '</p>';
	  				}
	  				if (duckCaller['QUESTION_3'][0] != null) {
	  				  html += '<h5>' + duckCaller['QUESTION_3'][0] + ':</h5>';
	  				  html += '<p>' + duckCaller['ANSWER_3'][0] + '</p>';
	  				}
	  				html += '<br />';
	  				html += '<br />';
	  				if (duckCaller['DUCK_STORY_ID'][0] != null) {
	  				  html += '<p><a href="/my_duckstory/story/' + duckCaller['DUCK_STORY_ID'][0] + '">Read <span>' + duckCaller['FIRST_NAME'][0] + '\'s</span> DuckStory...&raquo;</a></p>';
	  				}
	  			html += '</div>';
	  			html += '<div class="clear"></div>';
  	    html += '</div>';
	  $('#basicModalContent').append(html); 	
  }); 
  makeModal();
  return false;
}

function prevModal() {
	var callerID = $('#prev-caller').attr('class');
	var duckCallerLink = $('#prev-caller').attr('href');
	createModal(callerID, duckCallerLink);
  return false;
}
function nextModal() {
	var callerID = $('#next-caller').attr('class');
	var duckCallerLink = $('#next-caller').attr('href');
	createModal(callerID, duckCallerLink);
  return false;
}
function makeModal(){
	$('#basicModalContent').modal({
		overlayCss: {
			backgroundColor: '#000'
		},
		containerCss: {
			height: '400',
			width: '600',
			backgroundColor: '#fff',
			border: '3px solid #ccc'
		}
	});
}
function closeModal(){
  $.modal.close();
  return false;
};

/*jQUERY FUNCTIONS*/
$(document).ready(function() {
  
  /*MESSAGE BOXES*/
  /*Add Click handler to links to goodsearch.com*/
  $('a[@href^="http://www.goodsearch"]').click(function() {
  	var linkURL = $(this).attr('href');
    /*Create Semi-transparent black window*/
    $("<div>").css({
		  'position': 'absolute',
		  'top': '0px',
		  'left': '0px',
		  backgroundColor: 'black',
		  'opacity': '0.75',
		  'width': '100%',
		  'height': $(window).height(),
		  zIndex: 5000
	  })
	  .appendTo("body"); 
	  
	  /*Create Message Box*/
    $("<div class='dropshadow'><img src='/images/good_search_logo.gif' alt='Good Search' /><p><br />You are being redirected away from the<br />Annual Giving Program.<br /><br />Thank you for using GoodSearch to support<br />the University of Oregon!</p><br /><br /><p><a href='/goodsearch'><img src='/images/annual_giving_link.gif' alt='Annual Giving Home' class='float' style='margin:0 0 0 25px;' /></a><a href='" + linkURL + "'><img src='/images/good_search_now_link.gif' alt='GoodSearch Now' class='float' /></a></p></div>")
	    .css({
		    backgroundColor: 'white',
		    'top': '50%',
		    'left': '50%',
		    marginLeft: -210,
		    marginTop: -100,
		    width: 290,
		    padding: 20,
		    fontSize: 11,
		    height: 166,
		    'position': 'absolute',
		    zIndex: 6000
	  })
	  .appendTo("body");
	  return false;
  });
  
  /*Add Click handler to links to goodshop.com*/
  $('a[@href^="http://www.goodshop"]').click(function() {
  	var linkURL = $(this).attr('href');
    /*Create Semi-transparent black window*/
    $("<div>").css({
		  'position': 'absolute',
		  'top': '0px',
		  'left': '0px',
		  backgroundColor: 'black',
		  'opacity': '0.75',
		  'width': '100%',
		  'height': $(window).height(),
		  zIndex: 5000
	  })
	  .appendTo("body"); 
	  
	  /*Create Message Box*/
    $("<div class='dropshadow'><img src='/images/good_shop_logo.gif' alt='Good Shop' /><p><br />You are being redirected away from the<br />Annual Giving Program.<br /><br />Thank you for using GoodShop to support<br />the University of Oregon!</p><br /><p><a href='/goodsearch'><img src='/images/annual_giving_link.gif' alt='Annual Giving Home' class='float' style='margin:0 0 0 25px;' /></a><a href='" + linkURL + "'><img src='/images/good_shop_now_link.gif' alt='GoodShop Now' class='float' /></a></p></div>")
	    .css({
		    backgroundColor: 'white',
		    'top': '50%',
		    'left': '50%',
		    marginLeft: -210,
		    marginTop: -100,
		    width: 290,
		    padding: 20,
		    fontSize: 11,
		    height: 166,
		    'position': 'absolute',
		    zIndex: 6000
	  })
	  .appendTo("body");
	  return false;
  });
  
  /* Duck Call list*/
  $('.caller-item').click(function (e) {
  	e.preventDefault();
  	var callerID = $('a', this).attr('class');
  	var duckCallerLink = $('a', this).attr('href');
  	createModal(callerID, duckCallerLink);
		return false;
	});
	
	/* Contact List Tree */
	$("#contact-list").treeview({
		collapsed: true,
		animated: "fast"
	});
	
	/* Payroll Deduction Form */
	$("#gift_annuity_input").click(function() {
	  $("#gift_info_input").attr('checked', 'checked');
	});
	$("#remainder_trust_input").click(function() {
	  $("#gift_info_input").attr('checked', 'checked');
	});
	
	/* Search */

	/* Update the Fund Types based on search options */
  var updateFundTypes = function(){
     var programId = $('#fundSearchForm #program_id').val();
     var childId = $('#child_program_id').val();
     $.getJSON('/remote/RemoteFundService.cfc?method=getFundTypesByPrograms&returnFormat=json&queryFormat=column&parentProgramID=' + programId + '&childProgramID=' + childId, function(data) { 
      /* Parse JSON and create html */
      $('.fund-search-checkbox').empty();
      var response = data.DATA;
      var options = '';
      
      //hide or show the or search options
      if(response['TITLE'].length == 0){
        $('#fund-search-checkbox-option').hide();
      }else{
        $('#fund-search-checkbox-option').show();
      }

      for(var i=0, len=response['TITLE'].length; i < len; i++){
        $('.fund-search-checkbox').html($('.fund-search-checkbox').html() + '<input id="fund_type_id_list_' + response['FUND_TYPE_ID'][i]  + '" type="checkbox" value="' + response['FUND_TYPE_ID'][i] + '" name="fund_type_id_list"/>'
          + '<label for="fund_type_id_list">' + response['TITLE'][i] + '</label>' 
          + '<br/>')      
      }
    });
  };
	
	/* Update the Program or department based on changes to school */
	var updateProgramDepartment = function(){
	  var programId = $('#fundSearchForm #program_id').val();
	  
	  
    $.getJSON('/remote/RemoteProgramService.cfc?method=getProgramChildren&returnFormat=json&queryFormat=column&programID=' + programId , function(data) { 
      /* Parse JSON and create html */
      //$('#child_program_id').empty();
      var response = data.DATA;
      var options = '';
       	  
	  // remove all the items
	  var selectBox = document.getElementById('child_program_id');
	  var i;
	  for(i=selectBox.options.length-1;i>=0;i--){
		selectBox.remove(i);
      }
	  selectBox.options.length = 0;
	  
	  
      $('#child_program_container').show();
			
		if(response['TITLE'].length == 0){
			$('#child_program_container').hide();
		}
		
      $('#child_program_id').addOption('Select a program department', 'Select a program/department');
	  
      for(var i=0, len=response['TITLE'].length; i < len; i++){
	  	if(response['PROGRAM_ID'][i] != '' && response['PROGRAM_ID'][i] > 0){
			
			var elOptNew = document.createElement('option');
			  elOptNew.text = response['TITLE'][i];
			  elOptNew.value = response['PROGRAM_ID'][i];
			
			  try {
			    selectBox.add(elOptNew, null); // standards compliant; doesn't work in IE
			  }
			  catch(ex) {
			    selectBox.add(elOptNew); // IE only
			  }

		}
      }
      $("option:first","#child_program_id").attr("selected","selected");
    });
		
		//update the fund types based on the school / college
		updateFundTypes();
  };
	
	/* On college change */
	$("#fundSearchForm #program_id").change(updateProgramDepartment);
	
	/* On Department Change */
	$("#fundSearchForm #child_program_id").change(updateFundTypes);
	
	//when loading the page, update the parent
	if($("#fundSearchForm #program_id").length > 0){
		updateProgramDepartment();
		updateFundTypes();
	}
});