// !carousel stuff

var counter = 0;
var today = new Date();
var month_counter = 1;
var full_months = new Array("", "January","February","March","April","May","June","July","August","September","October","November","December");
var fields = new Object();

// !jquery reassignment
var j$ = jQuery.noConflict();


function carouselVisibleOut(carousel, item, i, state, evt)	{
	carousel.lock();
  carousel.add(++counter, item.innerHTML);
  carousel.remove(i);
	carousel.size( carousel.size()+1 );
  carousel.unlock();
};

function carouselInit(carousel) {
  j$('#next').click(function() {
      carousel.next();
      return false;
  });
}

function resettableFields() {

	//arguments should be an array of form IDs/classes with ./# notation
	for (var i = 0; i < arguments.length; i++) {

  	//dynamically build object with field name/initial value pairs
  	//someday we should rewrite this to allow for excluded form fields, but whatever
  	j$(arguments[i]+" input[type='text']").each(function(i) {
  		fields[ j$(this).attr("name") ] = j$(this).val();
  	});
      	
  	//now configure behavior 
  	j$(arguments[i]+" input[type='text']").focus(function() {
  		if ( j$(this).val() == fields[ j$(this).attr("name") ] ) 	j$(this).val("");
  	}).blur(function() {
  		if (j$(this).val() == "") j$(this).val( fields[ j$(this).attr("name") ] );
  	});
  	
  }
}


//checks for a valid zip code
function isZip( theval ) {
	var filter = /^([0-9]{5})+$/;
	if (!filter.test( theval )) {
		alert("Please enter a valid zip code"); 
		return false;
	}
	return true;					
}

//checks for a valid email address   
function isEmail( theval ) {
	var filter  = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if ( !filter.test( theval ) || "" == theval ) {
		alert("Please enter a valid email address");
		return false;
	}
	return true;		
}

function isFull( theval, text ) {
	if (theval.length < 1) {
		alert("Please enter "+text);
		return false;
	}
	return true;
}


function formatConvioDate ( edate_array, etime ) {
	var months = new Array("", "Jan. ","Feb. ","Mar. ","Apr. ","May ","June ","July ","Aug. ","Sept. ","Oct. ","Nov. ","Dec ");
	var merid = " p.m.";
	var timestring = "";
	if (typeof(etime) == "string") {
    var t = etime.split(":");
    if (t[0] > 12 ) t[0] = t[0] - 12;
    else (merid = " a.m."); 
    timestring = ", " + t[0] + ":" + t[1] + merid;
  }
	return months[ edate_array[1]*1 ] + (edate_array[2]*1) + timestring;	
}

function writeConvioEvent ( name, time ) {
  string = "&nbsp; ";
  if (name.length > 42) name = name.substr(0,39) + "... ";
  else name = name + ": "
  return string + name + time;
}

function makeJSONreq (apikey, month_to_get, year_to_get, num_months, the_url) {

	j$.getJSON(the_url, {
		v:"1.0",
		api_key:apikey,
		method:"getMonthEvents",
		response_format:"json",
		month:month_to_get,
		year:year_to_get
	}, function (json_result) {
	
		var eventlist = '<option disabled="disabled">'+full_months[month_to_get].toUpperCase()+" "+year_to_get+"</option>";

		if (json_result.errorResponse) {
			alert(json_result.errorResponse.message);
			return;
		}

		j$.each(json_result.getMonthEventsResponse.event, function(i,event){
			//if this event happened before today, ignore it
			e = event.eventDate.startDate.split("-");
			if (e[0] == today.getFullYear() && e[1]-1 == today.getMonth() && e[2]*1 < today.getDate()) return true;
			str = '<option value="'
						+ event.eventUrl + '">'
						+ writeConvioEvent(event.name, formatConvioDate( e, event.eventDate.startTime ) )
						+ '</option>';
			eventlist = eventlist + str;
		});	//end json results loop
		
		j$("#show_list").append(eventlist);
			
		//recursive if necessary
		if (++month_counter <= num_months) {
			month_to_get = ((today.getMonth() + month_counter) % 12);
			if (month_to_get == 0) month_to_get = 12;
			year_to_get = (today.getMonth() > month_to_get) ? today.getFullYear() + 1 : today.getFullYear();
			makeJSONreq(apikey,month_to_get,year_to_get,num_months,the_url);
		} else {
  		j$("#show_list").append('<option value="http://www.austintheatre.org/site/PageNavigator/shows_events/calendar">View Complete Calendar...</option>');
  		j$("#show_list option:first-child").html("(select show)");
		}
		
	}	//end json reult processing		
); //end getJSON call
} 	

function getConvioEventsRecursive(apikey, site_abbr, num_months) {
	if (window.location.hostname == "www.austintheatre.org") the_url = "/site/CROrgEventAPI";
	else the_url = "/"+site_abbr+"/site/CROrgEventAPI";
	
	makeJSONreq(apikey, today.getMonth()+1, today.getFullYear(), num_months, the_url);	
}

// !jquery load

j$(document).ready(function(){
	
	getConvioEventsRecursive("paramount","ata",6);

	resettableFields("#searchform","#signup");
	
	j$("#mask #next, #feedback, #search_submit, #twitter, #facebook, #flickr").hover(function() {
		j$(this).addClass("hover");
	}, function() { 
		j$(this).removeClass("hover");
	});
	
	j$("#show_list, #involvement_list").change(function() {
		if (j$(this).val() != "") window.location.href = j$(this).val();
	});
	
	j$("#features").fadeIn(2000);
	
	counter = j$("#features ul li").length;
				
	j$("#features ul").jcarousel({
		vertical:false,
		scroll:1,
		auto:8,
		animation:1280,
		wrap:'circular',
	  itemVisibleOutCallback: {onAfterAnimation: carouselVisibleOut},
	  initCallback: carouselInit,
	  easing:'easeOutCubic'
	});
	
	j$('ul.sf-menu > li > a').html('');
	
	j$('ul.sf-menu').superfish({
		animation:{opacity:'show', height:'show'},
		speed:'fast',
		delay:600
	});
	
	//IE7 hacks
	if ( typeof(isIE7) == 'boolean' ) {
	 innerheight = j$("#announcement div table").height();
	 offset = (j$("#announcement").height() - innerheight) / 2 | 0;  //cast as int
	 j$("#announcement div").css("padding-top",offset+"px");
	 j$("hr").replaceWith('<div class="ruler"');
	}
	
	// !form functionality
	j$('#submitter').click(function() {
		if (isEmail(j$("#signup #cons_email").val()) && 
				isZip(j$("#signup #cons_zip").val()) &&
				isFull(j$("#signup #cons_first_name").val(), "your first name") &&
				isFull(j$("#signup #cons_last_name").val(), "your last name")
				) {
			j$('form#get_updates').submit();
		}
	});

	j$('#search_submit').click(function() {
		j$('form#searchform').submit();
	});
	
	// blog links in new windows
	j$("#blogs a").attr("target","_blank");
	
	//sidebar height hack
	j$("#right").height( j$("#content").innerHeight() );
	
	//buy tickets online behaviors 
	j$("table.listing h3, table.bto h3").siblings("a").append(" &raquo;");
	j$("table.listing .buynow a, table.bto .buynow a").hover(function () {
	 j$(this).addClass("hover").parents("table").addClass("hover");
	}, function () {
	 j$(this).removeClass("hover").parents("table").removeClass("hover");	
	});
	
	//homepage return
	j$("#paramount, #state").click(function() {
	 window.location.href = "http://www.austintheatre.org/";
	});
	
	//announcement carat?
	the_url = j$("#announcement td a").attr("href");
	j$("#announcement td p").append('<a href="'+the_url+'">&raquo;</a>');
	
	j$("table.listing tr td span, table.bto tr td span").each(function(i) {
    contents = j$(this).html();
    terms = contents.split(" ",2);
    currentMonth = full_months[ today.getMonth()+1 ];
    if (terms[0] !== currentMonth) return true;
    else {
      if (terms[1] < today.getDate()) {
        j$(this).parents("table").remove();
      }
    }
  });
	
});
