/** declare global vars */
$.redbullcc = {};
$.redbullcc.thmbArray = [];
$.redbullcc.imgUrlArray = [];


$( function()
{
	scheduleRollover();
	schedBtnClick();
	thumbPreview();
	largeImgClick();
	expandImg();
	eventReturn();
});

function scheduleRollover()
{
	var oldLiveColor = $('.schedItemLive').css('background-color');
	var oldPastColor = $('.schedItemPast').css('background-color');
	var oldUpComingColor = $('.schedItemUpcoming').css('background-color');
    $('.schedItemLive a,.schedItemPast a,.schedItemUpcoming a').bind('mouseover',over);
	$('.schedItemLive a').bind('mouseout',{col:oldLiveColor},out); 
	$('.schedItemPast a').bind('mouseout', {col:oldPastColor},out);
	$('.schedItemUpcoming a').bind('mouseout', {col:oldUpComingColor},out);
}

/** sched rollover function */
var over = function()
{
	$(this).css('background-color', '#FFF');
	$(this).children('.event-name').css('color','#254d6e');
};

/** sched mouse out function */
var out = function(evt)//oldColor
{
	$(this).css('background-color', evt.data.col);
	$(this).children('.event-name').css('color','#FFF');
};

/** schedule button click to go to next page */
function schedBtnClick()
{
	$('#schedCheck').click(function()
	{
		$('#crowdScheduleArchived').slideToggle();
	})
}

function eventReturn()
{
	$('div#eventReturn').click(function(evt)
	{
		evt.preventDefault();
		history.back();
	});
}


function expandImg()
{
	$('div#fullSizeImg').click(function(evt)
	{
		var selectedImg = $('#largePreview').children('a').children('img').attr('src');
		
		/** hide scrollbars */ 
		$('body').css('overflow-y', 'hidden');
		
		/** add overlay cover */
        $('<div id="lightbox_overlay"></div>')
        .css('top', $(document).scrollTop())
        .css('opacity', '0')
        .animate({'opacity': '1'}, 'slow')
        .appendTo('body');

        /** add image div holder */
        $('<div id="lightbox"></div>').hide().appendTo('#lightbox_overlay');
		
        /** grab index of selected img */
        var urlArr = $.redbullcc.imgUrlArray
		var currIndex = urlArr.indexOf(selectedImg);
        
	   /** start the slideshow fade */
       startSlideShow(currIndex);
       evt.preventDefault();
    });
}


function startSlideShow($index)
{	
	var urlArr = $.redbullcc.imgUrlArray;
	$(urlArr).each(function(i)
	{
		$('<img />').attr('src',urlArr[i])
          .load(function()
          {
                positionLightboxImage($(this));
				$('#lightbox').cycle({fx: 'fade', startingSlide:$index,fit:1});
          })
          .click(function()
          {
                removeLightbox();
          })
          .appendTo('#lightbox');
		});		
		
		/** add slideshow controls div */
		$('<div id="slideShowControls"></div>').appendTo('#lightbox_overlay').css({'top':0,'zIndex':5599,'left':0});
		
		/** add 4 btn controls for slide show - expand/reduce btn, slow/med/fast */
		$('<div id="reduceImg"></div>')
		.appendTo('#slideShowControls')
		.css({'top':0,'zIndex':5599,'left':0})
		.click(function()
		{
			removeLightbox();
		});
		$('<a href="#" ><span class="slidecontrol">遅く</span></a>').appendTo('#slideShowControls').css({'top':0,'zIndex':5500})
		.click(function(evt)
		{
			$('#lightbox').cycle('pause');
			$('#lightbox').cycle({
				speed: 1500,timeout:5000
			}).cycle('resume');
			evt.preventDefault();
		}
		)
		$('<a href="#" ><span class="slidecontrol">普通</span></a>').appendTo('#slideShowControls').css({'zIndex':5501,'left':25})
		.click(function(evt)
		{
			$('#lightbox').cycle('pause');
			$('#lightbox').cycle({
				speed: 1000,timeout:3000
			}).cycle('resume');
			evt.preventDefault();
		}
		)
		$('<a href="#" ><span class="slidecontrol">速く</span></a>').appendTo('#slideShowControls').css({'zIndex':5502,'left':25})
		.click(function(evt)
		{
			$('#lightbox').cycle('pause');
			$('#lightbox').cycle({
				speed: 1000,timeout:1500
			}).cycle('resume');
			evt.preventDefault();
		})
		
		/** bind the escape key to remove slideshow */
		$(document).bind('keyup',function(e) 
		{
			 if (e.keyCode == 27) 
			 { 
				 removeLightbox(); 
			 }  
		});
}

/** position & scale lightbox image */
function positionLightboxImage(_img)
{
       $('#lightbox').fadeIn();

	   var fullImg = _img;

       var currW = $(fullImg).width();
       var currH = $(fullImg).height();
       var maxWidth = $(window).width();
       var maxHeight = $(window).height();
       
       if($.redbullcc.thmbArray.length <= 1)
       {
    	   var scalePercent =  Math.min(maxWidth/currW, maxHeight/currH);
           var newW = currW*scalePercent;
           var newH = currH*scalePercent;
           fullImg.width(newW);
           fullImg.height(newH);
           return;
       }
       if(currH > maxHeight || currW > maxWidth)
       {
           var scalePercent =  Math.min(maxWidth/currW, maxHeight/currH);
           var newW = currW*scalePercent;
           var newH = currH*scalePercent;
           fullImg.width(newW);
           fullImg.height(newH);
       }
      // var left = (maxWidth - currW) / 2;
      // var top = (maxHeight - currH) / 2;
      // $(_img).css({"left":left+"px","top":top+"px"});
	   $(_img).imgCenter({scaleToFit:false,centerVertical:true});   
}

/** remove lightbox */
function removeLightbox() 
{ 	
	$('#lightbox_overlay, #lightbox')
	.fadeOut('fast', function() 
	{ 
		$(this).remove(); 
		$('body').css('overflow-y', 'auto'); // show scrollbars!
	});
	
	/** remove escape key binding */
	$(document).unbind('keyup');
}

/** large image click function */
function largeImgClick()
{
	var selectedImg = "";
	var imgList = new Array();
	var thmbList = new Array();
	var len = 0;
	var urlToLoad = "";
	var indexToScroll = -1;
	
	$('#scroller a img').each(function(i) 
	{
		var value = $(this).attr('src');
		/** replace bs with n to grab the larger version of the image */
		var newVal = (value + "").replace('_bs.jpg','_b.jpg');
		/** add image urls & objects */
		imgList.push(newVal);
		thmbList.push($(this));
	});
	
	$('#largePreview').click(function(evt)
	{
		len = imgList.length;
		selectedImg = $(this).children('a').children('img').attr('src');
		indexToScroll = imgList.indexOf(selectedImg);
		
		if(indexToScroll == imgList.length-1)
		{
			indexToScroll = -1;
			//evt.preventDefault();
			//return;
		}
				
		indexToScroll += 1;
		sliderScroll(thmbList[indexToScroll],false);
		evt.preventDefault();
	});
}

/** thumb preview selected state */
function toggleSelected(target)
{
	var thmb = $.redbullcc.thmbArray;
	var len = thmb.length;
	
	while(len--)
	{
		var img = thmb[len];
		$(img).css('borderColor','#333').bind('mouseover',thmbOver).bind('mouseout',thmbOut); 
	}

	target.css('borderColor','white');
	target.unbind('mouseout').unbind('mouseover');
}

/** thumb preview rollover/rollout function */
function thmbOver(evt)
{
	$(evt.target).css('borderColor','white');
}

function thmbOut(evt)
{
	$(evt.target).css('borderColor','#333');
}


/** load the large version of the image */
function loadLargeImg(target)
{
	var $par;
	if(!target)  
		return;
	
	$par = $(target);
	
	var value = $par.attr('src');
	
	/** replace bs with n to grab the larger version of the image */
	var newVal = (value + "").replace('_bs','_b');
	var title = $par.attr('title');
	var timeStamp = $par.attr('time');
	var author = $par.attr('author');
	
	/** update textfields with new image data */
	$('div#eventTitle').html('<p>'+title+'</p><p id=eventTime>'+timeStamp+'</p>');
	$("div#preview-author").html('<span class="by">by </span><span>'+author+'</span>');

	/** preload the image and fade in once loaded */
	var img = new Image();
	var maxWidth = $(window).width();
	var maxHeight = ($(window).height() - 200);
	$(img)
	.hide()
	.load(function() 
	{  
		/** TODO: move this section to a separate resize function */
		$('#largePreview a img').replaceWith($(this));
		var currImg = $('#largePreview a img');
		var currW = currImg.width();
		var currH = currImg.height();
		if(currW > maxWidth || currH > maxHeight)
		{
			var scalePercent =  Math.min(maxWidth/currW,maxHeight/currH);
			var newW = currW*scalePercent;
			var newH = currH*scalePercent;
			currImg.width(newW);
			currImg.height(newH);
		}
		
		/** generate new qr code based on loaded image */
		createQRCode($par);
		
    }).attr('src', newVal).stop(true,true).fadeIn();

}

/** update QR code to point to picture url */
function createQRCode(target)
{
	var qrData = $('div#eventQR img').attr('src');
	var picId = target.attr('pic_id');
	var qrList = qrData.split(/post/);
	var qrEnding = qrList[1].split("?");
	var newQr = qrList[0]+"post/"+picId+"?"+qrEnding[1];

	$("div#eventQR img").attr('src',newQr);
}


/** pg 3 thumbnail scroller */
function thumbPreview()
{
	/** width of one thumbnail - includes border */
	var indSection = 160;
	
	var totalImages = $('#scroller a img').length;
	$.redbullcc.totalImages = totalImages;
	
	/** set total width of images div to # of images by each images width */
	$('#images').width(totalImages*indSection);
	
	/** set initial position of scroller bar to the right so it slides in */
	$('#images').css('left','1000px');
	
	$('#images .wrapper').click(function(evt) 
	{	
		  if ($(':animated').length) 
		        return false;
		  
		/** pass the selected image into the function to scroll to */
		sliderScroll($(this).children('img'),null);
		
		/** prevent default click event which causes window to jump */
		evt.preventDefault();
	});
	
	initialScroll();
}

function bindLeftRight()
{
	/** bind the escape key to remove slideshow */
	$(document).bind('keyup',function(e) 
	{
		 if (e.keyCode == 37) 
		 { 
			advanceImg('left');
		 }  
		 else if(e.keyCode == 39)
		 {
			advanceImg('right'); 
		 }
	});
}

function advanceImg($direction)
{
	$(document).unbind('keyup');
	var selectedImg = $('#largePreview').children('a').children('img').attr('src');
	var thmbList = $.redbullcc.thmbArray;
	var imgList = $.redbullcc.imgUrlArray;
	
	indexToScroll = imgList.indexOf(selectedImg);
	
	if($direction == 'right')
	{
		if(indexToScroll >= imgList.length-1)
			indexToScroll = 0;
		else
			indexToScroll++;
	}	
	else if($direction == 'left')
	{
		if(indexToScroll <= 0)
			indexToScroll = imgList.length-1;
		else
			indexToScroll--;
	}
	sliderScroll(thmbList[indexToScroll],false);
}

/** scroll the bar to the image selected initially-
 * n.b. TODO: i hate duplicate code..refactor please!!!
 * @return
 */
function initialScroll()
{
	var imgList = [];
	var thmbList = [];
	
	$('#scroller a img').each(function(i) 
	{
		var value = $(this).attr('src');
		/** replace bs with n to grab the larger version of the image */
		var newVal = (value + "").replace('_bs.jpg','_b.jpg');
		/** add image urls & objects */
		imgList.push(newVal);
		thmbList.push($(this));
	});
	
	/** reset the thmb array */
	$.redbullcc.thmbArray = [];
	$.redbullcc.imgUrlArray = [];
	
	/** store the thmbs */
	$.redbullcc.thmbArray = thmbList;
	$.redbullcc.imgUrlArray = imgList;
	
	/** get reference to image and search the array of images for the matching image index */
	var selectedImg = $('#largePreview').children('a').children('img').attr('src');
	
	indexToScroll = imgList.indexOf(selectedImg);
	sliderScroll(thmbList[indexToScroll],true);
	
	/** scale the initial image to proper dimensions */
	var currImg = $('#largePreview a img');
	$(currImg).load(function()
	{
		var currW = $(this).width();
		var currH = $(this).height();
		var maxWidth = $(window).width();
		var maxHeight = ($(window).height() - 200);
		if(currW > maxWidth || currH > maxHeight)
		{
			var scalePercent =  Math.min(maxWidth/currW,maxHeight/currH);
			var newW = currW*scalePercent;
			var newH = currH*scalePercent;
			$(this).width(newW);
			$(this).height(newH);
		}
	})
}

/** preview scroller */
function sliderScroll(target,init)
{
	if(target == null)
		return;
	
	bindLeftRight();
	
	/** grab the id of the scrollbar image */
	var id = $(target).attr('id');
	
	/** set selected state to white */
	toggleSelected(target);
	
	/** width of each image with padding */
	var itemWidth = 158;
	
	/** distance from left edge of window to middle point */
	var offsetCenter = ($(window).width() - itemWidth)/2;
	var xOffset = offsetCenter - (id*itemWidth);
  
	$('#images').stop(true,true).animate({left: xOffset},900,'swing',function() 
	{
		if(!init)
			//if(!$(':animated').length )
		      loadLargeImg(target)
	});
	return false;
}



