//used externally
function getQueryVariable(variable) {
	var pair, vars = (window.location.search.substring(1)).split("&");
	while(pair = vars.shift()){
		pair = pair.split('=');
		if(pair[0] == variable) return pair[1];
	}
	return false;
}

//ytPlayer globals
	var startVidTitle='';              
	var startVidTime='';
	var startVidDate='';
	var currentVideo, currentTitle, previousVideo;
	var startVideo, startVidLoaded = false, firstFeaturedVid = true;

//video browser globals
	var jsonFeed_ = null;
	var MAX_RESULTS_LIST = 5;
	var LIST_COUNT = 0, CURRENT_PAGE;
	
	var vidType = '', vidsContainer = null;
	var previousSearchTerm = '', previousQueryType = 'all';
	var firstLoad = true;
	var vCat = 'REI';
	if(QueryString('vcat')){
		vCat = QueryString('vcat').toLowerCase();
	}

    //--all vids
	    isFirstBlock = true;
	    var TOTAL_VIDEOS = 0, FEED_COUNT = 0, ALLVIDSBLOCK_MARKUP = '';
	    var ALL_VIDS_COUNT, blockCount = 0;
	    var allVidsInnerWrapper = null;
	    var scriptNumber = 0;
    
    
    



/**
    Copyright (c) 2007 Google Inc. original code by api.rboyd@google.com (Ryan Boyd) 
 * Creates a script tag for retrieving a Google data JSON feed and and adds it into the html head. 
 * @param {String} scriptSrc The URL for the script, assumed to already have at  least one query parameter, so the '?' is not added to the URL
 * @param {String} scriptId The id to use for the script tag added to the head @param {String} scriptCallback  The callback function to be used after the 
 *     JSON is retrieved.  The JSON is passed as the first argument to the  callback function.
 */
var appendScriptTag = function(scriptSrc, scriptId, scriptCallback) {
          // Remove any old existance of a script tag by the same name
          var oldScriptTag = document.getElementById(scriptId);
          if (oldScriptTag) {
                oldScriptTag.parentNode.removeChild(oldScriptTag);
          }
          
          // Create new script tag
          var script = document.createElement('script');
          script.setAttribute('id', scriptId);
          script.setAttribute('type', 'text/javascript');
          
          /*use this line for live viewing*/
            script.setAttribute('src', scriptSrc + '&alt=json-in-script&callback=' + scriptCallback);
          
          /*###    use this line for debugging.  You can see an xml error pop in firefox:errorConsole.  click error link and it will give you JSON Data ###*/
       //script.setAttribute('src', scriptSrc);

         document.getElementsByTagName('head')[0].appendChild(script);
};
   
 
function play() {
    if (ytplayer) {
        ytplayer.playVideo();
    }
}

function pause() {
    if (ytplayer) {
        ytplayer.pauseVideo();
    }
}

function stop() {
    if (ytplayer) {
        ytplayer.stopVideo();
    }
}

function getPlayerState() {
if (ytplayer) {
return ytplayer.getPlayerState();
}
}

function seekTo(seconds) {
    if (ytplayer) {
        ytplayer.seekTo(seconds, true);
    }
}

function getBytesLoaded() {
    if (ytplayer) {
        return ytplayer.getVideoBytesLoaded();
    }
}

function getBytesTotal() {
    if (ytplayer) {
        return ytplayer.getVideoBytesTotal();
    }
}

function getCurrentTime() {
    if (ytplayer) {
        return ytplayer.getCurrentTime();
    }
}

function getDuration() {
    if (ytplayer) {
        return ytplayer.getDuration();
    }
}

function getStartBytes() {
    if (ytplayer) {
        return ytplayer.getVideoStartBytes();
    }
}

function mute() {
    if (ytplayer) {
        ytplayer.mute();
    }
}

function unMute() {
    if (ytplayer) {
        ytplayer.unMute();
    }
}

function getEmbedCode() {
       // alert(ytplayer.getVideoEmbedCode());
       document.getElementById('embedBox').style.display="block";
       document.getElementById('urlValue').value='http://www.rei.com/video?videoId='+currentVideo;
        document.getElementById('embedValue').value=ytplayer.getVideoEmbedCode();
}

function getVideoUrl() {
        //alert(ytplayer.getVideoUrl());
        document.getElementById('shareBox').style.display="block";
        document.getElementById('urlValue2').value='http://www.rei.com/video?videoId='+currentVideo;
}

function setVolume(newVolume) {
    if (ytplayer) {
        ytplayer.setVolume(newVolume);
    }
}

function getVolume() {
    if (ytplayer) {
        return ytplayer.getVolume();
    }
}

function clearVideo() {
    if (ytplayer) {
        ytplayer.clearVideo();
    }
}                      
                      
function updateHTML(elmId, value) {
    document.getElementById(elmId).innerHTML = value;
}

function setytplayerState(newState) {
    updateHTML("playerstate", newState);
}

function onytplayerStateChange(newState) {
    setytplayerState(newState);
}

function updateytplayerInfo() {
    updateHTML("bytesloaded", getBytesLoaded());
    updateHTML("bytestotal", getBytesTotal());
    updateHTML("videoduration", getDuration());
    updateHTML("videotime", getCurrentTime());
    updateHTML("startbytes", getStartBytes());
    updateHTML("volume", getVolume());
}



function onYouTubePlayerReady(playerId) {
    ytplayer = document.getElementById("myytplayer");
    setInterval(updateytplayerInfo, 250);
    updateytplayerInfo();
    ytplayer.addEventListener("onStateChange", "onytplayerStateChange");    
    currentVideo=startVideo;
    previousVideo=startVideo;
   cueNewVideo(startVideo);
}
function cueNewVideo(id) { 
        if (ytplayer) {
                ytplayer.cueVideoById(id, 0);       

                fetchTitleId='title'+id;
                fetchTimeId='time'+id;
                fetchDateId='date'+id;
                fetchDescripId='descrip'+id;
                fetchKeywordId='keyword'+id;
                  $('#currentTime').html(startVidTime);
                  $('#currentDate').html(startVidDate);
                  $('#currentTitle').html(startVidTitle);
                
                document.getElementById('currentDescrip').innerHTML = document.getElementById(fetchDescripId).innerHTML;
               // document.getElementById('keywordList').firstChild.nodeValue=document.getElementById(fetchKeywordId).firstChild.nodeValue;
                previousVideo = '#snip' + id + '__F'; 
                activateSnip(previousVideo);
        }
}

/* #####    functions for the api calls    #####*/
function loadNewVideo(id, title, time, date, videoTab) {
        
        if (ytplayer) {            
            ytplayer.loadVideoById(id, parseInt(0));
            
            document.getElementById('currentTitle').innerHTML = cleanOutputStr(title);
            document.getElementById('currentTime').innerHTML = time;
            document.getElementById('currentDate').innerHTML = date;
            document.getElementById('currentDescrip').innerHTML = document.getElementById( 'descrip'+id ).innerHTML;
            currentVideo = id;
        }

        //check if same video click( )
        if(previousVideo.indexOf(id) < 0){                
                //deactivate lastVid
                deActivateSnip(previousVideo);

                //check if tabVideo click( )
                if(typeof(videoTab) != 'undefined'){
                        var newVid = '#snip' + id + '__' + videoTab;
                        previousVideo = newVid;
                        activateSnip(newVid);
                        return;
                }
        }
        
        previousVideo = id;
            
}          

function activateSnip(id) {
        $(id).addClass('active');       

}

function deActivateSnip(lastVid) {            
            if( $(lastVid)  && lastVid.indexOf('__')>0 ){
                    $(lastVid).removeClass('active');
             }
}





 
/*BEGIN Code for the Video Tabs ########################################################################*/
 var listFeaturedVideos_Callback = function(data) {
	var cnt = 0;
	var featuredVidsCategory = 'snow';
		if(vCat != 'REI'){ featuredVidsCategory = vCat; }
	
	for (var ii = 0, vidData; vidData = data.feed.entry[ii]; ii++) {    
	        if (!vidData.yt$noembed && vidData.media$group.media$keywords.$t.toLowerCase().indexOf(featuredVidsCategory) >-1 ){
	                $('#featuredVideos').append(createVideoElement(vidData, 'F'));
	        }
	}
};
 
 var listNewVideos_Callback = function(data) {      
      for (var ii = 0, vidData; vidData = data.feed.entry[ii]; ii++) {  
                if (! vidData.yt$noembed) {
                        $('#newVideos').append(createVideoElement(vidData, 'N'));
                }
      }
};
 
 var listPopularVideos_Callback = function(data) {       
      for (var ii = 0, vidData; vidData = data.feed.entry[ii]; ii++) {  
                if (! vidData.yt$noembed) {
                        $('#popularVideos').append(createVideoElement(vidData, 'P'));
                }
      }
};
/*#################################################################### END Code for the Video Tabs */


/*http://uhqtz01a.rei.com/video?vcat=kayaking&videoId=ShjxjaXKMJQ*/

/******************************************************************************************************************************************************************************
 * Retrieves a list of videos matching the provided criteria.  These videos can be restricted to a particular standard feed or search criteria.
 *
 * See this URL for more info: @ [ http://code.google.com/apis/youtube/reference.html#Feeds ]
 * Reference Guide: 
	@param {String} queryType The type of query to be done - either 'all' for querying all videos, or the name of a standard feed.
	@param {String} searchTerm The search term(s) to use for querying as the 'vq' query parameter value
 	@param {Number} page The 1-based page of results to return.
 ******************************************************************************************************************************************************************************/
 var listVideos = function(queryType, searchTerm, page) {
      previousSearchTerm = searchTerm; 
      previousQueryType = queryType;
      CURRENT_PAGE = page;

      var queryUrl = 'http://gdata.youtube.com/feeds/api/users/reifindout/uploads';
      var vidPullList = (MAX_RESULTS_LIST+1);
      
      if (queryUrl) {
            queryUrl += '?max-results=' + vidPullList + '&start-index=' + (((page - 1) * MAX_RESULTS_LIST) + 1);
            if (searchTerm != '') {
                  queryUrl += '&category=' + searchTerm + '%2C%2DXX';
            }
            appendScriptTag(queryUrl, 'searchResultsVideoListScript','listCategoryVideos_Callback');
      } 
      else {
            alert('Unknown feed type specified');
      }
};
 var listCategoryVideos_Callback = function(data) {      
      LIST_COUNT = 0;
      $('#categoryVideos').html('');
      
      for (var ii = 0, vidData; vidData = data.feed.entry[ii]; ii++) {      
             // The entry.yt$noembed property will exist if the YTvideo doesn't support viewing in an embedded player on a third-party site.      
                if (! vidData.yt$noembed) {
                        if(ii < 5){
                            $('#categoryVideos').append(createVideoElement(vidData, 'C'));
                        }
                        LIST_COUNT+= 1;
                }
      }
      updateNavigation(CURRENT_PAGE);      
};
/******************************************END CATEGORY VIDLISTING CODE********************************************************************************************/

 



 var listAllVideos = function(page, sortOrder, searchTerm) {
        var queryUrl = 'http://gdata.youtube.com/feeds/api/users/reifindout/uploads?';
       
       scriptNumber += 1;
       var scriptName = 'listAllVidsScript_' + scriptNumber;
        
        if(typeof(searchTerm) != 'undefined'){//this only occurs when category dropdown is used
                if(searchTerm == 'allVideos'){ searchTerm = 'REI'; }
                queryUrl += 'max-results=50&start-index=' + (((page - 1) * 50) + 1) + '&category=' + searchTerm + '%2C%2DXX&orderby=published';
                appendScriptTag(queryUrl, scriptName, 'listAllVideos_Callback');
        }
        else{
                switch(sortOrder){
                        case 'published':
                                if(vidType == 'new'){
                                        queryUrl += 'max-results=6&start-index=1&category=' + vCat + '%2C%2DXX&orderby=published';
                                        appendScriptTag(queryUrl, scriptName, 'listNewVideos_Callback');
                                }
                                else{
                                        queryUrl += 'max-results=50&start-index=1&category=' + vCat + '%2C%2DXX&orderby=published';
                                        if(vCat != 'REI'){
	                                    $('#categoryFilter').val(vCat);
                                        }                                    
                                        appendScriptTag(queryUrl, scriptName, 'listFeaturedVideos_Callback');
                                }
                                break;
                                
                        case 'viewCount':
                                    queryUrl += 'max-results=6&start-index=1&category=' + vCat + '%2C%2DXX&orderby=' + sortOrder;
                                    appendScriptTag(queryUrl, scriptName, 'listPopularVideos_Callback');
                            break;
                            
                        default:
                                        queryUrl += 'max-results=50&start-index=' + (((page - 1) * 50) + 1) + '&category=' + vCat + '%2C%2DXX&orderby=published';
                                        appendScriptTag(queryUrl, scriptName, 'listAllVideos_Callback');
                }
        }
        CURRENT_BLOCK = page;
};
var listAllVideos_Callback = function(data) {
        TOTAL_VIDEOS = 0;
                
        if(isFirstBlock){                
                 ALL_VIDS_COUNT = 0;
                isFirstBlock = false;
                keywordHtmlStr = '';
                keywordVidsCnt = 0;
                 
		$('#allVideos').html('');
		allVidsInnerWrapper = document.createElement('div');
		allVidsInnerWrapper.className = 'moreVideos';
          }
try{
	var l = data.feed.entry.length;
	for (var i = 0, entry; i < l; i++) {
                 entry = data.feed.entry[i];		//this was the cause of the last allVids bug... FIX: (data.feed.entry[i] >> data.feed.entry.length);
                // The entry.yt$noembed property will exist if the YTvideo doesn't support viewing in an embedded player on a third-party site.      
                if (! entry.yt$noembed) {
	                    //create variables for vid metaData
	                        var videoId = entry.id.$t;
	                                videoId = videoId.substring(videoId.lastIndexOf('/')+1, videoId.length);
	                        var publishedDate = entry.published.$t;
	                                publishedDate = publishedDate.substring(0, publishedDate.indexOf('T'));	                        
	                        var vidDuration = entry.media$group.yt$duration.seconds;
	                                var minVar = Math.floor(vidDuration / 60);  // The minutes
	                                var secVar = vidDuration % 60;              // The balance of seconds
	                                        if(secVar.toString().length < 2){ secVar = '0' + secVar; }
	                                vidDuration = minVar + ':' + secVar;
	                         
	                         var vidTitle= entry.media$group.media$title.$t;
	                         if( vidTitle.indexOf("'")>0 || vidTitle.indexOf('"')>0 ){
                	                         vidTitle = cleanInputStr(vidTitle);
                	              }
	                                
	                        var videoDescription = cleanVideoDescription(entry.media$group.media$description.$t);
	                        if( (videoId == startVideo) && !startVidLoaded){
	                               startVidLoaded = true;
                                          startVidTime = vidDuration;
                                          startVidDate = publishedDate;
                                          startVidTitle = cleanOutputStr(vidTitle);
                                    }
	                                 
	                    //now create markup to hold videos
	                        //-- holding ul
	                        var vidElement = document.createElement('ul');
	                            
	                         //-- vidThumb
	                         var firstLi = document.createElement('li');
	                                firstLi.className = 'p2';
													
                                    var vidThumb = document.createElement('div');
                                                vidThumb.className = 'thumbStyle2';																		                         
                                                var childElements = "";                            
                                                childElements = "<a href='#load' onclick=\"loadNewVideo('" + videoId + "', '" + vidTitle + "', '" + vidDuration + "', '" + publishedDate + "'); return false;\">";                            
                                                childElements += "<img src='" + entry.media$group.media$thumbnail[0].url + "' title='" + vidTitle + "'";
                                                childElements += " alt='" + entry.media$group.media$title.$t + "' border=\"none\" /></a>";
	                         vidThumb.innerHTML = childElements;
	                        
	                        //-- titleLink
	                        var vidTitleH4 = document.createElement('h4');
                                                childElements = "";
                                                childElements = "<a href='#load' onclick=\"loadNewVideo('" + videoId + "', '" + vidTitle + "', '" + vidDuration + "', '" + publishedDate + "'); return false;\">" + entry.media$group.media$title.$t + "</a>";
                                                
	                        vidTitleH4.innerHTML = childElements;
                                    firstLi.appendChild(vidThumb);
                                    firstLi.appendChild(vidTitleH4);                                    
                                    
                                    //-- vidDuration and vidDescription
                                    var secondLi = document.createElement('li');	                        
                                    
                                    var vidTime = document.createElement('span');
                                            vidTime.className = 'time';
                                            vidTime.id = 'time' + videoId;
                                            vidTime.innerHTML = vidDuration;
                                    
                                    var vidDescripWrapper = document.createElement('div');
                                            vidDescripWrapper.id = 'descrip' + videoId;
                                            vidDescripWrapper.style.display = 'none';
                                            vidDescripWrapper.innerHTML = videoDescription;
                                    
                                    secondLi.appendChild(vidTime);
                                    secondLi.appendChild(vidDescripWrapper);
                                    
                                    vidElement.appendChild(firstLi);
                                    vidElement.appendChild(secondLi);
                                    
                                    allVidsInnerWrapper.appendChild(vidElement);
                                   
                                    //still increment count for navigation purposes
                                    TOTAL_VIDEOS+= 1;
                                    if(TOTAL_VIDEOS % 5 ==0){
                                            var clearingDiv = document.createElement('div');
                                            clearingDiv.className = 'cleardiv';
                                            allVidsInnerWrapper.appendChild(clearingDiv);
                                    }
                                    
                }
      }
}catch(err){ // potential feed issue
}
	ALL_VIDS_COUNT += TOTAL_VIDEOS;
	checkTotalVideos(allVidsInnerWrapper);
};

function getTabVideos(theTab){
    switch(theTab){                
            case 'N':
                    if(document.getElementById('newVideos').childNodes.length == 0) { vidType='new'; listAllVideos(1, 'published'); }        
                break;
            
            case 'P':
                    if(document.getElementById('popularVideos').childNodes.length == 0) { listAllVideos(1, 'viewCount'); }                
                break;
            
            case 'C':                
                if(firstLoad == true){
                        firstLoad = false;
                        if(vCat != 'REI'){
	                        $('#categoriesOptions').val(vCat);
                        }
                        else{
                        	$("#categoriesOptions option:eq(1)").attr("selected","selected");
                        }
                        
                        getVidCat( document.getElementById('categoriesOptions') );
                }
                break;
    }
}
function getVidCat(dElem, vidArea){
        var theCategory =  dElem.options[dElem.selectedIndex].value;

        if(typeof(vidArea)!='undefined' && vidArea=='listAll'){//this is for all videos filter dropdown
        	isFirstBlock = true;
        	vCat = 'REI';
            listAllVideos(1, 'published', theCategory);
        }
        else{//this is for categories tab dropdown
            listVideos('all', theCategory, 1);
            vidType = 'category';
        }
}
function checkTotalVideos(dElem){
           //this happens on first load??
	if(TOTAL_VIDEOS == 0 || (TOTAL_VIDEOS < 50 && TOTAL_VIDEOS > 0)){
                var allVidsMainDiv = document.getElementById('allVideos');
                allVidsMainDiv.appendChild(dElem);
                isFirstBlock = true;
                categoryFilterSelection = false;
                if(QueryString('vcat')){
	                vCat = QueryString('vcat').toLowerCase();
                }
	}
	else{
                listAllVideos(CURRENT_BLOCK+1);
           }
}

function createVideoElement(entry, vidTypeSuffix){
        //create variables for vid metaData
            var videoId = entry.id.$t;
                    videoId = videoId.substring(videoId.lastIndexOf('/')+1, videoId.length);
                    
            var publishedDate = entry.published.$t;
                    publishedDate = publishedDate.substring(0, publishedDate.indexOf('T'));
            
            var vidTitle = cleanInputStr(entry.media$group.media$title.$t);
            if(firstFeaturedVid){
            	startVideo = videoId;
            	firstFeaturedVid = false;
            }

            var vidDuration = entry.media$group.yt$duration.seconds;
            var minVar = Math.floor(vidDuration / 60);  // The minutes
            var secVar = vidDuration % 60;              // The balance of seconds
                    if(secVar.toString().length == 1){
                        secVar = '0' + secVar;
                    }
            vidDuration = minVar + ':' + secVar;
                        
            var vidDescription = cleanVideoDescription(entry.media$group.media$description.$t);

        //now create markup to hold videos
            //-- holding div
            var vidElement = document.createElement('div');
                    vidElement.className = 'snippet';
                    vidElement.id = 'snip' + videoId + '__' + vidTypeSuffix;
                
             //-- vidThumb
             var vidThumb = document.createElement('div');
                    vidThumb.className = 'thumb';
             
             var childElements = "";                            
                    childElements = "<a href='#load' onclick=\"loadNewVideo('" + videoId + "', '" + vidTitle + "', '" + vidDuration + "', '" + publishedDate + "', '" + vidTypeSuffix + "'); return false;\">";                            
                    childElements += "<img src='" + entry.media$group.media$thumbnail[0].url + "' title='" + vidTitle + "'";
                    childElements += " alt='" + entry.media$group.media$title.$t + "' /></a>";
            
             vidThumb.innerHTML = childElements;
            vidElement.appendChild(vidThumb);
            
            //-- titleLink
            var metadataWrap = document.createElement('ul');
            var metadataElem = document.createElement('li');
                        metadataElem.className = 'p2';
            var metadataHolder = document.createElement('h4');                                
                        childElements = "<a href='#load' onclick=\"loadNewVideo('" + videoId + "', '" + vidTitle + "', '" + vidDuration + "', '" + publishedDate + "', '" + vidTypeSuffix + "'); return false;\">" + entry.media$group.media$title.$t + "</a>";                            
            
            metadataHolder.innerHTML = childElements;
            metadataElem.appendChild(metadataHolder);
            metadataWrap.appendChild(metadataElem);
            
            //-- pubdate/vidDuration
            metadataElem = document.createElement('li');
                        metadataElem.innerHTML = vidDuration + ' | ' + publishedDate;
            metadataWrap.appendChild(metadataElem);
             
            //--  vidDescription     
            metadataElem = document.createElement('li');
                        metadataElem.id = 'descrip' + videoId;
                        metadataElem.style.display = 'none'
                        metadataElem.innerHTML = vidDescription;
            metadataWrap.appendChild(metadataElem);
                    
            vidElement.appendChild(metadataWrap);
            
            return vidElement;
}



/**
 * Updates the variables used by the navigation buttons and the 'enabled' status of the buttons based upon the current page number passed in.
 * @param {Number} page The current page number
 */
var updateNavigation = function(page) {
        
            nextPage = page + 1;
            previousPage = page - 1;
            
            $('#vidCatSelector').css('height', '20px');          
          
            $('#nextPageButton').css('visibility', 'visible');
            $('#categoriesPaging').css('visibility', 'visible');
            
            $('#previousPageButton').css('visibility', 'visible');
            if (previousPage < 1) {
                    $('#previousPageButton').css('visibility', 'hidden');
            } 
            
            if( (LIST_COUNT < 6) && (page==1) ){
                $('#nextPageButton').css('visibility', 'hidden');
                $('#categoriesPaging').css('visibility', 'hidden');
            }
            else if(LIST_COUNT < 6){
                $('#nextPageButton').css('visibility', 'hidden');
            }
            else{
                    //do nothing 
           }
            
};

function cleanInputStr(myStr) {
        var rgExp = new RegExp("'", "g");
        myStr = myStr.replace(rgExp, "_REPLACE_");
                
        rgExp = new RegExp("\"", 'g');
        myStr = myStr.replace(rgExp, "@");
        
        return myStr;
}
function cleanOutputStr(myStr) {    
        var rgExp = new RegExp("_REPLACE_", "g");
        myStr = myStr.replace(rgExp, "'");
        
        rgExp = new RegExp('@', 'g');
        myStr = myStr.replace(rgExp, "\"");
        return myStr
}
function cleanVideoDescription(vidDescrip){
    
    if(vidDescrip.indexOf('www.rei.com') == 0){
        vidDescrip = vidDescrip.substring(12, vidDescrip.length);    
    }

    return vidDescrip
}





$(document).ready( function(){

	//need to check if category querystring value is a valid one
	var ddl = document.getElementById('categoryFilter');
	var ddlOption, validVCat = false;
	for(var xx=0;xx<ddl.length;xx++){
		ddlOption = ddl[xx].value;
		if(vCat == ddlOption){
			validVCat = true;
			break;
		}
	}
	if(!validVCat){ vCat = 'REI'; }//if not reset to default category
	

        //-- list featured vids, the other tabs load on initial tab click( );
        listAllVideos(1, 'published');
        
        //-- list 'All OUtdoors, Recreation and Gear Videos
        listAllVideos(1);
        
});


