/**
*
*   global.js
*
*   This JS file include will hold all global functionality.
*   Global is defined as appearing on more than one type of page.
*
*/
$(function() {

	initMantle();

	$("#expand-small").mouseover(function() {
		$("#expand-small").hide();
		$("#expand-big").show();
	});

	$("#expand-big").mouseout(function() {
		$("#expand-small").show();
		$("#expand-big").hide();
	});

});

/**
*
*    Mantle
*
*    Generates the Mantle Module Which Slides the Featured Content On Homepage
*    Added By: Tito To (5/27/2009)
*/
function rotate() {

	//Get the first image
	var currentImg = ($('.contentdiv.show') ?  $('.contentdiv.show') : $('.contentdiv:first'));
	var currentNo = ($('.toc.selected') ?  $('.toc.selected') : $('.toc:first'));

	//Get next image, when it reaches the end, rotate it back to the first image
	var nextImg = ((currentImg.next().length && !currentImg.next().hasClass('pagination')) ? ((currentImg.next().hasClass('show')) ? $('.contentdiv:first') : currentImg.next()) : $('.contentdiv:first'));
	var nextNo = ((currentNo.next().length) ? ((currentNo.next().hasClass('selected')) ? $('.toc:first') : currentNo.next()) : $('.toc:first'));

	//Set the fade in effect for the next image, the show class has higher z-index
	nextImg.css({opacity: 0.0})
	.addClass('show')
	.animate({opacity: 1.0}, 700);
	nextNo.addClass('selected');

	//Hide the current image
	currentImg.animate({opacity: 0.0}, 700)
	.removeClass('show');
	currentNo.removeClass('selected');

};

function initMantle() {

	//Get the first image and display it (gets set to full opacity)
	$('.contentdiv:first').css({opacity: 1.0})
	.addClass('show');

	$('.indicators').css({opacity: 1.0})
	$('.toc:first').addClass('selected');

	var set = setInterval('rotate()',6000);	

	$('.toc').click(function(event) {
		//Clear out timer
		clearInterval(set);

    var url = this.toString();
    var delimiter = '#';
    var id = url.split(delimiter);
    id = parseInt(id[1]);

    $('.contentdiv.show').css({opacity: 0.0})
		.removeClass('show');

		$('.contentdiv.content_'+id).css({opacity: 1.0})
		.addClass('show');

    $('.toc.selected').removeClass('selected');

		$('.toc.content_'+id).addClass('selected');

		return false;
	});

}

function clearTimer() {

	clearInterval(set);
}

/**
*
*   Toggles Tabs
*
*   This function will toggle through tabs or any other ID'd DOM elements, showing the selected
*   tab.  It also has the option to change the tab CSS styles.
*
*   @param array options Options List (Example: ['MyVideos','FavoriteVideos','TaggedVideos'])
*   @param string selected Selected Option (Example: 'TaggedVideos')
*   @param string offClass Tab 'Off Class' CSS Classes To Set
*   @param string onClass Tab 'On Class' CSS Classes To Set
*   @return void
*
*/
function toggle_tabs(options, selected, offClass, onClass) {
	if (options instanceof Array) {
    	for (var i=0; i<options.length; i++) {
            if (document.getElementById(options[i])) {
                document.getElementById(options[i]).style.display = 'none';
            }
            if (typeof(offClass) != 'undefined') {
                if (document.getElementById(options[i]+'Tab')) {
                    document.getElementById(options[i]+'Tab').className = offClass;
                }
            }
        }
	} else {
        if (document.getElementById(options)) {
            document.getElementById(options).style.display = 'none';
        }
        if (typeof(offClass) != 'undefined') {
            if (document.getElementById(options+'Tab')) {
                document.getElementById(options+'Tab').className = offClass;
            }
        }
	}
    if (selected instanceof Array) {
    	for (var i=0; i<selected.length; i++) {
	        if (document.getElementById(selected[i])) {
	            document.getElementById(selected[i]).style.display = 'inline';
	        }
	        if (typeof(onClass) != 'undefined') {
	            if (document.getElementById(selected[i]+'Tab')) {
	                document.getElementById(selected[i]+'Tab').className = onClass;
	            }
	        }
    	}
    } else {
        if (document.getElementById(selected)) {
            document.getElementById(selected).style.display = 'inline';
        }
        if (typeof(onClass) != 'undefined') {
            if (document.getElementById(selected+'Tab')) {
                document.getElementById(selected+'Tab').className = onClass;
            }
        }
    }
}

/****************************************
 **
 **    Photo Gallery
 **
 ****************************************/

var Collection;
var showAnchor = true;
var firstImageID = '';
var CollectionComponent = function()
{
 this.images = {};

 // Loads Playlist
 this.Load = function(playlist) {

     // Loads Playlist
     try {
         this.images = $.parseJSON(playlist);
     } catch (e) {
    	 alert('Error parsing JSON');
         return false;
     }
     
     // Shows Initial Image
     if (typeof(GetID('#')) != 'undefined') {
         this.ShowImage(GetID('#'));
     } else if (typeof(GetID('?image=')) != 'undefined') {
         this.ShowImage(GetID('?image='));
     } else {
    	 showAnchor = false;
    	 firstImageID = this.images[0].id;
    	 this.ShowImage(this.images[0].id);	 
     }

     //Keylistener for Left/Right arrows
     $(document).bind('keydown', function(e) {
         if (e.which == '37') {
             Collection.ShowImage(Collection.prevID);
         }
         if (e.which == '39') {
             Collection.ShowImage(Collection.nextID);
         }
     });
     
 	var HashCheckInterval = setInterval(this.CheckForHash, 500);

 };

 // Show Image (Primary Function Call)
 this.ShowImage = function(id) {

     // Adds Anchor Tag With ID Of Current Image
	 if(showAnchor == true) {
		 document.location.href = "#"+id; 
	 } else {
		 showAnchor = true;
	 }

     this.ShowLoader();

     this.UpdatePhotoPaging(id); // <-- Updates Photo Paging, Per Image

 };

 // Shows Loader
 this.ShowLoader = function() {
     $('#imageLoaderGif').css('display','block');
 }

 // Hides Loader
 this.HideLoader = function() {
     $('#imageLoaderGif').css('display','none');
     $('#featured-photo').css('display','block');
 };

 // Updates Image
 this.UpdateFeatureImage = function(id,nextId) {
	 var image = this.GetImage(id);

	 $('#selectedImage').html('<a href="'+this.GetCollectionPath()+'#'+nextId+'" onclick="Collection.ShowImage(\''+nextId+'\');return false;"><img style="vertical-align:middle;" src="'+image.link+'" alt="" onload="Collection.HideLoader();return false;"/></a>');
	 
};

 // Updates Photo Paging
 this.UpdatePhotoPaging = function(id) {

     var currentPage = 0;
     var totalPages = 0;

     var currentNumber = 1;
     var totalImages = 0;
     var prevID = 0;
     var nextID = 0;
     var num = 0;

     if ($('#GalleryView').length > 0) {
         var noDisplayThumb = 8;
     }

     // Gets Total Image Count, Current Page
     var first = 0;
     var prev = 0;
     var count = 0;
     for (image in this.images) {
    	 if (image == 'filter' || image == 'indexOf') continue;
         count++;
         if ((count % noDisplayThumb) == 1) {
             totalPages++;
         }
         if (first == 0) {
             first = this.images[image].id;
         }
         if (this.images[image].id == id) { // <-- Image Match Found
             this.UpdateCaption(this.images[image].desc); // <-- Updates Caption, Per Image
             currentNumber = count;
             currentPage = totalPages;
             prevID = prev; // <-- Sets Previous Image ID (Or 0 If Image Is First Image)

         }
         if (prev == id) { // <-- Sets Next Image ID (Based On Cycle/Rotation)
             nextID = this.images[image].id;
         }
         prev = this.images[image].id;
         totalImages++;
     }

     if (totalImages > 0) {
         if (prevID == 0) { // <-- If PrevID Still Not Set, Use Last Image Found (As Image ID Was First Image)
             prevID = prev;
         }
         if (nextID == 0) { // <-- If NextID Still Not Set, Use First Image Found (As Image ID Was Last Image)
             nextID = first;
         }
     }

     this.prevID = prevID;
     this.nextID = nextID;

     this.UpdateFeatureImage(id,nextID); // <-- Updates Feature Image

     // Builds Pagination Arrows
     var html = '';
     html += '<a id="PrevImg" href="'+this.GetCollectionPath()+'#'+prevID+'" onclick="Collection.ShowImage(\''+prevID+'\');return false;">&lt; Previous</a> ';
     html += currentNumber+' of '+totalImages+' ';
     html += '<a id="NextImg" href="'+this.GetCollectionPath()+'#'+nextID+'" onclick="Collection.ShowImage(\''+nextID+'\');return false;">Next &gt;</a>';
     $('#paginationLinks').html(html);

     // Builds Image Navigation
     var html = '';
     if (totalImages <= noDisplayThumb) {
         num = totalImages;
     } else {
         num = (totalImages % noDisplayThumb == 0) ? noDisplayThumb : (totalImages % noDisplayThumb);

     }

     if (currentPage == totalPages) {
         for (i=0; i<num; i++) {

             var startImg = ((currentPage-1) * noDisplayThumb) + i;
             var startImage = this.GetImage(this.images[startImg].id);

             html += '<img src="'+startImage.thumb+'" width="100" height="75" border="0" onclick="Collection.ShowImage(\''+this.images[startImg].id+'\');return false;" id="img_'+this.images[startImg].id+'"';
             if (this.images[startImg].id == id) {
                 html += ' class="selected"';
             } else {
                 html += ' class="notSelected"';
             }
             html += ' />';
         }

     } else { 
         for (i=0; i<noDisplayThumb; i++) {
 
             var startImg = ((currentPage-1) * noDisplayThumb) + i;
             var startImage = this.GetImage(this.images[startImg].id);

             html += '<img src="'+startImage.thumb+'" width="100" height="75" border="0" onclick="Collection.ShowImage(\''+this.images[startImg].id+'\');return false;" id="img_'+this.images[startImg].id+'"';
             if (this.images[startImg].id == id) {
                 html += ' class="selected"';
             } else {
                 html += ' class="notSelected"';
             }
             html += ' />';
         }
     }
     $('#photoThumbs').html(html);

     // Builds Previous Image Navigation Button
     var ppImage = document.getElementById('previousPageImage');
     if (currentPage == 1) {
         $('#previousPageImage').attr('src',arrow_prev_inactive);
         $('#previousPageImage').removeClass('cursoron');
         $('#previousPageImage').addClass('cursoroff');
         $('#previousPageImage').click(function() {});
     } else {
         var num1 = currentNumber - (currentNumber % noDisplayThumb + noDisplayThumb);
         imageID2 = this.images[num1].id; // <-- Define Before Sending Into 'onclick' Definition
         ppImage.src = arrow_prev_active;
         ppImage.className = 'cursoron';
         ppImage.title = '< Previous Page';
         ppImage.onclick = function() {
             Collection.ShowImage(imageID2);
         }
     }

     // Builds Next Image Navigation Button
     var npImage = document.getElementById('nextPageImage');
     if (totalPages > 1 && currentPage != totalPages) {
         var num2 = (currentPage * noDisplayThumb);
         imageID = this.images[num2].id; // <-- Define Before Sending Into 'onclick' Definition
         npImage.className = 'cursoron';
         npImage.src = arrow_next_active;
         npImage.title = 'Next Page >';
         npImage.onclick = function() {
             Collection.ShowImage(imageID);
         }
     } else {
         $('#nextPageImage').attr('src',arrow_next_inactive);
         $('#nextPageImage').removeClass('cursoron');
         $('#nextPageImage').addClass('cursoroff');
         $('#nextPageImage').click(function() {});
     }
          
 };

 // Updates Caption
 this.UpdateCaption = function(caption) {
     if (caption != '') {
    	 $('#photo-description').css('display','block')
         $('#imageDescription').html(caption);
     } else {
    	 $('#photo-description').css('display','none');
     }
 };
 
 // Updates share Facebook
 this.UpdateShareIcons = function(id) {
	 $('#shareFB').html('<fb:like href="'+this.GetCollectionSharePath()+id+'" show_faces="false" send="true"></fb:like>'); 
	 $('#shareTwitter').html('<iframe allowtransparency="true" frameborder="0" scrolling="no" src="http://platform.twitter.com/widgets/tweet_button.html?url='+encodeURIComponent(this.GetCollectionSharePath()+id)+'" style="width:130px; height:26px;"></iframe>'); 
	 try {
         FB.XFBML.parse();
     } catch (e) {}
 };
 // Gets Current Collection Path
 this.GetCollectionPath = function() {
     var url = window.location.href;
     var delimiter = '#';
     var segment = url.split(delimiter);
     return segment[0];

 };
 
 // Gets Current Collection Path for FB share
 this.GetCollectionSharePath = function() {
     var url = window.location.href;
     var segment = url.split('?image=');
     if (typeof(segment[1]) == 'undefined') {
    	 var segment = segment[0].split('#');
    	 return segment[0]+'?image=';
     } else {
    	 var image = segment[1].split('#');
    	 return segment[0]+'?image='; 
     }
 };

 // Gets Image Info
 this.GetImage = function(id) {
	 var imgObj;
	 var i;
     for(i in this.images) {
    	 if (this.images[i].id == id) {
			 imgObj = this.images[i]; 
		 }
	 }
     return imgObj;
 };

 /**
 *
 *   Check for image hash id and update featured photo accordingly
 *   @return void
 *
 */
 this.tempID;
 this.CheckForHash = function() {
	 var currentID = GetID('#');
	if(typeof(currentID) != 'undefined') {
		if (currentID != this.tempID) {
			this.tempID = currentID ;
			Collection.UpdateShareIcons(this.tempID);
			Collection.UpdatePhotoPaging(this.tempID);
		}
	} 
	else if(this.tempID != firstImageID) 
	{ 
		this.tempID = firstImageID;
		Collection.UpdateShareIcons(this.tempID);
		Collection.UpdatePhotoPaging(this.tempID); 
	}
};
 
} //end Collection

/**
*
*   Retrieves Anchor Tag From URL As ID
*   @return void
*
*/
function GetID(delimiter){
	var url = window.location.href;
	var id = url.split(delimiter);
	if (id[1] != '') {
	    return id[1];
	} else {
	    return '';
	}
}


