// THIS SCRIPT REQUIRES THE USE OF JQUERY 1.3
// CONFIG VARIABLES

var vmix_section = '789';
var vmix_limit = 10; 
var vmix_path = 'cgi-bin/php/ajax/';
var vmix_domain = 'http://www.charlotteobserver.com/';
var vmix_author = 'charlotte.com';
var vmix_title = 'Our Videos';
var vmix_message = '<b>Thank you for your comment! Your comment will be reviewed and once approved be made visible.</b>';
var vmix_ty = '<b>Thank you for your vote!</b>';
var vmix_first = 'Click the Add Comment tab above and be the first!';
var vmix_disclaimer = '<p class="disclaimer"> The Charlotte Observer is pleased to be able to offer its users the opportunity to make comments and hold conversations online. However, the interactive nature of the internet makes it impracticable for our staff to monitor each and every posting.</p><p class="disclaimer"> Since charlotte.com does not control user submitted statements, we cannot promise that readers will not occasionally find offensive or inaccurate comments posted on our website. In addition, we remind anyone interested in making an online comment that responsibility for statements posted lies with the person submitting the comment, not The Charlotte Observer. </p><p class="disclaimer">If you find a comment offensive, clicking on the exclamation icon will flag the comment for review by the administrators, we are counting on the good judgment of all our readers to help us.</p>';
var vmix_spinner = 'spinner_mac.gif';
var vmix_wait = 'Please wait as video loads...';

// The following videoplayer information is retrieved by setting up a player in the vmix admin
var vmix_width = '560';
var vmix_height = '373';
var vmix_id = '67da357a6a5d4b942a6b017d6c58f2c7';

// This is the path to you member services page
var vmix_login = '/member_services';
var vmix_loginmsg = 'You must <a href="/member_services">login</a> to comment.';

// Vmix genres for the dropdown can be added as follows ['genre id','genre name']
var vmix_cats = new Array(['446','News'],['447','Sports']);

// It's nice to have the window pop back up to the top of the video when a user clicks a video. Set x,y coordinates here
var vmix_x = 0;
var vmix_y = 0;

// END CONFIG VARIABLES

// DOCUMENT.READY

$(document).ready(function() {
    
  // At this point we are setting up the parameters for what we are looking for
  // Some information is passed in the URL string
  var genres = gup('genres');
  var media_id = gup('media_id');
  var start = parseInt(gup('start'));
  var total = parseInt(gup('total'));
  var page_title = unescape(gup('page'));
  
  // Do we need a different page title for a different genre?
  if (page_title) {
    $('#vid_title').html(page_title + 'Videos');
  }
  else {
    $('#vid_title').html(vmix_title);
  }
  
  // Are we looking for a particular genre?
  if (!genres) {
    var cat = '&genre_ids=6011';
  }
  else {
    var cat = '&genre_ids=6011';
  }
  
  // Have we been sent here via a direct link?
  if (!start) {
        var start = 0;
    }
  
  if (media_id != '') {
    getNewclip(media_id);
  }
  
  //Default request, which is a medialist from Vmix starting at 0 and set to paginate.
  var proxy = vmix_domain + vmix_path + 'apiproxy_v2.php?miaction=list&vmix=media.php?action=getMediaList' + cat + '&limit=' + vmix_limit + '&start=' + start;
  getMediaList(proxy, start, page_title, genres);
  
});

// END DOCUMENT READY, START FUNCTIONS

// GET SINGLE VIDEO CLIP + THE COMMENTS

function getNewclip(media_id) {
        //alert(media_id);
        $('#firstVideo').hide();
        proxy = vmix_domain + vmix_path + 'apiproxy_v2.php?miaction=single&vmix=media.php?action=getMedia&media_id=' + media_id;
        $.getJSON(proxy, function(video){
        //console.log('Single Item: ', video);
	var str='';
	str+='<div class="box"><div class="box2"><div id="embed_player">';
        str+='<div id="clip_loader"></div>';
        str+='<embed id="player_swf" src="http:\/\/media.vmixcore.com\/core-flash\/UnifiedVideoPlayer\/UnifiedVideoPlayer.swf" quality="high" width="' + vmix_width + '" height="' + vmix_height + '" name="UnifiedVideoPlayer" align="middle" play="true" loop="false" quality="high" allowScriptAccess="always" allowFullScreen="true" wmode="transparent" type="application\/x-shockwave-flash" flashvars="player_id=' + vmix_id + '&token=' + video.token +'" pluginspage="http:\/\/www.adobe.com\/go\/getflashplayer"><\/embed><\/div>';
	str+='<div class="videoinfo"><h1>' + video.title + '<\/h1>';
        str+='<div class="byline">' + video.duration + ' Seconds | ' + video.total_views +' Total Views | <a href="' + vmix_domain + vmix_section +  '/index.html?media_id=' + video.id + '">Permalink</a></div>';
	str+='<p>' + video.description + '<\/p></div>';
	str+='<\/div><\/div>';

    // Insert the HTML into the video clip div
    $('#vid_clip').html(str);
    //userCred(media_id);
    });
    
    
    // Turn the wrapper div on so the user can see the video clip
    $('#firstVideo').show();
    window.scrollTo(vmix_x,vmix_y);
}


// GET MEDIA LIST

function getMediaList (proxy, start, page_title, genres) {

  // Need to create a javascript function so each video can be clicked
  var str = '';
  str += '<script type="text/javascript">';
  str += '$(document).ready(function() {';
  str += '      $(\'div.story-highlight\').hover(';
  str += '      function () {';
  str += '        $(this).css(\'background\', \'#EDF3F5\');';
  str += '      }, ';
  str += '      function () {';
  str += '        $(this).css(\'background\',\'#FFFFFF\');';
  str += '      }';
  str += '    );';
  str += '});';
  str += '<\/script>';
  str += '<div class="highlights">';
  
    $.getJSON(proxy, function(data){
      //console.log('MediaList', data); // for troubleshooting
      var total = parseInt(data.total_count-1);
      //console.log('Total Count', total); // for troubleshooting

      $.each(data.media, function(i,video){

                str += '<div class="story-highlight" onclick="javascript:getNewclip(\''+ video.id + '\');">';
                str += '<div class="clearfix">';
                str += '<div class="img f-left">';
        
                if (typeof video.thumbnail[0] != 'undefined') {
                str += '<a href="javascript:void(0);"><img src="http://image.vmixcore.com/imgman.jpg?url=' + video.thumbnail[0].url + '&width=150&fill=000000000" alt="' + video.title + '" /></a>';
                }
                str += '</div>';
                str += '<div class="teaser"><div class="title"><a href="javascript:void(0);">' + video.title + '</a></div>';
                str += '<div class="byline">' + video.duration + ' Seconds | ' + video.total_views +' Total Views | <a href="' + vmix_domain + vmix_section +'/index.html?media_id=' + video.id + '">Permalink</a> </div>';
                str += '<p>' + video.description + '</p></div></div></div>';
      }); // End .each function
      
                //str += '</div>';
                //$('#vid_categories').show();
                $('#vid_clips').empty();
                $('#vid_clips').html(str);
                buildNav(genres, total, start, page_title);
      });
}


// BUILD NAVIGATION FUNCTION, THIS IS CONVOLUTED, BUT WORKS

function buildNav(genres, total, start, page_title) {
  
        var endpoint = start + vmix_limit;
        var prevpoint = start - vmix_limit;
        var prev = ''; 
        var next = '';
        var nav = '';
        var place = '';
        
        if (start == 0) {
          if (endpoint > total){
            nav = '<b>Viewing: 1 - ' + (total + 1 )+ ' of ' + (total + 1) + ' total</b><br /><br />';
          }
          else {
            nav = '<b>Viewing: 1 - ' + endpoint + ' of ' + total + ' total</b><br /><br />';                        
          }
        }
        
        if (start > 0) {
          if (endpoint > total) {
          nav = '<b>Viewing: ' + start + ' - ' + total + ' of ' + total + ' total</b><br /><br />';
          }
          else {
          nav = '<b>Viewing: ' + start + ' - ' + (endpoint - 1) + ' of ' + total + ' total</b><br /><br />';
          }
          if (prevpoint < 0) {prevpoint = 0;}
          prev = '<a href="' + vmix_domain + vmix_section +'/index.html?genres=' + genres + '&media_id=&start=' + prevpoint +'&limit=' + vmix_limit +'&total=' + total + '&page=' + escape(page_title) + '">&laquo; Previous</a>';
        }
        
        if (total > endpoint) {
          next += '<a href="' + vmix_domain + vmix_section +'/index.html?genres=' + genres + '&media_id=&start=' + endpoint +'&limit=' + vmix_limit +'&total=' + total + '&page=' + escape(page_title) + '">Next &raquo; </a>';
        }
        
        if (prev && next) {
          nav += prev + ' | ' + next;
        }
        else {
          nav += prev + next;
        }
        //alert(nav);
        $('#vid_clips').append(nav);
  
}

// FUNCTION TO PARSE PARAMETERS OFF URL STRINGS

function gup(name)
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}