var videoDomain = 'video.foxbusiness.com';

String.prototype.ucFirst = function () {
    return this.substr(0,1).toUpperCase() + this.substr(1,this.length);
};


/** NEW VIDEO PLAYER FUNCTIONS **/
/*
playShowsVideo();
playShowsVideoAttempt();
setSmoothScroll(); -> setSlideshowVideoItems();
*/

function playShowsVideo(videoId,autoplay) {
  // it plays on page load
  holderElm = $(".video-player-wrapper");
  var id = "videoid:g"+videoId; // g for grab video
  var config = {
    holder: holderElm,
    type: "video",
    id: id,
    cssClass: "video-player-format",
    autoplay: true,
    callbacks: { // define callback functions
      feedLoaded: function(data) { updatePageContent(data); }, // if new feed is loaded
      dataChanged: function(data) { updatePageContent(data); }, // if current data was changed
      videoEnded: function(controls) {
        if (controls) { // html5 controls
          controls.jumpTo(id,0);
          controls.pause(id);
        }
        //playNextSlideshowVideo(videoId);
      }
    }
  }

  $(document).ready(function(){
    videoPlayer.render(config);
    /*
    videoPlayer.getFeed({
      id: id,
      callback: function(data) {
        console.log(data);
      }

    });
    */
  });

}

function playNextSlideshowVideo(id) {
	id = id || false;
	var list = $("ul#accordion .slideshow > ul"),
		items = list.children(),
		first = list.children(":first"),
		selected = list.children(".selected:first"),
		selData = returnItemData(selected.find("a:first"));
	
	function trigger(target) {
		target = target || false;
		if (target) {
			target = target.next();
			if (target.size()===0) { target = first; } // if no next item, default to first
		} else {
			target = first;
		}
		
		var data = returnItemData(target.find("a:first"));
		
		pageVars.videoId = data.videoId;
		pageVars.playlistId = data.playlistId;
		document.location.hash = data.href; // add video link as hash
		
		items.removeClass("selected");
		target.addClass("selected");
		playShowsVideo(data.videoId,true);
	}
	
	function findId() {
		var elm = false;
		items.find("a:first").each(function(){
			var data = returnItemData($(this));
			if (data.videoId===id) { elm = $(this); return; }
		});
		trigger(elm);
	}
	
	if (id && selData.videoId===id) {
		trigger(selected);
	} else if (id && selData.videoId!==id) {
		findId();
	} else {
		trigger(selected);
	}
}

function playNextVideo() {
	var videoId = (pageVars && pageVars.videoId) ? pageVars.videoId : false;
	playNextSlideshowVideo(videoId);
}

function returnItemData(aTag) {
  var href = oFoxVideo.cleanHref(aTag.attr("href"));
  var playlistId = oFoxVideo.extractVideoId(href);
  var videoId = oFoxVideo.extractVideoId(href);

  var obj = {
    href: href,
    playlistId: playlistId,
    videoId: videoId
  };

  return obj;
}

function playShowsVideoAttempt(videoId,autoplay) { // DEPRECATED - video player object in video player prototype
  playShowsVideo(videoId,autoplay);
}

function setSlideshowVideoItems(videoItems) {
  videoItems = videoItems || false;
  if (!videoItems) { return false; }

  videoItems.each(function(i){
    var item = $(this);

    item.find("a:first").each(function(){
      var data = returnItemData($(this));

      if (!item.data("itemVideoId")) { // set this for reference on playNexSlideshowVideo()
        item.data("itemVideoId",data.videoId);
      }
    });


    item.find("a").click(function(){
      var data = returnItemData($(this));

      pageVars.videoId = data.videoId;
      pageVars.playlistId = data.playlistId;

      videoItems.removeClass("selected");
      $('li[class=""]').removeAttr("class");
      item.addClass("selected");
      document.location.hash = data.href;
      playShowsVideo(data.videoId,true);
      return false;

    });

  });

}

function updatePageContent(oVideo) {
  // page elements
  var article = $(".article");
  article.find("h2").html(oVideo.title);
  article.find(".date").html(oVideo.creationDate);
  article.find("p.description").html(oVideo.description);
  $('#embed-input').val('<script type="text/javascript" src="http://' + videoDomain + '/embed.js?id=' + pageVars.videoId + '&w=400&h=249"></script><noscript>Watch the latest video at <a href="http://video.foxnews.com/">FOXNews.com</a></noscript>');

  // share this
  shareInfo.title = oVideo.title;
  shareInfo.summary = oVideo.shortDescription;
  shareInfo.url = 'http://' + videoDomain + '/v/' + pageVars.videoId + '/' + oFoxVideo.cleanTitle(shareInfo.title) + '?playlist_id=' + pageVars.playlistId;
  shareInfo.icon = 'http://' + videoDomain + oFoxVideo.cleanImageUrl(oVideo.thumbnail);
}


/** NEW VIDEO PLAYER FUNCTIONS - END **/

function transcriptUpdateSelect(obj, value) {
  jQuery.ajax({
        type: 'POST',
        url: Drupal.settings.base_url+'/transcript_category/'+value,
        success: function(data){
          jQuery('#latest-transcripts').html(data);
        }
  });
  jQuery('.dropdown.current-value').html($('#transcript-select :selected').text());
  var datedisplayed = new Date('01 '+jQuery('.turn-me-into-datepicker h2').html());
  transcriptUpdateAvailableDays((datedisplayed.asString()).substring(6,10),(datedisplayed.asString()).substring(3,5));
}

function transcriptUpdateAvailableDays(year,month) {
  jQuery.getJSON(Drupal.settings.base_url+'/transcript_exists/'+year+month+'/'+$('#transcript-select').val()+'?callback=?',
    function(data) {
      $('.current-month').addClass('disabled');
      jQuery.each(data, function(i, item) {
        $('.dp-calendar td.current-month').each(
        function() {
          if (Number($(this).text()) == item) {
            $(this).removeClass('disabled');
          }
        });
      });
  });
}

jQuery.fn.exists=function(){return jQuery(this).length>0;}

function createCarouselButtons(obj) {
    var list = []
    for (var x=1;x<=obj.batch.max;x++) {
      list.push('<li><a href="#">&nbsp;&nbsp;&nbsp;</a></li>');
    }
    return list.join('');
}

//for links with hash
function scrollToCarouselItem(id) {
  id = id || false;
  if (!id) { return false; }
  var loop = 100;

  $("#accordion .section-mod").each(function(){
    var carousel = $(this);
    var children = carousel.find("ul:first").children();
    var title = carousel.children().filter("h2.title:first");

    children.each(function(){
      var item = $(this);
      if (item.find("a[href*='/v/"+id+"/']:first").size()>0) {
        children.removeClass("selected");
        var n = 0;
        function trigger() {
          if (carousel.data("isCarouselLoaded")) {
            if (!title.hasClass("active")) { title.trigger("click"); } // trigger accordion if not the opened accordion
            item.trigger("focusCarouselOnItem"); // trigger bind item from carousel
            item.addClass("selected"); // selected
          } else if (n<loop) {
            n++;
            setTimeout(function(){ trigger(); },10);
          }
        }
        trigger();
      }
    });

  });
};


$(document).ready(function(){
  $.ad.init();
  
  /*** External Links ***/
  (function(){
	 var wOpen = function(elm,force) {
	   if (!elm.data("relSet")) {
		  elm.data("relSet",true).click(function(){ 
			 var win = $(window), props = "width="+win.width()+",height="+win.height()+",location=1,resizable=1,scrollbars=1,menubar=1,status=0,titlebar=1,toolbar=1";
			 window.open($(this).attr("href"),"_blank",(force) ? props : null); 
			 return false; 
		  });
	   }
	 };
	
	 // force window open first
	 $("#nav-related a[rel='external']").each(function(){ wOpen($(this),true); });

	 // the rest of the externals
	 $("a[rel='external']").each(function(){ wOpen($(this)); });

  }());
  
  
  // video player
  if (Drupal.settings.videoplayer) {
    if (document.location.hash!='') {
      pageVars.playlistId = document.location.hash.substring(1).split('playlist_id=')[1];
      pageVars.videoId = document.location.hash.substring(1).split('/')[2];
    }

    var slideshowVideos = $("ul#accordion").find(".slideshow ul").children();
    setSlideshowVideoItems(slideshowVideos);
    slideshowVideos.filter(":first").addClass("selected");

    // clipboard copy app
    if (jQuery('#embed-input').length >= 1) {
      clip = new ZeroClipboard.Client();
      clip.setHandCursor( true );
      clip.glue('embed-but');
      clip.addEventListener( 'mouseDown', function(client) {
        clip.setText($('#embed-input').val());
      });
    }
  }

  /*** Twitter ***/
  if (jQuery('#twitter_module').length >= 1) {
    var url = 'http://twitter.com/status/user_timeline/'+jQuery('#twitter_id').val()+'.json?count=3&callback=?';
    jQuery.getJSON(url,
     function(data){
      var w_names = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
      var m_names = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
      var html = '';
      jQuery.each(data, function(i, item) {
        var profile_picture = '';
        var values = item.created_at.split(" ");
        time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
        var post_date = new Date(Date.parse(time_value));
        post_time = (post_date.getHours() > 12) ? (post_date.getHours()%12)+'PM' : post_date.getHours()+'AM';
        html += '<li><blockquote><p>'+item.text.ucFirst()+'</p></blockquote><p class="time">'+post_time+' '+w_names[post_date.getDay()]+', '+m_names[post_date.getMonth()]+' '+post_date.getDate()+', '+post_date.getFullYear()+'</p></li>';
      });
      jQuery("#twitter_module .content ul").html(html);
      jQuery('#twitter_module .content ul li:first-child').addClass('first');
      jQuery('#twitter_module').show();
     });
  }

	// omniture tracking 
	$(document).ready(function(){
		$.loadAttempt({
			maxAttempts: 30, // interval
			timeout: 500, // in ms
			callback: {
				check: function() {
					return (typeof twttr!=="undefined") ? true : false;
				},
				success: function() {
				  	twttr.events.bind('click', function(event){
						$.ad.track({ "twitter": {"click":true} });
				  });
				}
			}
		});		
	})	

  /*** Live Events Schedule ***/
  if ((jQuery('#stream-image').val() || "").length >= 1) {
    jQuery.getJSON($('#show-feed').val()+'?callback=?',
      function(data) {
      var islive = false;
      if (data != undefined) {
        jQuery.each(data, function(i, item) {
          if (item.show_title == $('#show-title').val()) {
          var Start = new Date();
          var End = new Date();
          Start.setMinutes(Start.getMinutes() + 5);
          End.setMinutes(End.getMinutes() - 5);
            if (((new Date(item.episode_start_time)) < Start) && ((new Date(item.episode_end_time)) > End)) {
              islive = true;
            }
          }
        });
      }
      if ($('#show-title').val() && !islive && jQuery('#stream-image').val()) {
        jQuery('#section-video .video-player-wrapper').html('<img src="'+Drupal.settings.base_url+'/'+jQuery('#stream-image').val()+'">');
      }
    });
  }

  /*** IE6 Selector Fix ***/
  //$(".description").after('<div class="br"></div>');
  //$(".br + *").css("paddingTop", "5px");

  /*** List 2 ****/
  $(".list-2,.list-features").each(function(i) {
      var $list = $(this).find(".list");

      $list.wrap('<div class="list-encapsulator"></div>');
  });

  /*** Apps ***/
  $(".apps ul").each(function(){
    var ul = $(this);
    var item = ul.find("li");
    var size = item.size();

    ul.find("li:nth-child(even)").addClass("alt");
    ul.find("li:last").addClass("last-type");

    if (size%2===0) {
      ul.find("li:nth-child(" + (size-1) + ")").addClass("last-type");
    }
  });

  /*** Tabbed Mod ***/
  $(".tabbed-mod").each(function(i) {
    var $tabs = $(this);
    var $li = $tabs.find(".content ul.controller").children();
    var $div = $tabs.find(".content").children().filter(".section");

    $li.each(function(i) {
      $("a",this).click(function() {
        var $this = $(this);

        $li.removeClass("active");
        $this.parent().addClass("active");

        $div.removeClass("active");
        $($div[i]).addClass("active");

        return false;
      });

    });
  });


  /*** Date Picker ***/
  if ($("div").is(".turn-me-into-datepicker")) {
    $('.turn-me-into-datepicker')
    .datePicker({inline:true,startDate: '01/01/2000',endDate: (new Date()).asString()})
    .bind(
      'dateSelected',
      function(e, selectedDate, $td)
      {
        var vocab_id = ($('#transcript-select').length >= 1) ? $('#transcript-select').val() : 1;
        jQuery.ajax({
          type: 'POST',
          url: Drupal.settings.base_url+'/transcript_url/'+((new Date(selectedDate)).asString('yyyymmdd'))+'/'+vocab_id,
          success: function(data){
            window.location = Drupal.settings.base_url+'/'+data;
          }
        });
      }
    );
    transcriptUpdateAvailableDays(((new Date()).asString()).substring(6,10),((new Date()).asString()).substring(3,5));

    $('.turn-me-into-datepicker')
    .datePicker({inline:true})
    .bind(
      'dpMonthChanged',
      function(e, displayedMonth, displayedYear)
      {
        $('.current-month').addClass('disabled');
        var displayedMonth = (++displayedMonth < 10) ? '0'+displayedMonth : displayedMonth;
        transcriptUpdateAvailableDays(displayedYear,displayedMonth);
      }
    );

  }


  /*** Start Attribute ***/
  var count = 1;

  $("ol.list").each(function(i) {
    if (i == 0) {
      count = $("li", this).size() + 1;
    }

    else {
      $(this).attr("start", count);
      count = count + $("li", this).size();
    }
  });

  /*** External Linking ***/
  
  if ($(".format-1").css("float") == "left") {
    $(".format-1").find(".description").css("margin-left","127px");
  }

  /*** Accordion ***/
  $("#accordion .title").append('<span class="indicator"></span>');

  $("ul[id='accordion']").jfoxAccordion({
    duration: 400,
    speed: "fast",
    activeClass: "active"
  });

  /*** Carousel ***/
  $("#accordion .section-mod, #photo-slide-show .section-mod").each(function(i) {

    var carousel = $(this);
      var config = {
      auto: { set:false,speed:3000 }, // auto scroll
      slide: 'horizontal', // horizontal or vertical
      scroll: 3, // number of items to scroll per event
      show: 4, // items shown
      speed: "slow", // scroll speed
      rotate: true, // rotate back to star if end
      eventCallback: function(obj) { // callback function for all carousel events

        if (obj.event=='init') {
          carousel.data("isCarouselLoaded",true);
          $(".content ol:first",carousel).html(createCarouselButtons(obj)); // create the buttons
          $(".content ol li:first",carousel).addClass("active"); // set the first one as always active
          if (obj.batch.max == 1) { //remove buttons and controls if less than one page
            carousel.children('.content').children('.sectioning').remove();
            carousel.children('.content').children('.controls').remove();
          }
        } else {
          $("ol li",carousel).each(function(i){ // button highlight listener
            if (i+1 == obj.batch.current) {
              $(this).addClass("active");
            } else {
              $(this).removeClass("active");
            }
          });
        }
      },
      controlsCallback: function(control) { // callback to set up controls

        $("ol li a",carousel).each(function(i){ // buttons links
          $(this).click(function(){
            control.stopAutoScroll();
            control.scrollToBatch(i+1);
            return false;
          });
        });

        $(".prev",carousel).click(function(){ // previous link
          control.stopAutoScroll();
          control.slide('prev');
          return false;
        });

        $(".next",carousel).click(function(){ // next link
          control.stopAutoScroll();
          control.slide('next')
          return false;
        });

        // set up event listener - focus
    carousel.find("div.slideshow ul:first").children().each(function(i){
      $(this).bind("focusCarouselOnItem",function(){
        control.stopAutoScroll();
        control.scrollToItem(i+1);
        return false;
      });
    });

      }
    };

    /*** Photo Slideshow Mod ***/
    if (carousel.parent().hasClass("photo-slide-mod")) {
      config.scroll = 7;
      config.show = 7;
  }

    $(".photo-slide-mod").each(function(){
    var slide = $(this);
    var height = slide.find("div.content").innerHeight();
    var width = slide.find("div.content").innerWidth();

    slide.find('.slideshow ul li ul li a').click(function(){

        var anchor = $(this).attr("href");
        $('.photo-zoom-wrapper .full-size').attr("src",anchor);
        if (carousel.parent().hasClass("photo-slide-mod")) {
          var newImg = new Image();
          newImg.onload = function() {
            $('.photo-zoom-wrapper .photo-title').width(this.width);
            $('.photo-zoom-wrapper').show();
              //center height
             var negativeHeight = height - newImg.height;
              var topOffset = negativeHeight / 2;
              $('.photo-zoom-wrapper').css("top",topOffset);
              //center width
            var negativeWidth = width - newImg.width;
              var leftOffset = negativeWidth / 2;
            $('.photo-zoom-wrapper').css("left",leftOffset);

          };
          newImg.src = anchor;
        }
        $('.photo-zoom-wrapper .photo-title').text($(this).text());
        return false;
        });
        $('.photo-zoom-wrapper #zoom-close').click(function(){
          $('.photo-zoom-wrapper').hide();
         });
  });


    carousel.jfoxCarousel(config);


    var listenerConfig = {
    elm: carousel,
    moveSensitivity: 15,
    eventsCallback: {
      touchmoveMoveOnce: function(direction,moveProperties,rawEvent) {
        // move callback - sensitivity
        var directions = direction.join("|");

        if (directions.indexOf("left")>-1) {
          carousel.find(".next").click();
        }

        if (directions.indexOf("right")>-1) {
          carousel.find(".prev").click();
        }

      }
    }
  };

    touchEventListener.append(listenerConfig);

  });

  // "iframe" issue workaround
  touchEventListener.reTriggerListener();

  /*** Gerri's Two Cents Slideshow ***/
  $('#feature-slider').each(function(){
  var target = $("#feature-slider");
  var controlElm = target.find("p.controls");
  var sectionElm = target.find(".slideshow ul");

  var prev = controlElm.find(".prev");
  var next = controlElm.find(".next");

  var currentNumElm = target.find(".current-num");
  var maxNumElm = target.find(".max-num");

  function setItems(max) {
    var html = [];
    for (var x = 0; x < max; x++) { html.push('<li><a href="#">&nbsp;</a></li>'); }
    sectionElm.html(html.join(""));
  }

  var config = {
    auto: false, // auto scroll
    slide: 'horizontal', // horizontal or vertical
    scroll: 2, // number of items to scroll per event
    show: 2, // items shown
    speed: "slow", // scroll speed
    rotate: false, // rotate back to star if end
    eventCallback: function(obj) { // callback function for all carousel events
      var start = obj.start;
      var end = obj.end;

      //if (obj.event==="init") { setItems(obj.batch.max); }
      sectionElm.find("> li").each(function(i){
        $(this).toggleClass("focus",(obj.batch.current===(i+1)));
      });

      currentNumElm.text(obj.batch.current);
      maxNumElm.text(obj.batch.max);

      if (obj.batch.current===obj.batch.max) {
        next.addClass("inactive-next");
      } else {
        next.removeClass("inactive-next");
      }

      if (obj.batch.current===1) {
        prev.addClass("inactive-prev");
      } else {
        prev.removeClass("inactive-prev");
      }
    },
    controlsCallback: function(control) { // callback to set up controls
      controlElm.find(".prev").click(function(){ // previous link
        control.stopAutoScroll();
        control.slide("prev");
        return false;
      });

      controlElm.find(".next").click(function(){ // next link
        control.stopAutoScroll();
        control.slide("next");
        return false;
      });

    }
  };

  target.jfoxCarousel(config);
  })
  $('.post .content, .node .content').each( function(){
		var content = $(this);		
		var imgs = content.find('img');
		
		
		imgs.each(function(){	
			
			var thisImg = $(this);
			var thisImgAlt = thisImg.attr('alt');
			var parent = thisImg.parent();
			
			if(thisImgAlt != "" && thisImgAlt != "Quantcast"){
				if(parent.hasClass('img_link')){
		
					parent.wrap('<div class="hmedia fn" style="width: '+ (thisImg.attr('width')+10)+'px; float:left" >');
					parent.after('<p>' + thisImgAlt + '</p>');
				
				}
				else{
					thisImg.wrap('<div class="hmedia fn" style="width: '+ (thisImg.attr('width')+10)+'px;" float:"left" >');
					thisImg.after('<p>' + thisImgAlt + '</p>');					
				}
				thisImg.addClass('alignleft');
			}	
		});
	});
});

