var RTG; if (!RTG) RTG = {}; if (!RTG.ui) RTG.ui = {}; RTG.ui.tooltips = [];

Function.prototype.delay = function() {
	var __method = this
	var timeout = arguments[0];
	var args = arguments;
    return window.setTimeout(function() {
      return __method.apply(__method, args);
    }, timeout);
	}



$(function(){
	$('.search_form select').selectbox();
	jQuery.ajaxSetup({ 
  'beforeSend': function(xhr) {
    xhr.setRequestHeader("Accept", "text/javascript");
		  } 
		});
	
	/*
if (document.getElementById('custom_amount'))
	$('#custom_amount').ajaxForm(function(req){
		$('#cart').html(req);
		$('#current_item').effect("highlight", {color: '#87D7ED'}, 1000);
	});
*/
	
	//new RTG.ui.Cart();
	
	$('.reasons .load_video').click(function(e){
		e.preventDefault();
		var target = $(e.target).parent('a').attr('href');
		//$('#video').load(target + " #video div");
		$.get(target, function(req){
			var content = $(req).find('#video div');
			$('#video').html(content);
		});
	});
	
	$('.success_stories .load_video').click(function(e){
		e.preventDefault();
		var target = $(e.target).parent('a').attr('href');
		//$('#video').load(target);
		$.get(target, function(req){
			$('#video').html(req);
		});
	});

	$('.holiday-gift-cards .load_video').click(function(e){
		e.preventDefault();
		var target = $(e.target).parent('a').attr('href');
		//$('#video').load(target);
		$.get(target, function(req){
			$('#video').html(req);
		});
	});
	
	//cart functions//
	$.getScript("/javascripts/jquery.tooltip.js", function() {
		$('#percent_donated a').tooltip({track: true,  top: 4, left: -300, delay: 0, showURL: false}).css({textDecoration: 'none'}).click(function(e){e.preventDefault()});
		$('.why_this_amount a').tooltip({track: true,  top: 4, left: -300,delay: 0, showURL: false}).css({textDecoration: 'none'}).click(function(e){e.preventDefault()});
		$('.donor_thanked').tooltip({track: true,  top: 4, left: -300,delay: 0, showURL: false}).css({textDecoration: 'none'}).click(function(e){e.preventDefault()});
		$(RTG.ui.tooltips).each(function(i, el){
			$(el).tooltip({track: true,  top: 4, left: -300,showURL: false, delay: 0,  extraClass: $(el).attr('id')}).css({textDecoration: 'none'}).click(function(e){e.preventDefault()});
		});
	});
	
	//hide yellow instuction boxes
	$('.instructions .circle_close a').click(function(e){
		e.preventDefault();
		$(this).parents('.instructions').hide('normal');
	});
	
	if(document.getElementById('slideShow'))
		initCarousel();
		
	fixExternalLinks();
	
});




function initCarousel() {
	var images = ['feature1.jpg', 'feature2.jpg', 'feature3.jpg', 'feature4.jpg', 'feature5.jpg', 'feature6.jpg', 'feature7.jpg', 'feature8.jpg', 'feature9.jpg', 'feature10.jpg'];
	var nav = $("<ul id='slideShowNav'></ul>"); 
	$("#slideShow").after(nav);
	 $.each(images, function(i, el){
	 	if (i != 0) {
			var newLi = "<li><img src='/features/" + el + "' /></li>"
			$('#slideShow').append($(newLi));
			}
			var newNavLi = "<li><a href='#'>" + (i+1) + "</a></li>";
			nav.append($(newNavLi)); 
	});
	
	$('#slideShow').jcarousel({
		auto: 4,
		scroll: 1,
		wrap: 'last',
		initCallback: mycarousel_initCallback,
		itemVisibleInCallback:{
			onBeforeAnimation: updateUI
		} 
	});
}

function updateUI(carousel, li, index, state) {
	$('#slideShowNav a').removeClass('current');
	$($('#slideShowNav a').get(index - 1)).addClass('current');
	//$('#slideShowNav').get(index).attr('class', 'on');
}

function mycarousel_initCallback(carousel, li) {
 jQuery('#slideShowNav a').bind('click', function() {
 	var index = jQuery(this).text();
 carousel.scroll(jQuery.jcarousel.intval(index));
 carousel.stopAuto();
 carousel.startAuto();
 	updateUI(carousel, li, index)
 return false;
 });

 jQuery('.jcarousel-scroll select').bind('change', function() {
 carousel.options.scroll = jQuery.jcarousel.intval(this.options[this.selectedIndex].value);
 $('#slideShowNav a').removeClass('current');
 return false;
 });

 jQuery('#mycarousel-next').bind('click', function() {
 carousel.next();
 return false;
 });

 jQuery('#mycarousel-prev').bind('click', function() {
 carousel.prev();
 return false;
 });
};

function popup(element){
  $(element).toggle();
  $(element).style.position = 'absolute';
  var dim = Element.getDimensions($(element));
  var top = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
  $(element).style.top = (top + 100) + 'px';
  $(element).style.left = (($('main-container').offsetWidth - dim.width) / 2) + 'px';
}

function checkForAdmin(){
		new Ajax.Request('/sessions/show', {
		onComplete: function(req){
			if (req.responseText == 'Administrator') {
	  		document.fire('load:admin');
	 		 }
		},
		method: 'GET',
		requestHeaders: {
			Accept: 'text/plain'
		}
	});
}

function initTinyMce() {
	tinyMCE.init({
		mode : "textareas",
		theme : "firebelly",
		theme_firebelly_buttons1 : "bold,italic,underline,strikethrough,|,styleselect,formatselect,link,unlink,code,image,media",
		theme_firebelly_buttons2 : "",
		theme_firebelly_buttons3 : "",
		theme_firebelly_buttons4 : "",
		theme_firebelly_toolbar_location : "top",
		plugins : "media",
		valid_elements: "a[href],strong/b,small,img[src],div[align|class],br,p[align|class],em/i,ul[align|class],li[align],-p,h3[align|class|id],h2[align|class|id],h4[align],h1[align],embed",
		extended_valid_elements: "embed[*],object[*]"
	});
}

//cookie functions from quirksmode
function createCookie(name,value,days) {
 if (days) {
 var date = new Date();
 date.setTime(date.getTime()+(days*24*60*60*1000));
 var expires = "; expires="+date.toGMTString();
 }
 else var expires = "";
 document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
 var nameEQ = name + "=";
 var ca = document.cookie.split(';');
 for(var i=0;i < ca.length;i++) {
 var c = ca[i];
 while (c.charAt(0)==' ') c = c.substring(1,c.length);
 if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
 }
 return null;
}

function destroy_upon_submit(element){
  $(element).next('.destroy_upon_submit').value = 1;
  $(element).up('.item').hide();
}

function fixExternalLinks() {
	var a = document.getElementsByTagName('a');
	for(var i=0; i<a.length; i++) {
		if (a[i].getAttribute('href') && (a[i].getAttribute('href').indexOf('http') == 0) && (a[i].getAttribute('href').toString().indexOf(window.location.host) == -1)) {
		$(a[i]).css({color: '#F55CAC' });
		$('.copyright a').css({color: '#77787B' });
		a[i].onclick = function(event){
			var event = event || window.event;
			if (event.preventDefault) 
				event.preventDefault();
			if (event.cancelBubble) 
				event.cancelBubble = true;
			window.open(this.href);
			return false;
		}
	}
	}
}

//Template function - John Resig


// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
(function(){
  var cache = {};
 
  this.tmpl = function tmpl(str, data){
    // Figure out if we're getting a template, or if we need to
    // load the template - and be sure to cache the result.
    var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
        tmpl(document.getElementById(str).innerHTML) :
     
      // Generate a reusable function that will serve as a template
      // generator (and which will be cached).
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +
       
        // Introduce the data as local variables using with(){}
        "with(obj){p.push('" +
       
        // Convert the template into pure JavaScript
        str
          .replace(/[\r\t\n]/g, " ")
          .split("<%").join("\t")
          .replace(/((^|%>)[^\t]*)'/g, "$1\r")
          .replace(/\t=(.*?)%>/g, "',$1,'")
          .split("\t").join("');")
          .split("%>").join("p.push('")
          .split("\r").join("\\'")
      + "');}return p.join('');");
   
    // Provide some basic currying to the user
    return data ? fn( data ) : fn;
  };
})();


