// Copyright 2013 Google Inc. All Rights Reserved.
// You may study, modify, and use this example for any purpose.
// Note that this example is provided "as is", WITHOUT WARRANTY
// of any kind either expressed or implied.

var adsManager;
var adsLoader;
var adDisplayContainer;
var intervalTimer;
var videoContent = null;
var adContainer = null;
var progressTimer;
var second = 0;
var bAdPlayed = false;
var contentDuration = -1;
var adUrl = null;

function resizeScreen() {
	console.log('[resizeScreen]');
	if(adsManager != null) {
		console.log('[resizeScreen] adsManager resize(' + document.body.clientWidth + 'x' + document.body.clientHeight + ')');
		adsManager.resize(document.body.clientWidth, 
						 document.body.clientHeight, 
						 google.ima.ViewMode.NORMAL);
	}
}

function setUpIMA() {
  console.log('[setUpIMA]');
  // Create the ad display container.
  createAdDisplayContainer();
  // Create ads loader.
  adsLoader = new google.ima.AdsLoader(adDisplayContainer);
  // Listen and respond to ads loaded and error events.
  adsLoader.addEventListener(
      google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED,
      onAdsManagerLoaded,
      false);
  adsLoader.addEventListener(
      google.ima.AdErrorEvent.Type.AD_ERROR,
      onAdError,
      false);

  // Request video ads.
  var adsRequest = new google.ima.AdsRequest();
  adsRequest.adTagUrl = adUrl;	
  // Specify the linear and nonlinear slot sizes. This helps the SDK to
  // select the correct creative if multiple are returned.
  adsRequest.linearAdSlotWidth = 400;//640;
  adsRequest.linearAdSlotHeight = 300;

  adsRequest.nonLinearAdSlotWidth = 400;//640;
  adsRequest.nonLinearAdSlotHeight = 150;

  adsLoader.requestAds(adsRequest);
  
  if(window != null) {
  	window.addEventListener('resize', resizeScreen);
  }
}

function createAdDisplayContainer() {
  // We assume the adContainer is the DOM id of the element that will house
  // the ads.
  adContainer = document.getElementById('adContainer');
  adDisplayContainer = new google.ima.AdDisplayContainer(
      								adContainer, videoContent);
      
  // Enable VPAID.    
  google.ima.settings.setVpaidMode(google.ima.ImaSdkSettings.VpaidMode.ENABLED);    
}

function playAds() {
  // Initialize the container. Must be done via a user action on mobile devices.
  // videoContent.load();
  console.log('[playAds]');
  
  if(bAdPlayed) {
  	console.log('[playAds] Already played...');
  	return;
  }
  adDisplayContainer.initialize();

  try {
    // Initialize the ads manager. Ad rules playlist will start at this time.
    console.log('[playAds] adsManager init(' + document.body.clientWidth + 'x' + document.body.clientHeight + ')');
    adsManager.init(document.body.clientWidth, 
    				document.body.clientHeight, 
    				google.ima.ViewMode.NORMAL);
    // Call play to start showing the ad. Single video and overlay ads will
    // start at this time; the call will be ignored for ad rules.
    adsManager.start();
    console.log('[playAds] adbManager started...');
    bAdPlayed = true;
    NexVASTPlayer.startAd();
  } catch (adError) {
    // An error may be thrown if there was a problem with the VAST response.
    console.log('[playAds] error:' + adError.toString());
    bAdPlayed = false;
    onContentResumeRequested();
  }
}

function onAdsManagerLoaded(adsManagerLoadedEvent) {
  // Get the ads manager.
  var adsRenderingSettings = new google.ima.AdsRenderingSettings();
  adsRenderingSettings.restoreCustomPlaybackStateOnAdBreakComplete = true;
  adsRenderingSettings.enablePreloading = true;
  
  // videoContent should be set to the content video element.
  adsManager = adsManagerLoadedEvent.getAdsManager(
      					videoContent, adsRenderingSettings);

  console.log('[onAdsManagerLoaded]');
  // Add listeners to the required events.
  adsManager.addEventListener(
      google.ima.AdErrorEvent.Type.AD_ERROR,
      onAdError);
  adsManager.addEventListener(
      google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED,
      onContentPauseRequested);
  adsManager.addEventListener(
      google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,
      onContentResumeRequested);
  adsManager.addEventListener(
      google.ima.AdEvent.Type.ALL_ADS_COMPLETED,
      onAdEvent);

  // Listen to any additional events, if necessary.
  adsManager.addEventListener(
      google.ima.AdEvent.Type.LOADED,
      onAdEvent);
  adsManager.addEventListener(
      google.ima.AdEvent.Type.STARTED,
      onAdEvent);
  adsManager.addEventListener(
      google.ima.AdEvent.Type.COMPLETE,
      onAdEvent);

  playAds();
    
  // Get Cue Points
  var arrCue = adsManager.getCuePoints();  
  var i;
  var cueNum = arrCue.length;
  console.log('[onAdsManagerLoaded] cue number : ' + cueNum);
  if(cueNum > 0) {
	  for(i=0; i<cueNum; i++) {
		console.log('[onAdsManagerLoaded] cue[' + i + '] ' + arrCue[i]);
	  } 
  } else {
    arrCue[0] = 0;   
  }
  
  NexVASTPlayer.setCuePoints(arrCue);
  	  
  console.log('[onAdsManagerLoaded] complete.');
}

function onAdEvent(adEvent) {
  // Retrieve the ad from the event. Some events (e.g. ALL_ADS_COMPLETED)
  // don't have ad object associated.
  var ad = adEvent.getAd();
  console.log('[onAdEvent] type : ' + adEvent.type);
  switch (adEvent.type) {
    case google.ima.AdEvent.Type.LOADED:
    	console.log('[onAdEvent] LOADED');

      // This is the first event sent for an ad - it is possible to
      // determine whether the ad is a video ad or an overlay.
      if (!ad.isLinear()) {
        // Position AdDisplayContainer correctly for overlay.
        // Use ad.width and ad.height.
        onContentResumeRequested();
      }

      break;
    case google.ima.AdEvent.Type.STARTED:
      // This event indicates the ad has started - the video player
      // can adjust the UI, for example display a pause button and
      // remaining time.
      console.log('[onAdEvent] STARTED');
      if (ad.isLinear()) {
        // For a linear ad, a timer can be started to poll for
        // the remaining time.
        intervalTimer = setInterval(
            function() {
              var remainingTime = adsManager.getRemainingTime();
            },
            300); // every 300ms
      }
      break;
    case google.ima.AdEvent.Type.COMPLETE:
      // This event indicates the ad has finished - the video player
      // can perform appropriate UI actions, such as removing the timer for
      // remaining time detection.
      console.log('[onAdEvent] COMPLETE');
      if (ad.isLinear()) {
        clearInterval(intervalTimer);
      }
      break;
    case google.ima.AdEvent.Type.ALL_ADS_COMPLETED:
      console.log('[onAdEvent] ALL_ADS_COMPLETED');
      NexVASTPlayer.completeAd();
      break;
  }
}

function onAdError(adErrorEvent) {
  // Handle the error logging.
  console.log('[onAdError]');
  console.log(adErrorEvent.getError().getMessage());
  
  onContentResumeRequested();
  
  if(adsManager != null) {
  	adsManager.destroy();
  }
}

function onContentPauseRequested() {
  console.log('onContentPauseRequested()');
  NexVASTPlayer.pauseContent();

  // This function is where you should setup UI for showing ads (e.g.
  // display ad timer countdown, disable seeking etc.)
  // setupUIForAds();
}

function onContentResumeRequested() {
  console.log('onContentResumeRequested()');
  NexVASTPlayer.resumeContent();
  
  // This function is where you should ensure that your UI is ready
  // to play content. It is the responsibility of the Publisher to
  // implement this function when necessary.
  // setupUIForContent();
}



// APIs which will be called from JAVA layer
function javaSetCurrentTime(time) {
	if(videoContent != null && time >= 0) {
		videoContent.currentTime = time;
		console.log('[javaSetCurrentTime] time : ' + time);
	}
}

function javaSetDuration(duration) {
	console.log('[javaSetDurtion] duration : ' + duration);
	contentDuration = duration;
	
}

function javaSetEndOfContent() {
	console.log('[javaSetEndOfContent]');
	// Tell the SDK that our content video
    // is completed so the SDK can play any post-roll ads.
	adsLoader.contentComplete();
}

function javaSetVASTUrl(url) {
	console.log('[javaSetVASTUrl] url : ' + url);
	adUrl = url;
}

function javaInit() {
  console.log('[init]');
  bAdPlayed = false;
  videoContent = document.getElementById('contentElement');
  setUpIMA();
}

