var curSlide = 1;
var maxSlideId = 1;
function initSpartavSlider(selectedSlide) {
  curSlide = selectedSlide;
  if (document.getElementById("slide1_thumb")) {
    do {
	  maxSlideId++; 
    } while (document.getElementById("slide"+maxSlideId+"_thumb"));
    maxSlideId--;
  
    for (i=1; i<=maxSlideId; i++) {
      var el=document.getElementById("slide"+i+"_thumb");
      el.onclick=function() {fade(this.number);};
      el.number=i;
    }
    cycleFadeInterval=setInterval("cycleFade();",8000);
  }
}

function cycleFade() {
  var nextSlide=(curSlide==maxSlideId)?1:curSlide+1;
  if (curSlide != nextSlide && isNaN(parseInt(getURLParam('mid')))) {
    opacity('slide'+curSlide,'slide'+nextSlide);
    curSlide=(curSlide==maxSlideId)?1:curSlide+1;
  }
}

function fade(nextSlide) {
  var switcher = document.getElementById('spartavMediaSlider');
  var switcherHeadings = switcher.getElementsByTagName('p');
  for (var i in switcherHeadings) {
	if (switcherHeadings[i].nodeName == 'P') {
      switcherHeadings[i].style.display = 'block';
	}
  }
  clearInterval(cycleFadeInterval);
  if (curSlide!=nextSlide) {
    opacity('slide'+curSlide,'slide'+nextSlide);
    curSlide=nextSlide;
  }
}

function opacity(id1,id2) {
  var speed=3;
  var timer=0;
  for (i=100; i>=0; i--) {
    setTimeout("changeOpac("+i+",'"+id1+"')",(timer * speed));
    timer++;
  }
  for (i=0; i<= 100; i++) {
    setTimeout("changeOpac("+i+",'"+id2+"')",(timer * speed));
    timer++;
  } 
}

function changeOpac(opacity,id) {
  var el=document.getElementById(id).style;
  var elthumb=document.getElementById(id+'_thumb');
  el.opacity=(opacity / 100);
  el.filter="alpha(opacity="+opacity+")";
  el.display=(opacity>0)?'block':'none';
  elthumb.className=(opacity>0)?'selected':'';
}

var ytplayerSelectedId;
function onytplayerStateChange(newState) {
  switch(newState) {
    case 0: // Ended
      if (ytplayerSelectedId) {
        $("#my"+ytplayerSelectedId).parent().find("div.spartavVideoControls img.playerPlay").attr("src","/images/spartav/playerPlay.png");
      }
      break;
    case 1: // Playing
      if (ytplayerSelectedId) {
        $("#my"+ytplayerSelectedId).parent().find("div.spartavVideoControls img.playerPlay").attr("src","/images/spartav/playerPause.png");
      }
      clearInterval(cycleFadeInterval);
      var switcher = document.getElementById('spartavMediaSlider');
      if (switcher) {
        var switcherHeadings = switcher.getElementsByTagName('p');
        for (var i in switcherHeadings) {
          if (switcherHeadings[i].nodeName == 'P') {
            switcherHeadings[i].style.display = 'none';
          }
        }
      }
      break;
  }
}

$(document).ready(function() {
  var spartavVideoObjects = false;
  spartavVideoObjects = $(".spartavVideoContainer object");
  if (spartavVideoObjects.length) {
    spartavVideoObjects.each(function() {
      $(this).parent().hover(function () {
        $(this).parent().find("div.spartavVideoControls").css("display","block");
      },function () {
        $(this).parent().find("div.spartavVideoControls").css("display","none");
      });
      $(this).parent().find("div.spartavVideoControls img.playerPlay").click(function() {
        if ($(this).attr("src") == "/images/spartav/playerPause.png") {
          document.getElementById($(this).parent().parent().find("object").attr("id")).pauseVideo();
          $(this).attr("src","/images/spartav/playerPlay.png");
        } else {
          document.getElementById($(this).parent().parent().find("object").attr("id")).playVideo();
          $(this).attr("src","/images/spartav/playerPause.png");
        }
      });
      $(this).parent().find("div.spartavVideoControls img.playerVolume").click(function() {
        if ($(this).attr("src") == "/images/spartav/playerVolumeOn.png") {
          document.getElementById($(this).parent().parent().find("object").attr("id")).mute();
          $(this).attr("src","/images/spartav/playerVolumeOff.png");
        } else {
          document.getElementById($(this).parent().parent().find("object").attr("id")).unMute();
          $(this).attr("src","/images/spartav/playerVolumeOn.png");
        }
      });
    });
  }
});

var galleryId;
var galleryDivId;
var media;
var mediaId;
var loadedThumbs = new Array();
var thumbArrayStart = 0;
var thumbTotal;
var thumbHeight;
var thumbWidth;
var thumbWidthMargin = 20;
var thumbDisplay;
var thumbOffset = 0;
var galleryImageDir = "";
var pageURL;

function initSpartavGallery(id,width,height,visible,dir,selected,start,total,customPageURL) {
  galleryDivId = id;
  thumbWidth = parseInt(width);
  thumbHeight = parseInt(height);
  thumbDisplay = parseInt(visible);
  galleryImageDir = dir;
  thumbSelectedId = parseInt(selected);
  thumbArrayStart = parseInt(start);
  thumbTotal = parseInt(total);
  mediaId = parseInt(getURLParam('mid')) || 0;
  
  // Construct page URL to make sure it still all works with mod_rewrite
  pageURL = (customPageURL)?customPageURL:location.pathname + location.search;
  pageURL = pageURL.replace(/gid=(\d+)/,'');
  pageURL = pageURL.replace(/mid=(\d+)/,'');
  pageURL = pageURL.replace(/&+/,'');
  pageURL = pageURL.replace(/\?$/,'');
  pageURL += (pageURL.indexOf('?') != -1)?'&amp;':'?';
  
  var myRequest = new ajaxObject('/spartav/index.php', getThumbs);
  galleryId = (getURLParam('gid'))?parseInt(getURLParam('gid')):1;
  myRequest.update('gid='+galleryId);
  
  for (var i = thumbArrayStart; (i < thumbArrayStart + thumbDisplay && i < thumbTotal); i++) {
    loadedThumbs[i] = true;
  }
}

function getURLParam(name) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.href);
  if (results == null)
    return "";
  else
    return results[1];
}

function outputThumbnail(thisMedia) {
  if (thisMedia.thumbnail) {
    mediaThumbnailSrc = '/'+galleryImageDir+thisMedia.thumbnail.replace('_thumb.','_'+thumbWidth+'x'+thumbHeight+'.');
  } else {
    switch (thisMedia.type) {
      case 'image':
        mediaThumbnailSrc = '/'+galleryImageDir+thisMedia.filename.replace('_original.','_'+thumbWidth+'x'+thumbHeight+'.');
        break;
      case 'audio':
        mediaThumbnailSrc = '/images/spartav/audio-thumb.jpg';
        break;
    }
  }
  return '<img src="'+mediaThumbnailSrc+'" width="'+thumbWidth+'" height="'+thumbHeight+'" title="'+thisMedia.title+'" alt="'+thisMedia.title+'" />';
}

function moveThumbs(direction) {
  if (!animating) {
    var divGalleryThumbs = document.getElementById('thumbsList'+galleryDivId);
    var beginPosition = parseInt(divGalleryThumbs.style.left) || thumbOffset;
    var endPosition   = beginPosition;
    
    switch (direction) {
      case 'next':
    	if (thumbArrayStart + thumbDisplay < thumbTotal && thumbTotal > thumbDisplay) { 
          var nextThumb = (thumbArrayStart + thumbDisplay);
          if (!loadedThumbs[nextThumb]) {
            loadedThumbs[nextThumb] = true;
            divGalleryThumbs.innerHTML += '<a href="'+pageURL+'gid='+galleryId+'&amp;mid='+media[nextThumb].id+'">'+outputThumbnail(media[nextThumb])+'</a>';
          }
          thumbArrayStart++;
          endPosition -= (thumbWidth + thumbWidthMargin);
    	}
        break;
      case 'prev':
    	if (thumbArrayStart > 0 && thumbTotal > thumbDisplay) {
    	  var prevThumb = (thumbArrayStart - 1);
          if (!loadedThumbs[prevThumb]) {
            loadedThumbs[prevThumb] = true;
            beginPosition -= (thumbWidth + thumbWidthMargin);
            endPosition = beginPosition;
            divGalleryThumbs.style.left = beginPosition + 'px';
            divGalleryThumbs.innerHTML = '<a href="'+pageURL+'gid='+galleryId+'&amp;mid='+media[prevThumb].id+'">'+outputThumbnail(media[prevThumb])+'</a>'+divGalleryThumbs.innerHTML;
          }
          thumbArrayStart--;
          endPosition += (thumbWidth + thumbWidthMargin);
    	}
        break;
    }
    var properties={left:{start:beginPosition,end:endPosition}};
    animate(divGalleryThumbs,properties,500,20,easeOutQuart);
    var nextThumbImg = document.getElementById('nextThumbImg'+galleryDivId);
    nextThumbImg.className = (thumbArrayStart + thumbDisplay >= thumbTotal)?'disabled':'';
    nextThumbImg.src = (thumbArrayStart + thumbDisplay >= thumbTotal)?'/images/spartav/gallery-next-thumb-disabled.gif':'/images/spartav/gallery-next-thumb.gif';
    var prevThumbImg = document.getElementById('prevThumbImg'+galleryDivId);
    prevThumbImg.className = (thumbArrayStart == 0 || thumbTotal <= thumbDisplay)?'disabled':'';
    prevThumbImg.src = (thumbArrayStart == 0 || thumbTotal <= thumbDisplay)?'/images/spartav/gallery-prev-thumb-disabled.gif':'/images/spartav/gallery-prev-thumb.gif';
    var thumbsInfo = document.getElementById('thumbsInfo'+galleryDivId);
    var thumbsInfoText = "Displaying thumbnails " + (thumbArrayStart + 1) + " to ";
    if (thumbTotal < thumbDisplay) {
      thumbsInfoText += thumbTotal;
    } else {
      thumbsInfoText += (thumbArrayStart + thumbDisplay);
    }
    thumbsInfoText += " out of " + thumbTotal;
    thumbsInfo.innerHTML = thumbsInfoText;
  }
}

function getThumbs(responseText, responseStatus) {
  if (responseStatus==200) {
    media = eval('('+responseText+')');
  } else {
    alert(responseStatus + ' - Error Processing Request');
  }
}