// init variables
var switchFunction = null;
var counter = 0;
var playing = true;
var inTransition = false;

jQuery(document).ready( function($) {

  // display loading
  $('.carousel .slide').html('<div class="loading"></div>');

  // apply opacity
  $('.carousel ul.manualnav a.active, .front .carousel-holder #front-menu').css({'opacity': 0.85});
  
  // create manual navigation if more than one item
  if (nodes.length > 1) {
    // shuffle node
    nodes = $.randomize(nodes);

    var strNav = '';
    for (var i=0; i < nodes.length; i++) {
      strNav += '<li><a class="item' + i + '" href="#' + i + '"></a></li>';
    };
    strNav += '<li><a href="playcontrol" class="playcontrol playing"></a></li>';
    $('.carousel .slide').after('<ul class="manualnav">' + strNav + '</ul>');
    $('.carousel ul.manualnav').find('li:first a').addClass('active');
  }
  
  // start auto slideshow if more than one item
  if (nodes.length > 1) {
    
    var img = new Image();
    jQuery(img)
      .load(function () {
        
        jQuery('.carousel .slide a.slide-img').remove();
        
        var css = 'slide-img';
        var target = '';
        if(nodes[0].url.substr(0,7) == 'http://' || nodes[0].url.substr(0,7) == 'https://') {
          css = css + ' externa-link';
          target = 'target="_blank"';
          target = '';
        }
        var label = 'carousel_slide_1_'+ nodes[0].url;
        var link = jQuery('<a class="' + css + '" href="' + nodes[0].url + '"' +
                   'onclick="_gaq.push([\'_trackEvent\',\'banner\',\'click\',\''+label+'\']);" ' + target + '></a>');
        link.append(jQuery(this));
        jQuery('.carousel .slide').prepend(link);
        jQuery('.carousel .slide .loading').remove();
        setTimeout('switchSlide()', 8000);
      })
      .attr('src', nodes[0].image)
      .attr('alt', nodes[0].title);
      
  }

  // manual navigation
  $('.carousel .manualnav a').click(function(e){
    e.preventDefault(); 
    if ($(this).hasClass('playcontrol')) { // user clicked on playcontrol link
      if (playing) {
        stopPlaying();
      }
      else {
        startPlaying();
      }
    }
    else { // user clicked on specific slide link
        
      if (inTransition) {
          return false;
      } else {
          inTransition = true;
      }
        
      var hrefValue = $(this).attr('href');
      var hashPos = hrefValue.indexOf('#') + 1; // workaround because IE gets absolute URL from href
      newIndex = hrefValue.substr(hashPos);

      //alert(hashPos);
      newIndex = hrefValue.substr(hashPos);
      // only do sth if user clicked on non-active tab and currently a different slide than index is shown
      if (!$(this).hasClass('active') && counter != newIndex) {
        if(playing){ // reset timer
          stopPlaying();
        }

        switchToSlide(newIndex);
        counter = newIndex;
      } else {
        inTransition = false;
      }

    }
   
  });
});



/**
 * switches to the next slide. if end of carousel is reached, it starts again at the beginning
 */
function switchSlide() {
  if (!playing) {
    return;
  }
  
  if (counter >= (nodes.length - 1)) {
    counter = 0;
  }
  else {
    counter++;
  }
  switchToSlide(counter);
}



/**
 * loads the image of the slide specified in index. once this is done, it swaps image, headline and teaser
 */
function switchToSlide(index) {
  
  var img = new Image();
  jQuery(img)
    .load(function () {

      var current_slide = jQuery('.carousel .slide a.slide-img:first');
      var trans = inTransition;
      
      var css = 'slide-img';
      var target = '';
      if(nodes[index].url.substr(0,7) == 'http://' || nodes[index].url.substr(0,7) == 'https://') {
        css = css + ' externa-link';
        target = 'target="_blank"';
        target = '';
      }
      var label = 'carousel_slide'+(parseInt(index)+1)+'_'+ nodes[index].url;
      var link = jQuery('<a class="' + css + '" href="' + nodes[index].url + '"' +
                 'onclick="_gaq.push([\'_trackEvent\',\'banner\',\'click\',\''+label+'\']);" ' + target + '></a>');
      
      var transitionCallback = function() {
          current_slide.remove();
          jQuery(this).css({left: '0'});
          inTransition = false;
          if(playing){ // reset timer
            setTimeout("switchSlide()", 8000);        
          }
      };
      
      link.append(jQuery(this));
      jQuery('.carousel .slide a.slide-img').after(link);
      jQuery('.carousel .slide').animate({left: '-960px'},1000, transitionCallback);
      
      // switch nav
      updateNav(index);
      
    })
    .error(function () { // if sth goes wrong, remove the carousel
      jQuery('.carousel').slideUp(function(){
        jQuery(this).remove();
      })
    })
    .attr('src', nodes[index].image)
    .attr('alt', nodes[index].title);

}



/**
 * sets the active class to the link which has the same href value as specified in hrefValue.
 * also, the position of the nav is calculated anew
 */
function updateNav(hrefValue) {
  jQuery('.carousel ul.manualnav li a.active').removeClass('active');
  jQuery('.carousel ul.manualnav li a.item' + hrefValue).addClass('active');
}



function stopPlaying() {
  playing = false;
  jQuery('.carousel .manualnav a.playcontrol').removeClass('playing');
}



function startPlaying() {
  playing = true;
  jQuery('.carousel .manualnav a.playcontrol').addClass('playing');
  setTimeout('switchSlide()', 2500); 
}


(function($) {
  $.randomize = function(arr) {
    for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
    return arr;
  };
})(jQuery);;
//http://www.featureblend.com/license.txt
var FlashDetect=new function(){var self=this;self.installed=false;self.raw="";self.major=-1;self.minor=-1;self.revision=-1;self.revisionStr="";var activeXDetectRules=[{"name":"ShockwaveFlash.ShockwaveFlash.7","version":function(obj){return getActiveXVersion(obj);}},{"name":"ShockwaveFlash.ShockwaveFlash.6","version":function(obj){var version="6,0,21";try{obj.AllowScriptAccess="always";version=getActiveXVersion(obj);}catch(err){}
return version;}},{"name":"ShockwaveFlash.ShockwaveFlash","version":function(obj){return getActiveXVersion(obj);}}];var getActiveXVersion=function(activeXObj){var version=-1;try{version=activeXObj.GetVariable("$version");}catch(err){}
return version;};var getActiveXObject=function(name){var obj=-1;try{obj=new ActiveXObject(name);}catch(err){obj={activeXError:true};}
return obj;};var parseActiveXVersion=function(str){var versionArray=str.split(",");return{"raw":str,"major":parseInt(versionArray[0].split(" ")[1],10),"minor":parseInt(versionArray[1],10),"revision":parseInt(versionArray[2],10),"revisionStr":versionArray[2]};};var parseStandardVersion=function(str){var descParts=str.split(/ +/);var majorMinor=descParts[2].split(/\./);var revisionStr=descParts[3];return{"raw":str,"major":parseInt(majorMinor[0],10),"minor":parseInt(majorMinor[1],10),"revisionStr":revisionStr,"revision":parseRevisionStrToInt(revisionStr)};};var parseRevisionStrToInt=function(str){return parseInt(str.replace(/[a-zA-Z]/g,""),10)||self.revision;};self.majorAtLeast=function(version){return self.major>=version;};self.minorAtLeast=function(version){return self.minor>=version;};self.revisionAtLeast=function(version){return self.revision>=version;};self.versionAtLeast=function(major){var properties=[self.major,self.minor,self.revision];var len=Math.min(properties.length,arguments.length);for(i=0;i<len;i++){if(properties[i]>=arguments[i]){if(i+1<len&&properties[i]==arguments[i]){continue;}else{return true;}}else{return false;}}};self.FlashDetect=function(){if(navigator.plugins&&navigator.plugins.length>0){var type='application/x-shockwave-flash';var mimeTypes=navigator.mimeTypes;if(mimeTypes&&mimeTypes[type]&&mimeTypes[type].enabledPlugin&&mimeTypes[type].enabledPlugin.description){var version=mimeTypes[type].enabledPlugin.description;var versionObj=parseStandardVersion(version);self.raw=versionObj.raw;self.major=versionObj.major;self.minor=versionObj.minor;self.revisionStr=versionObj.revisionStr;self.revision=versionObj.revision;self.installed=true;}}else if(navigator.appVersion.indexOf("Mac")==-1&&window.execScript){var version=-1;for(var i=0;i<activeXDetectRules.length&&version==-1;i++){var obj=getActiveXObject(activeXDetectRules[i].name);if(!obj.activeXError){self.installed=true;version=activeXDetectRules[i].version(obj);if(version!=-1){var versionObj=parseActiveXVersion(version);self.raw=versionObj.raw;self.major=versionObj.major;self.minor=versionObj.minor;self.revision=versionObj.revision;self.revisionStr=versionObj.revisionStr;}}}}}();};FlashDetect.JS_RELEASE="1.0.4";;

/**
 * @file media_unswtv/js/media_unswtv.js
 */

(function ($) {

Drupal.media_unswtv = {};
Drupal.behaviors.media_unswtv = {
  attach: function (context, settings) {
    // Check the browser to see if it supports html5 video.
    var video = document.createElement('video');
    var html5 = video.canPlayType ? true : false;

    // If it has video, does it support the correct codecs?
    if (html5) {
      html5 = false;
      if (video.canPlayType( 'video/webm; codecs="vp8, vorbis"' ) || video.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"')) {
        html5 = true;
      }
    }

    // Put a prompt in the video wrappers to let users know they need flash
    if (!FlashDetect.installed && !html5){
      $('.media-unswtv-preview-wrapper').each(Drupal.media_unswtv.needFlash);
    }
  }
};

Drupal.media_unswtv.needFlash = function () {
  var id = $(this).attr('id');
  var wrapper = $('.media-unswtv-preview-wrapper');
  var hw = Drupal.settings.media_unswtv[id].height / Drupal.settings.media_unswtv[id].width;
  wrapper.html('<div class="js-fallback">' + Drupal.t('You need Flash to watch this video. <a href="@flash">Get Flash</a>', {'@flash':'http://get.adobe.com/flashplayer'}) + '</div>');
  wrapper.height(wrapper.width() * hw);
};

Drupal.media_unswtv.insertEmbed = function (embed_id) {
  var videoWrapper = $('#' + embed_id + '.media-unswtv-preview-wrapper');
  var settings = Drupal.settings.media_unswtv[embed_id];

  // Calculate the ratio of the dimensions of the embed.
  settings.hw = settings.height / settings.width;

  // Replace the object embed with unswtv's iframe. This isn't done by the
  // theme function because unswtv doesn't have a no-JS or no-Flash fallback.
  var video = $('<iframe class="unswtv-player" type="text/html" frameborder="0"></iframe>');
  var src = 'https://tv.unsw.edu.au/p/v.?v=' + settings.video_id + '&s=1&c=&auto=false&k=';

  // Allow other modules to modify the video settings.
  settings.options.wmode = 'opaque';
  $(window).trigger('media_unswtv_load', settings);

  // Merge unswtv options (such as autoplay) into the source URL.
  var query = $.param(settings.options);
  if (query) {
    //src += '?' + query;
  }

  // Set up the iframe with its contents and add it to the page.
  video
    .attr('id', settings.id)
    .attr('width', settings.width)
    .attr('height', settings.height)
    .attr('src', src);
  videoWrapper.html(video);

  // Bind a resize event to handle fluid layouts.
  $(window).bind('resize', Drupal.media_unswtv.resizeEmbeds);

  // For some reason Chrome does not properly size the container around the
  // embed and it will just render the embed at full size unless we set this
  // timeout.
  if (!$('.lightbox-stack').length) {
    setTimeout(Drupal.media_unswtv.resizeEmbeds, 1);
  }
};

Drupal.media_unswtv.resizeEmbeds = function () {
  $('.media-unswtv-preview-wrapper').each(Drupal.media_unswtv.resizeEmbed);
};

Drupal.media_unswtv.resizeEmbed = function () {
  var context = $(this).parent();
  var video = $(this).children(':first-child');
  var hw = Drupal.settings.media_unswtv[$(this).attr('id')].hw;
  // Change the height of the wrapper that was given a fixed height by the
  // unswtv theming function.
  $(this)
    .height(context.width() * hw)
    .width(context.width());

  // Change the attributes on the embed to match the new size.
  video
    .height(context.width() * hw)
    .width(context.width());
};

})(jQuery);;

/**
 * @file media_youtube/js/media_youtube.js
 */

(function ($) {

Drupal.media_youtube = {};
Drupal.behaviors.media_youtube = {
  attach: function (context, settings) {
    // Check the browser to see if it supports html5 video.
    var video = document.createElement('video');
    var html5 = video.canPlayType ? true : false;

    // If it has video, does it support the correct codecs?
    if (html5) {
      html5 = false;
      if (video.canPlayType( 'video/webm; codecs="vp8, vorbis"' ) || video.canPlayType('video/mp4; codecs="avc1.42E01E, mp4a.40.2"')) {
        html5 = true;
      }
    }

    // Put a prompt in the video wrappers to let users know they need flash
    if (!FlashDetect.installed && !html5){
      $('.media-youtube-preview-wrapper').each(Drupal.media_youtube.needFlash);
    }
  }
};

Drupal.media_youtube.needFlash = function () {
  var id = $(this).attr('id');
  var wrapper = $('.media-youtube-preview-wrapper');
  var hw = Drupal.settings.media_youtube[id].height / Drupal.settings.media_youtube[id].width;
  wrapper.html('<div class="js-fallback">' + Drupal.t('You need Flash to watch this video. <a href="@flash">Get Flash</a>', {'@flash':'http://get.adobe.com/flashplayer'}) + '</div>');
  wrapper.height(wrapper.width() * hw);
};

Drupal.media_youtube.insertEmbed = function (embed_id) {
  var videoWrapper = $('#' + embed_id + '.media-youtube-preview-wrapper');
  var settings = Drupal.settings.media_youtube[embed_id];

  // Calculate the ratio of the dimensions of the embed.
  settings.hw = settings.height / settings.width;

  // Replace the object embed with YouTube's iframe. This isn't done by the
  // theme function because YouTube doesn't have a no-JS or no-Flash fallback.
  var video = $('<iframe class="youtube-player" type="text/html" frameborder="0"></iframe>');
  var src = 'https://www.youtube.com/embed/' + settings.video_id;

  // Allow other modules to modify the video settings.
  settings.options.wmode = 'opaque';
  $(window).trigger('media_youtube_load', settings);

  // Merge YouTube options (such as autoplay) into the source URL.
  var query = $.param(settings.options);
  if (query) {
    src += '?' + query;
  }

  // Set up the iframe with its contents and add it to the page.
  video
    .attr('id', settings.id)
    .attr('width', settings.width)
    .attr('height', settings.height)
    .attr('src', src);
  videoWrapper.html(video);

  // Bind a resize event to handle fluid layouts.
  $(window).bind('resize', Drupal.media_youtube.resizeEmbeds);

  // For some reason Chrome does not properly size the container around the
  // embed and it will just render the embed at full size unless we set this
  // timeout.
  if (!$('.lightbox-stack').length) {
    setTimeout(Drupal.media_youtube.resizeEmbeds, 1);
  }
};

Drupal.media_youtube.resizeEmbeds = function () {
  $('.media-youtube-preview-wrapper').each(Drupal.media_youtube.resizeEmbed);
};

Drupal.media_youtube.resizeEmbed = function () {
  var context = $(this).parent();
  var video = $(this).children(':first-child');
  var hw = Drupal.settings.media_youtube[$(this).attr('id')].hw;
  // Change the height of the wrapper that was given a fixed height by the
  // YouTube theming function.
  $(this)
    .height(context.width() * hw)
    .width(context.width());

  // Change the attributes on the embed to match the new size.
  video
    .height(context.width() * hw)
    .width(context.width());
};

})(jQuery);;
(function ($) {

$(document).ready(function() {

  // Accepts a string; returns the string with regex metacharacters escaped. The returned string
  // can safely be used at any point within a regex to match the provided literal string. Escaped
  // characters are [ ] { } ( ) * + ? - . , \ ^ $ # and whitespace. The character | is excluded
  // in this function as it's used to separate the domains names.
  RegExp.escapeDomains = function(text) {
    return (text) ? text.replace(/[-[\]{}()*+?.,\\^$#\s]/g, "\\$&") : '';
  }

  // Attach onclick event to document only and catch clicks on all elements.
  $(document.body).click(function(event) {
    // Catch the closest surrounding link of a clicked element.
    $(event.target).closest("a,area").each(function() {

      var ga = Drupal.settings.googleanalytics;
      // Expression to check for absolute internal links.
      var isInternal = new RegExp("^(https?):\/\/" + window.location.host, "i");
      // Expression to check for special links like gotwo.module /go/* links.
      var isInternalSpecial = new RegExp("(\/go\/.*)$", "i");
      // Expression to check for download links.
      var isDownload = new RegExp("\\.(" + ga.trackDownloadExtensions + ")$", "i");
      // Expression to check for the sites cross domains.
      var isCrossDomain = new RegExp("^(https?|ftp|news|nntp|telnet|irc|ssh|sftp|webcal):\/\/.*(" + RegExp.escapeDomains(ga.trackCrossDomains) + ")", "i");

      // Is the clicked URL internal?
      if (isInternal.test(this.href)) {
        // Is download tracking activated and the file extension configured for download tracking?
        if (ga.trackDownload && isDownload.test(this.href)) {
          // Download link clicked.
          var extension = isDownload.exec(this.href);
          _gaq.push(["_trackEvent", "Downloads", extension[1].toUpperCase(), this.href.replace(isInternal, '')]);
        }
        else if (isInternalSpecial.test(this.href)) {
          // Keep the internal URL for Google Analytics website overlay intact.
          _gaq.push(["_trackPageview", this.href.replace(isInternal, '')]);
        }
      }
      else {
        if (ga.trackMailto && $(this).is("a[href^=mailto:],area[href^=mailto:]")) {
          // Mailto link clicked.
          _gaq.push(["_trackEvent", "Mails", "Click", this.href.substring(7)]);
        }
        else if (ga.trackOutbound && this.href) {
          if (ga.trackDomainMode == 2 && isCrossDomain.test(this.href)) {
            // Top-level cross domain clicked. document.location is handled by _link internally.
            _gaq.push(["_link", this.href]);
          }
          else if (ga.trackOutboundAsPageview) {
            // Track all external links as page views after URL cleanup.
            // Currently required, if click should be tracked as goal.
            _gaq.push(["_trackPageview", '/outbound/' + this.href.replace(/^(https?|ftp|news|nntp|telnet|irc|ssh|sftp|webcal):\/\//i, '').split('/').join('--')]);
          }
          else {
            // External link clicked.
            _gaq.push(["_trackEvent", "Outbound links", "Click", this.href]);
          }
        }
      }
    });
  });
});

})(jQuery);
;

