$(function() {
    weatherby_gallery_ready();
});


/* --------------------------
 * PAGE LOAD
 * -------------------------- */ 

function weatherby_gallery_ready() {
    // Show video gallery if possible
    $('div.body-inner #no-js-message').css('display', 'none');
    $('div.body-inner #videoGallery').css('display', 'block');

    // Everything reported finished, so prepare the initial carousel
    weatherby_video_prepare_carousel();
    weatherby_video_apply_carousel();
    
    // Run prepopulate check, if available
    weatherby_video_prepopulate();
    
    // Activate the first video
    $('li.jcarousel-item:visible:first', '#sorted-carousel').each(function() {
        var videoId = $('a.link', this).attr('rel');
        weatherby_video_embed(videoId, false);
    });

    // Watch for sorting videos by Type
    $("#sort-type").change( function (){
        weatherby_video_sort_type();
    });
    
    // Watch for sorting videos by Family
    $("#sort-family").change( function (){
        weatherby_video_sort_family();
    });
    
    // Bind video thumbnail click events on load
    weatherby_video_links();
}


/* --------------------------
 * INDIVIDUAL VIDEOS
 * -------------------------- */ 

// Embed an individual video
function weatherby_video_embed(videoID, autoplay){
    // detect firefox as browser to increase youtube player size
    var is_firefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;

    var params = {
        allowScriptAccess: "always",
        rel: 0
    };
    var atts = {
        id: "myytplayer",
	allowfullscreen: true
    };
    
    if (is_firefox){
        var player_url = "http://www.youtube.com/v/" + videoID + "?enablejsapi=1&playerapiid=ytplayer&rel=0&autoplay=" + autoplay + "&fs=1&border=0&version=3";
    }
    else {
        var player_url = "http://www.youtube.com/v/" + videoID + "?enablejsapi=1&playerapiid=ytplayer&rel=0&autoplay=" + autoplay + "&fs=1&version=3";
    }
    
    swfobject.embedSWF(
        player_url,
        "weatherby-video", 
        "768", 
        "432", 
        "8", 
        null, 
        params, 
        atts
    );
    $('#weatherby-video, object#myytplayer').show() .css('display', 'block');
}

// Click bindings for carousel links
function weatherby_video_links(){
    $("#sorted-carousel li.item a.link").unbind('click').click(function() {
        var vidID = $(this).attr('rel');
        var autoplay = 1;
        weatherby_video_embed(vidID, autoplay);
        
        var offset = $('#videoGallery').offset().top;
        $(window).scrollTop(offset);
        
        return false;
    });
}


/* --------------------------
 * PREPARE MARKUP AND APPLY CAROUSEL
 * -------------------------- */ 

function weatherby_video_prepare_carousel(){
    // Remove any existing sorted carousel
    $('ul#sorted-carousel').parents('.jcarousel-skin').remove();
    
    // Clone the prepared data
    $('div#carousels').append('<ul id="sorted-carousel" class="jcarousel-skin"></ul>');
    $('ul#source-carousel li').each(function(i) {
        var source = {
            html: $(this).html(),
            classes: $(this).attr('class'),
            id: ( !$(this).attr('id') ) ? 'sorted-video-vid-' + i : $(this).attr('id')
        };
        var newHtml = '<li class="' + source.classes + '" id="' + source.id + '">' + source.html + '</li>';
        $('ul#sorted-carousel').append(newHtml);
    });
    
    // Embed videos on click
    weatherby_video_links();
}
function weatherby_video_apply_carousel() {
    var resultCount = $('#sorted-carousel li.item:visible').length;
    
    if(resultCount <= 0) {
        $('#carousels').addClass('empty');
    }
    else {
        $('#carousels').removeClass('empty');
        
        // Apply jCarousel plugin
        $('#sorted-carousel').jcarousel({
            scroll: 5
        });
    }
}


/* --------------------------
 * SORT BY TYPE
 * -------------------------- */ 

function weatherby_video_sort_type(sortType){
    if(!sortType) {
        var sortType = $('#sort-type :selected').val();
    }

    // Perform the primary sort
    weatherby_video_sort_type_interior(sortType);
    
    // Re-apply carousel
    weatherby_video_apply_carousel();
    
    // Use new sort value to populate Family options
    weatherby_video_sort_family_options(sortType);
}

// Actually perform the video sort (by Type)
function weatherby_video_sort_type_interior(sortType){
    // Prepare a new version of the default video list
    weatherby_video_prepare_carousel();
    
    // Make sure the select field is accurate
    $('#sort-type option:selected').removeAttr('selected');
    $('#sort-type option[value="' + sortType + '"]').attr('selected','selected');

    // Sort videos
    if(sortType != "all") {
        $('ul#sorted-carousel li:not(.' + sortType + ')').remove();
    }
}


/* --------------------------
 * SORT BY FAMILY
 * -------------------------- */ 

// Actually perform the sort (by Family)
function weatherby_video_sort_family(sortType, sortFamily){
    // Get new sort value
    if(!sortType) {
        var sortType = $('#sort-type :selected').val();
    }
    if(!sortFamily) {
        var sortFamily = $('#sort-family :selected').val();
    }

    // Run Type sort again to be safe
    weatherby_video_sort_type_interior(sortType);
    
    // Make sure the select field is accurate
    $('#sort-family option:selected').removeAttr('selected');
    $('#sort-family option[value="' + sortFamily + '"]').attr('selected','selected');
    
    // Remove non-matches
    $('ul#sorted-carousel li:not(.' + sortFamily + ')').remove();
    
    // Re-apply carousel
    weatherby_video_apply_carousel();
}

// Populate Family options based on Type value
function weatherby_video_sort_family_options(sortType){
    // Clear previous Type options
    remove_select_options(sortType);
    
    // Rifles
    if (sortType == 'rifle') {
        var productsArray = [{
            'option': 'vanguard',
            'title': 'Vanguard'
        }, {
            'option': 'markv',
            'title': 'Mark V'
        }];
        $('#sort-family').removeAttr("disabled");
    }
    // Shotguns
    else if (sortType == 'shotgun') {
        var productsArray = [{
            'option': 'semiauto',
            'title': 'Semi-Auto'
        }, {
            'option': 'pump',
            'title': 'Pump'
        }, {
            'option': 'overunder',
            'title': 'Over Under'
        }, {
            'option': 'sidebyside',
            'title': 'Side-by-Side'
        }];
        $('#sort-family').removeAttr("disabled");
    }
    // Other
    else {
        var productsArray = [];
        $('#sort-family').attr("disabled","disabled");
    }

    // Populate Type options based on the settings above
    add_select_options(productsArray);
}


/* --------------------------
 * POPULATE FROM QUERY STRING
 * -------------------------- */ 

function weatherby_video_prepopulate() {
    var qs = {
        type: getQueryString()["type"],
        family: getQueryString()["family"]
    };
    
    if(window.location.href.indexOf('type=') != -1) {
        weatherby_video_sort_type(qs.type);
    }
    if(window.location.href.indexOf('type=') != -1 && window.location.href.indexOf('family=') != -1) {
        weatherby_video_sort_family(qs.type, qs.family);
    }
}


/* --------------------------
 * UTILITY FUNCTIONS
 * -------------------------- */ 

// Add/Remove second select options
function add_select_options(productsArray){
    for (i = 0; i < productsArray.length; i++) {
        $('<option/>').val(productsArray[i].option).html(productsArray[i].title).appendTo('#sort-family');
    }
}
function remove_select_options(sortItem){
    $('#sort-family').children().remove();
    $('#sort-family').html('<option value="'+sortItem+'">--</option');
}

// Character Truncate
String.prototype.truncate = function(length){
    var length = (typeof(length) == "undefined") ? 25 : length;
    var pattern = new RegExp('^.{0,' + length + '}[\S]*');
    var re = this.match(pattern);
    var l = re[0].length;
    var re = re[0].replace(/\s$/,'');
    if(l < this.length)
        re = re + "&hellip;";
    return re;
}

// Parse a URL for query string
function getQueryString() {
  var result = {}, queryString = location.search.substring(1),
      re = /([^&=]+)=([^&]*)/g, m;

  while (m = re.exec(queryString)) {
    result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
  }

  return result;
}

