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

initMantle();

/**
*
*    url_goto()
*
*    @param: string
*    
*    @returns: url of state selected  
*/
function url_goto( menuform )
{
    selecteditem = menuform.newurl.selectedIndex ;
    newurl = menuform.newurl.options[ selecteditem ].value ;
    if (newurl.length != 0) {
      location.href = base_url + '/trails/' + newurl ;
    }
}

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

	//Get the first div
	var currentDiv = ($('.contentdiv.show') ?  $('.contentdiv.show') : $('.contentdiv:first'));

	//Get next div, when it reaches the end, rotate it back to the first div
	var nextDiv = ((currentDiv.next().length && !currentDiv.next().hasClass('pagination')) ? ((currentDiv.next().hasClass('show')) ? $('.contentdiv:first') : currentDiv.next()) : $('.contentdiv:first'));

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

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

};

function initMantle() {

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

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

}

/**
*
*   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 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 {
    	 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);
         }
     });


 };

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

     // Adds Anchor Tag With ID Of Current Image
     document.location.href = "#"+id;

     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="Feature" 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" 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" 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() {});
     }
     
     this.UpdateShareFacebook(id); // <-- Updates Facebook Share, Per Image
          
 };

 // 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.UpdateShareFacebook = function(id) {
	 $('#shareFB').html('<fb:like href="'+this.GetCollectionSharePath()+id+'" layout="button_count" show_faces="false" action="like" colorscheme="light"></fb:like>'); 
     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;
 };

}

/**
*
*   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 '';
	}
}

/**
*
*   Google Sponsored Ads
*
*   This function will is for Google Sponsored Links ads
*
*   @param none
*   @return void
*
*/
function google_ad_request_done(google_ads)
{var s='';var i;
var s = '<div class ="googleAdTitle"><a target="_new" class="ad_attribution" href="' + google_info.feedback_url + '">Sponsored Links</a></div>';
var multicolumns=false;if(google_ads.length==0)
return;if(google_ads[0].type=="text")
{if(column_count_afc>1)
{multicolumns=true;}
if(multicolumns==true)
s+='<table width="100%" class="google_afc_tbl" border="0" cellspacing="0" cellpadding="5">';for(i=0;i<google_ads.length;++i)
{if(multicolumns==true)
{if(i%column_count_afc==0)
s+='<tr>';s+='<td valign="top" width="25%">';}
var description=google_ads[i].line2+' '+google_ads[i].line3;var url_text=google_ads[i].visible_url;if(max_length_description>0)
description=description.substring(0,max_length_description);if(max_length_url>0)
url_text=url_text.substring(0,max_length_url);s+='<div '+css_class_item_cell+'><a target="_blank" href="'+google_ads[i].url+'" '+'onmouseout="window.status=\'\'" '+'onmouseover="window.status=\'go to '+
google_ads[i].visible_url+'\';return true;" '+
css_class_ads_title+'>'+
google_ads[i].line1+'</a><br /><span '+
css_class_ads_description+'>'+
description+'</span><br><a target="_blank" href="'+google_ads[i].url+'" '+'onmouseout="window.status=\'\'" '+'onmouseover="window.status=\'go to '+
google_ads[i].visible_url+'\';return true;" '+
css_class_ads_url+'>'+
url_text+'</a></div><br />';if(multicolumns==true)
{s+='</td>';if(i%column_count_afc==column_count_afc-1)
s+='</tr>';}}
if(multicolumns==true)
{s+='</table>';}}
document.write(s);return;}
function rewrite_google_header()
{var headers=document.getElementsByTagName('div');if((headers!=null)&&(headers.length>0))
{for(var i=headers.length-1;i>=0;i--)
{var att=headers[i].getAttribute("name");if(att=='adsByGoogleHeader')
{var color=get_element_style(headers[i],"color","color");if(typeof google_info!="undefined")
{headers[i].innerHTML='<a style\=\"color:'+color+'; text-decoration: none" target="_blank" class="ad_attribution" href="'+
google_info.feedback_url+'">'+headers[i].innerHTML+'</a>';}}}}}
function get_element_style(elem,ieStyleProp,cssStyleProp){if(elem.currentStyle){return elem.currentStyle[ieStyleProp];}else if(window.getComputedStyle){var compStyle=window.getComputedStyle(elem,"");return compStyle.getPropertyValue(cssStyleProp);}
return"";}	

