// for browsers that do not have array indexOf
if (!Array.prototype.indexOf){
  Array.prototype.indexOf = function(searchElement /*, fromIndex */)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (len === 0)
      return -1;

    var n = 0;
    if (arguments.length > 0)
    {
      n = Number(arguments[1]);
      if (n !== n) // shortcut for verifying if it's NaN
        n = 0;
      else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
        n = (n > 0 || -1) * Math.floor(Math.abs(n));
    }

    if (n >= len)
      return -1;

    var k = n >= 0
          ? n
          : Math.max(len - Math.abs(n), 0);

    for (; k < len; k++)
    {
      if (k in t && t[k] === searchElement)
        return k;
    }
    return -1;
  };
}
//*****Replace align attribute with class**************************************************//
function replaceAlign() {
  if ($('img').length < 1) return false;
  $('img[align="left"]').addClass('left').removeAttr('align');
  $('img[align="right"]').addClass('right').removeAttr('align');
  $('img[align="middle"]').addClass('middle').removeAttr('align');
}
//*****Replace target attribute with class**************************************************//
function replaceTarget() {
  if ($('a').length < 1) return false;
  $('a[target]').addClass('newwindow').removeAttr('target');
}
//*****The following function make it possible to have web standard popups**************************************************//
function strictNewWindow() {
  if ($('a').length < 1) return false;
  $('a.newwindow').click(function() {
    window.open($(this).attr('href'));
    return false;
  });
}
//*****Add swfobject flash call**************************************************//
function initializeFlash() {
  if (!document.getElementById('flash-content')) return false;
  var flashvars = {};
  var params = {wmode: 'transparent'};
  var attributes = {};
  attributes.id = "flash";
  swfobject.embedSWF("/swf/banner-flash-home.swf", "flash-content", "960", "338", "8.0.0", "/swf/expressInstall.swf", flashvars, params, attributes);
}
//*****jQuery clear value from july 21st 2009 comment on http://www.joesak.com/2008/11/19/a-jquery-function-to-auto-fill-input-fields-and-clear-them-on-click*****//
function clearDefaultValue() {
  $(':input').focus(function() {
    if($(this).val() == $(this).attr('title')) {
      $(this).val('');
    }
  }).blur(function() {
    if($(this).val() == '') {
      $(this).val($(this).attr('title'));
    }
  });
  $('#btnNext, #searchButton').click(function() {
	  $(':input').each(function (i) {
      if($(this).val() == $(this).attr('title')) {
        $(this).val('');
      }
    });
  });
}
function populateDefaultValues(){
  $(':input').each(function(){
    if($(this).val() == ''){
      $(this).val($(this).attr('title'));      
    }
  });
}
//*****Extend the footer to the bottom of the page**************************************************//
function extendFooter() {
  if ($('body.mediagallery.app').length > 0) return false;
  var footerHeight = $('#footer').height();
  var pageHeight = $(document.body).height();
  var windowHeight = $(document).height();
  var difference = windowHeight - pageHeight;
  if (pageHeight < windowHeight) {
    $('#footer').height(footerHeight + difference);
  } else {
    $('#footer').height('auto');
  }
}
//*****IE rounded corners from http://dillerdesign.com/experiment/DD_roundies/**************************************************//
function rounded() {
  DD_roundies.addRule('#header ul#headerNav li ul', '0 0 5px 5px');
  DD_roundies.addRule('#sidebar ul#sidebarNav', '0 0 10px 0');
}
//*****gallery Switcher**************************************************//
function gallerySelectChange() {
  if ($('#sitesDropdown').length < 1) return false;
  $('#sitesDropdown').change(function() {
    var site = '/gallery/' + $('#sitesDropdown option:selected').val() + '/';
    window.location.pathname = (site);
  });
}
//*****faculty Switcher**************************************************//
function facultySelectChange() {
  if ($('#slctFacultyMembers').length < 1) return false;
  $('#slctFacultyMembers').change(function() {
    var site = $('#slctFacultyMembers option:selected').val();
    window.location.href = (site);
  });
}
//*****Calendar Switcher**************************************************//
function calendarSelectChange() {
  $('#slctOtherCalendars').change(function() {
    var url = location.href;  // entire url including querystring - also: window.location.href;
    var hashes = url.slice(url.indexOf('/calendar/'));
    var site = $('#slctOtherCalendars option:selected').val();
    if ($(this).val() == "") {
      window.location = (site + hashes);
    } else {
      window.location = ('/' + site + hashes);
    }
  });
}
//*****Monthly Calendar Items**************************************************//
function monthlyCalendar() {
  if (!$.events) return false;
  var fullSourceList = $.events.fullSources;
  var date = new Date();
  var d = date.getDate();
  var m = date.getMonth();
  var y = date.getFullYear();
  $('#calendar').fullCalendar( {
	  aspectRatio: 1.20,
    titleFormat: {
		  month: 'MMM yyyy'
	  },
		columnFormat: {
			month: 'dddd'
		},
		header: {
      left: 'prevYear,prev,title,next,nextYear',
      center: '',
      right: ''
    },
		buttonText: {
			prev: '&nbsp;&lt;&nbsp;',
			next: '&nbsp;&gt;&nbsp;',
			prevYear: '&nbsp;&lt;&lt;&nbsp;', // << made from triangles
   		nextYear: '&nbsp;&gt;&gt;&nbsp;' // >> made from triangles
		},
    editable: false,
    eventSources: $.events.sources,
    loading: function(isLoading, view) {
      if (!isLoading){
        $('.fc-event').each(function(i) {
          var boxSize = 113;
          var leftOffset = 4;
          var rightOffset = 5;
          var width = $(this).width();
          var position = $(this).position();
          var size = [107,108];
          if ($.inArray(width % boxSize, size) != -1 && position && position.left != 0) {
            width = $(this).width(width - rightOffset + 'px');
          } else if (width % boxSize == 3 && position.left == 0) {
            $(this).css({left: leftOffset + 'px'});
            width = $(this).width(width - rightOffset - leftOffset + 'px');
          } else if (position.left == 0) {
            $(this).css({left: leftOffset + 'px'});
            $(this).width(width - leftOffset + 'px');
          }
        });
      }
    }
  });
				
	$("a[rel^='prettyPhoto']").prettyPhoto({
	  markup: '<div class="pp_pic_holder"> \
		    <div class="pp_top"> \
				  <div class="pp_left"></div> \
					<div class="pp_middle"></div> \
					<div class="pp_right"></div> \
				</div> \
				<div class="pp_content_container"> \
				  <div class="pp_left"> \
					  <div class="pp_right"> \
							<div class="pp_content"> \
								<div class="pp_fade"> \
									<a href="#" class="pp_expand" title="Expand the image">Expand</a> \
									<a class="pp_close" href="#">Close</a> \
									<div class="pp_loaderIcon"></div> \
									<div class="pp_hoverContainer"> \
										<a class="pp_next" href="#">next</a> \
										<a class="pp_previous" href="#">previous</a> \
									</div> \
									<div id="pp_full_res"></div> \
									<div class="pp_details clearfix"> \
										<p class="pp_description"></p> \
										<div class="pp_nav"> \
											<a href="#" class="pp_arrow_previous">Previous</a> \
											<p class="currentTextHolder">0/0</p> \
											<a href="#" class="pp_arrow_next">Next</a> \
										</div> \
									</div> \
								</div> \
							</div> \
						</div> \
					</div> \
				</div> \
				<div class="pp_bottom"> \
					<div class="pp_left"></div> \
					<div class="pp_middle"></div> \
					<div class="pp_right"></div> \
				</div> \
			</div> \
			<div class="pp_overlay"></div> \
			<div class="ppt"></div> \
		'
	});
		
	$('.fc-event a').live("click", function(e){
	  //use $(this) to grab/pass info from the <a> attributes such as rel, title, or just make one up with jQuery
	  url = $(this).attr('href');
	  cal = $(this).parent('div').attr('class').match(/cal\d+/gi);
		$.prettyPhoto.open($(this).attr('href')+'?cal='+cal[0]+'&iframe=true&width=550&height=300','','');
		e.preventDefault();
	});
		
	$('a#subscribeBtn').live("click", function(e){
	  //use $(this) to grab/pass info from the <a> attributes such as rel, title, or just make one up with jQuery
		$.prettyPhoto.open('ical/?iframe=true&width=550&height=447','','');
		e.preventDefault();
	});	
					
	$('#calendarList li a').click(function(e){
		if($(this).hasClass('strike')){
		  $(this).removeClass('strike');
		  var calType = "." + $(this).attr('rel') + ".fc-event";
      var calID = $(this).attr('rel').slice(3);
      $('#calendar').fullCalendar('addEventSource',fullSourceList[calID - 1]);        
		}	else{
		  $(this).addClass('strike');
		  var calType = "." + $(this).attr('rel') + ".fc-event";
      var calID = $(this).attr('rel').slice(3);
      $('#calendar').fullCalendar('removeEventSource',fullSourceList[calID - 1]);
		  
			//$('td.fc-leftmost .fc-day-content div').css('height', 'auto');
		}
		e.preventDefault();
	});
		
	$('a#closeCalendar').click(function(e){
	  window.close();
	  e.preventDefault();
	});
		
	function setDate() {
    var d = $('#calendar').fullCalendar('getDate');
    var year = d.getFullYear();
    var month = d.getMonth()+1;
    $('#printBtn').attr('href','print/?year=' + year + '&month=' + month);
    $('#listLink').attr('href','list/' + year + '/' + month + '/');
	}
		
	$('#printBtn').click(function(e){
	  if($('#calendarList li a.strike').length != 0){
	    var id_array = new Array(); 
	    $('#calendarList li a:not(.strike)').each(function(){
        var calID = $(this).attr('rel').slice(3);
	      id_array.push(calID);
      });
      var href = $('#printBtn').attr('href');
	    if(href.indexOf('?') <= 0){
	      $('#printBtn').attr('href', href + '?calendars=' + id_array.join(','));
	    }
	    else{
	      $('#printBtn').attr('href', href + '&calendars=' + id_array.join(','));
	    }
	  }
	});
    
  $('#listLink').click(function(e){
	  if($('#calendarList li a.strike').length != 0){
	    var id_array = new Array(); 
	    $('#calendarList li a:not(.strike)').each(function(){
        var calID = $(this).attr('id').slice(3);
	      id_array.push(calID);
      });
      var href = $('#listLink').attr('href');
	    if(href.indexOf('?') <= 0){
	      $('#listLink').attr('href', href + '?calendars=' + id_array.join(','));
	    }
	    else{
	      $('#listLink').attr('href', href + '&calendars=' + id_array.join(','));
	    }
	  }
	});
		
	$('.fc-button-prevYear, .fc-button-prev, .fc-button-next, .fc-button-nextYear').click(function(e) {
	  setDate();
	  e.preventDefault();
  });
    
  d = $('#calendar').fullCalendar('getDate');
  if ($.date.month == '') {
    var month = d.getMonth();
  } else {
    var month = $.date.month;
  }
  if ($.date.year == '') {
    var year = d.getFullYear();
  } else {
   var year = $.date.year; 
  }
	$('#calendar').fullCalendar('gotoDate',year,month);
  setDate();
  calendarSelectChange();
  
  //fire modal when linked from other page
  var url = location.href;  // entire url including querystring - also: window.location.href;
  var baseURL = url.substring(0, url.indexOf('?event', 14));
  var hashes = url.slice(url.indexOf('?') + 1);
  var cal = url.slice(url.indexOf('?cal') + 1);
  if (baseURL != "") {
    var calClass = $('#' + cal).attr('class');
    $.prettyPhoto.open(hashes+'&cal='+calClass+'&iframe=true&width=560&height=320' ,'','');
  }
}
//*****List Calendar Items**************************************************//
function listCalendar() {
  if ($('body#listview.calendar').length < 1) return false;
  $('#calendarList li a').click(function(e){
	  if($(this).hasClass('strike')){
		  $(this).removeClass('strike');
		  var calType = "#listView ul#eventlist li p." + $(this).attr('rel');
		  $(calType).parent('li').fadeIn();
		}
		else{
		  $(this).addClass('strike');
		  var calType = "#listView ul#eventlist li p." + $(this).attr('rel');
		  $(calType).parent('li').fadeOut();
		}
		e.preventDefault();
  });
		    
  $("a[rel^='prettyPhoto']").prettyPhoto({
		markup: '<div class="pp_pic_holder"> \
				<div class="pp_top"> \
					<div class="pp_left"></div> \
					<div class="pp_middle"></div> \
					<div class="pp_right"></div> \
				</div> \
				<div class="pp_content_container"> \
					<div class="pp_left"> \
					<div class="pp_right"> \
						<div class="pp_content"> \
							<div class="pp_fade"> \
								<a href="#" class="pp_expand" title="Expand the image">Expand</a> \
								<a class="pp_close" href="#">Close</a> \
								<div class="pp_loaderIcon"></div> \
								<div class="pp_hoverContainer"> \
									<a class="pp_next" href="#">next</a> \
									<a class="pp_previous" href="#">previous</a> \
								</div> \
								<div id="pp_full_res"></div> \
								<div class="pp_details clearfix"> \
									<p class="pp_description"></p> \
									<div class="pp_nav"> \
										<a href="#" class="pp_arrow_previous">Previous</a> \
										<p class="currentTextHolder">0/0</p> \
										<a href="#" class="pp_arrow_next">Next</a> \
									</div> \
								</div> \
							</div> \
						</div> \
					</div> \
					</div> \
				</div> \
				<div class="pp_bottom"> \
					<div class="pp_left"></div> \
					<div class="pp_middle"></div> \
					<div class="pp_right"></div> \
				</div> \
			</div> \
			<div class="pp_overlay"></div> \
			<div class="ppt"></div>'
	});
	
	function setDate() {
    var year = $.date.year;
    var month = $.date.month;
    $('#printBtn').attr('href','../../../../calendar/print/?year=' + year + '&month=' + month);
    $('#gridLink').attr('href','../../../../calendar/?month=' + month + '&year=' + year);
  }
      
	$('li.event p:not(.header)').live("click", function(e){
		//use $(this) to grab/pass info from the <a> attributes such as rel, title, or just make one up with jQuery
		//also grab info from FullCalendar using its API
		var cal = $(this).attr('class');
		var url = $(this).children('span').children('a').attr('href');
		url = url + '?cal=' + cal;
		$.prettyPhoto.open(url + '&iframe=true&width=550&height=300','','');
		e.preventDefault();
	});
		
	$('li.event p:not(.header)').each(function(){
	  var cal_id = $(this).attr('rel');
	  if(cal_id){
	    var cal_num = $('a#cal'+cal_id).attr('rel');
	    $(this).addClass(cal_num);
    }
	});
		
	$('a#subscribeBtn').live("click", function(e){
	  //use $(this) to grab/pass info from the <a> attributes such as rel, title, or just make one up with jQuery
		$.prettyPhoto.open('../../../ical/?iframe=true&width=550&height=447','','');
		e.preventDefault();
	});
    
  $('#printBtn').click(function(e){
	  if($('#calendarList li a.strike').length != 0){
	    var id_array = new Array(); 
	    $('#calendarList li a:not(.strike)').each(function(){
        var calID = $(this).attr('rel').slice(3);
	      id_array.push(calID);
      });
      var href = $('#printBtn').attr('href');
	    if(href.indexOf('?') <= 0){
	      $('#printBtn').attr('href', href + '?calendars=' + id_array.join(','));
	    }
	    else{
	      $('#printBtn').attr('href', href + '&calendars=' + id_array.join(','));
	    }
	  }
	});
  
  $('#gridLink').click(function(e){
	  if($('#calendarList li a.strike').length != 0){
	    var id_array = new Array(); 
	    $('#calendarList li a:not(.strike)').each(function(){
        var calID = $(this).attr('id').slice(3);
	      id_array.push(calID);
      });
      var href = $('#gridLink').attr('href');
	    if(href.indexOf('?') <= 0){
	      $('#gridLink').attr('href', href + '?calendars=' + id_array.join(','));
	    }
	    else{
	      $('#gridLink').attr('href', href + '&calendars=' + id_array.join(','));
	    }
	  }
	});
		
  $('a#closeCalendar').click(function(e){
    window.close();
    e.preventDefault();
  });
    
  $('.fc-button-prevYear, .fc-button-prev, .fc-button-next, .fc-button-nextYear').click(function(e) {
    if($('#calendarList li a.strike').length != 0){
      var id_array = new Array(); 
      $('#calendarList li a:not(.strike)').each(function(){
        var calID = $(this).attr('rel').slice(3);
        id_array.push(calID);
      });
      var href = $(this).attr('href');
      if(href.indexOf('?') <= 0){
        $(this).attr('href', href + '?calendars=' + id_array.join(','));
      }
      else{
        $(this).attr('href', href + '&calendars=' + id_array.join(','));
      }
    }
  });
  
	setDate();
  calendarSelectChange();
}

//*****Load all functions**************************************************//
$(document).ready(function(){
  replaceAlign();
  replaceTarget();
  strictNewWindow();
  initializeFlash();
  clearDefaultValue();
  extendFooter();
  rounded();
  gallerySelectChange();
  facultySelectChange();
  monthlyCalendar();
  listCalendar();
  populateDefaultValues();
});
//$(window).resize(function(){
//  extendFooter();
//});
