(function($){ //self calling anon-function to avoid global variable collisions



  /*jQuery outerHTML function for model*/
  $.fn.outerHTML = function() {
    return $('<div>').append( this.eq(0).clone() ).html();
  };

  var animating = false;
  var model = [];
  var currentIndex = -1;//will be initialize on load

  var interval;
	// var cycle_timeout_ref;
  var shouldCycle = true;

  function stopSlides()
  {
    shouldCycle = false;
    clearInterval(interval);
		// clearTimeout(cycle_timeout_ref);
  }

  /*set up click and live functions*/
  $("#pagination a.prev-button").live('click',
    function() {
      stopSlides();
      var selectedIndex = currentIndex; 
      if( selectedIndex <= 0)
        return false;

      if(!changeSlide(selectedIndex - 1))
        return false;
 
      selectedIndex--;
      $('a.pager').removeClass('inpage');
      $('a.pager:eq(' + selectedIndex + ')').addClass('inpage');

      $("#pagination a.prev-button img").attr("src", "/template/css_files/images/arrow_lft.png").parent().removeClass("arrow-disable").attr("title", "prev");
      $("#pagination a.next-button img").attr("src", "/template/css_files/images/arrow_rht.png").parent().removeClass("arrow-disable").attr("title", "next");

      if(selectedIndex === 0)
      {
        $("#pagination a.prev-button img").attr("src", "/template/css_files/images/arrow_lft_ov.png").parent().addClass("arrow-disable").attr("title", "");
      }
      if(selectedIndex  == model.length - 1)
      {
        $("#pagination a.next-button img").attr("src", "/template/css_files/images/arrow_rht_ov.png").parent().addClass("arrow-disable").attr("title", "");
      }      
    }
  );

  $("#pagination a.next-button").live('click',
    function() {
      stopSlides();
      cycleNext();
    }
  );

  $("#pagination a.pager").live('click', function() {
    var selectedIndex = parseInt($(this).html(), 10) -1;
   stopSlides();

    if(  !changeSlide( selectedIndex ) ) //update slide to the index
      return false;

    /*undate active page*/
    $('a.pager').removeClass('inpage');
    $(this).addClass('inpage');
    /*enable disable arrows*/

    $("#pagination a.prev-button").html('<img width="8" height="16" src="/template/css_files/images/arrow_lft.png">').removeClass("arrow-disable").attr("title", "prev");
    $("#pagination a.next-button").html('<img width="8" height="16" src="/template/css_files/images/arrow_rht.png">').removeClass("arrow-disable").attr("title", "next");

    if(selectedIndex === 0)
    {
      $("#pagination a.prev-button").html('<img width="8" height="16" src="/template/css_files/images/arrow_lft_ov.png">').addClass("arrow-disable").attr("title", "");
    }

    if(selectedIndex == model.length - 1)
    {
      $("#pagination a.next-button").html('<img width="8" height="16" src="/template/css_files/images/arrow_rht_ov.png">').addClass("arrow-disable").attr("title", "");
    }

  });

  $(".tabs ul li a").live('click', function() 
  {
    stopSlides();
    if(animating)
      return false;
    animating = true;
    $(".tabs ul li a").removeClass("downarrow");
    $(".tabs ul li a").addClass("sidearrow");
    $(this).addClass("downarrow");
    $(this).removeClass("sidearrow");
    var showTab = $(this).attr("href").replace("#", "");
    $(".tab-content").fadeOut(0);
    $(".tab-content").removeClass("showtab");
	$("#rightstrip #" + showTab).show(0, function(){ animating = false; });
    
    $("#rightstrip #" + showTab).addClass("showtab");
    return false;
  });

	// setup clickable thumbnail action
	
	$('#leftstrip a.clickableVideoStill').live('click', function(evt) {
		evt.preventDefault();
		
		var xml;

		// check for valid current index
		if (currentIndex >= 0 && currentIndex <= model.length - 1) {
			// stop slides
			stopSlides();

			// swap out for brightcove player
			xml = model[currentIndex];
			$("#leftstrip").html(processReplaceCalloutHTMLElement($("#tabs-1 .replaceCallout", xml).html()));

		}
		
	});
	
	


  /*onload*/
  $(function(){
    //build the data used for the interface one time.
    buildModel();

		// triggerCycleLoadedOnCompleteLoad();
  });

  function cycleNext()
  {
      var selectedIndex = currentIndex;
      if( selectedIndex == model.length - 1)
        return false;

      if(!changeSlide(selectedIndex + 1))
        return false;

      selectedIndex++;
      $('a.pager').removeClass('inpage');
      $('a.pager:eq(' + selectedIndex + ')').addClass('inpage');

      $("#pagination a.prev-button img").attr("src", "/template/css_files/images/arrow_lft.png").parent().removeClass("arrow-disable").attr("title", "prev");
      $("#pagination a.next-button img").attr("src", "/template/css_files/images/arrow_rht.png").parent().removeClass("arrow-disable").attr("title", "next");

      if(selectedIndex === 0)
      {
        $("#pagination a.prev-button img").attr("src", "/template/css_files/images/arrow_lft_ov.png").parent().addClass("arrow-disable").attr("title", "");
      }

      if(selectedIndex  == model.length - 1)
      {
        $("#pagination a.next-button img").attr("src", "/template/css_files/images/arrow_rht_ov.png").parent().addClass("arrow-disable").attr("title", "");
      }

			// trigger the cycleLoaded event
			// triggerCycleLoadedOnCompleteLoad();
  }

// function triggerCycleLoadedOnCompleteLoad() {
// // wait for the video to load, then trigger the cycle
// $('body').bind('videoLoaded', function(evt) {
// $('body').unbind(evt);
// 
// // console.log('videoLoaded triggered evt.experienceID=',evt.experienceID)
// $('body').trigger('cycleLoaded');
// });
// }

  function buildModel()
  {
		
	var data = $("#spotlightStories");
        var pagecount = 1;

        $('.story', data).each(function(index,value){
          //push story to model
          model.push($(this).outerHTML());
          //update view
          if (pagecount == 1)
            $("#pagination li:nth-child(" + $('#pagination li').length + ")").before("<li><a class='inpage pager' href='javascript:void(0);'>" + pagecount + "</a></li>");
          else
            $("#pagination li:nth-child(" + $('#pagination li').length + ")").before("<li><a class='pager' href='javascript:void(0);'>" + pagecount + "</a></li>");
            
          pagecount++;
            
        });

        pagecount--;
        //page ready to display
        changeSlide(0,{ 'hideSlide' : false });
        if(shouldCycle)
        {
          interval = setInterval( function(){ if(currentIndex >= model.length - 1){ currentIndex = -1; } cycleNext(); } , 5000 ) ;
					// $('body').bind('cycleLoaded', function() {
					// cycle_timeout_ref = setTimeout(function() {
					// if (currentIndex >= model.length - 1) { currentIndex = -1; }
					// cycleNext();
					// }, 5000);
					// });
        }


  }

  function changeSlide(index, options)
  {
		//private method -- keep in changeSlide
		function loadData()
		{
			//reset to challenge tab
			$(".tabs ul li a.downarrow").removeClass('downarrow').addClass('sidearrow');
			$(".tabs ul li a[href='#tabs1']").removeClass('sidearrow').addClass('downarrow');

			var showTab = "tabs1";
			$(".tab-content").removeClass("showtab");
			$("#rightstrip #" + showTab).addClass("showtab");
			//end reset
			//loadData from model
			var xml = model[index];
			//index value from previous closure
			currentIndex = index;

			//header content
			var path = $("#header-impact").css("background-image");
			path = path.substring(0, path.indexOf("images")).replace('"', '');
			var bgimg = $(".bground img", xml).attr("src");
			// the following line does not work for images stored in the /media/image directory
			// bgimg = path + bgimg.substring(bgimg.indexOf("images")) + ')';
			// DW: replaced with this:
			bgimg = bgimg.length ? 'url("' + bgimg + '")': '';

			$("#header-impact").css("background-image", bgimg);
			$("#header-history").css("background-image", bgimg);

			$("#leftstrip").html(buildReplaceCalloutHtml(xml));

			// activate flowplayer for a video in callout
			// var video_link = $("#leftstrip a.awc_video");
			// if (video_link.is('*')) {
			// // make slide rotation stop if video is played
			// video_link.bind('click', function() {
			//		 stopSlides();
			// });
			//
			// var div_id = video_link.attr('id');
			// _AWCfp.activate(div_id, div_id);
			//
			// }

			//Change copy out
			$("#h1-content").html($(".storyContent h1", xml).html());

			//Change headline out
			$("#h1-content").attr('style', $('h1.hdlHome', xml).attr('style'));
			$("#h2-content").html($(".storyContent h2", xml).html());
			$("#h3-content").html($(".storyContent h3", xml).html());
			// $("#readmore-content a").attr("href", $("#tabs-1 a:first", xml).attr("href") );
			$("#readmore-content a").attr("href", $("h1.hdlHome a:first", xml).attr("href"));
			$("#rightstrip .tabs li a[href='#tabs1']").html($("div.tabs li a:eq(0)", xml).html());
			$("#rightstrip .tabs li a[href='#tabs2']").html($("div.tabs li a:eq(1)", xml).html());
			$("#rightstrip .tabs li a[href='#tabs3']").html($("div.tabs li a:eq(2)", xml).html());
			$("#rightstrip #tabs1").html($("div.tabs div#tabs-1", xml).html());
			$("#rightstrip #tabs2").html($("div.tabs div#tabs-2", xml).html());
			$("#rightstrip #tabs3").html($("div.tabs div#tabs-3 #interviews", xml).html());

			//Show data
			$('#header-impact, #leftstrip, #h2-content, #h1-content').show(0,
			function() { $('#h3-content, #readmore-content').show(0,
				function() { $('.tabs ul').show(0,
					function() { $('.showtab').show(0, 
						function() { animating = false; });
					});
				});
			});

		} // end loadData
	
    //ignore user feedback if we are currently animating
    if(animating || index == currentIndex)
      return false;

    animating = true; //begin animating...lock out other user requests

    //use passed in options or defaults if not present
    options = options || { };
    options.hideSlide = options.hideSlide || true; //hide previous slide if setting not overridden 

    //hide
    if(options.hideSlide)
    {
      $('.showtab, .tabs ul, #readmore-content,#h3-content, #h1-content, #h2-content, #leftstrip, #header-impact').hide();
      loadData();
    }
    else
    {
      loadData();
    }
  
    return true;
  }

	function buildReplaceCalloutHtml(xml) {

		// if there is a thumbHref div, then just build a clickable image
		var 
			thumb_href_data_div = $("#tabs-1 .replaceCallout div.thumbHref", xml),
			href = thumb_href_data_div.data('thumbhref'),
			out_html = '';

		if (href !== undefined && href.length) {
			out_html = '<a class="clickableVideoStill" href="#"><img src="'+href+'"/></a>';
		} else {
			// just use the contents of replaceCallout
			out_html =  processReplaceCalloutHTMLElement($("#tabs-1 .replaceCallout", xml).html());
		}
		
		
		return out_html;
		
	}

  
	var modExp, bcExp, modVP;
	window.onTemplateLoaded = function(experienceID) {
	  // console.log('onTemplateLoaded experienceID='+experienceID+'')
	
    bcExp = brightcove.getExperience(experienceID);
		modExp = bcExp.getModule(APIModules.EXPERIENCE);
    modVP = bcExp.getModule(APIModules.VIDEO_PLAYER);


		modExp.addEventListener(BCExperienceEvent.CONTENT_LOAD, function(evt) {
		  // console.log('CONTENT_LOAD fired experienceID='+experienceID+'');
		
			// always play immediately when loaded
			modVP.play();

			// say that the content is loaded
			// var custom_event = jQuery.Event("videoLoaded");
			// custom_event.experienceID = experienceID;
			// $('body').trigger(custom_event);
		});
		
		
		modVP.addEventListener(BCMediaEvent.PLAY, function(evt) {
			// console.log('BCMediaEvent.PLAY fired');

			// playing a video - stop slides
			stopSlides();
		});
	};
	

	////////////////////////////////
	// DEBUG //
	// temporary css file
	// $(function() {
	// 	$('head').append('<link rel="stylesheet" href="/media/css/BChome.css" type="text/css" />');
	// });
	//  END DEBUG //
	////////////////////////////////
	
	
	function isIPad() { return (navigator.platform.indexOf("iPad") != -1); }
	function isIPod() { return ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))); }
	function processReplaceCalloutHTMLElement(in_html_text) {
		var
			out_html_text = in_html_text,
			is_ipad = isIPad() || isIPod();
		
		// swap out the player id if this is an iPad
		if (is_ipad) {
			// swap out the player id
			// 913861299001 = built-in
			out_html_text = out_html_text.replace(/playerID=(\d+)/i,'playerID=913861299001');
		}
		
		return out_html_text;
	}
	
})(jQuery); //pass the current jQuery context scope as $



