var media_id; // Video for main area
var genre_id; // List of videos
var genreID; //for transmitting to VMIX
//var start;
var defaultGenreID = 4275; // Set default video list

function switchVideoList(gid,start,media_id){
// Get genreID from onclick event
//alert('start in switchvideo:' + start + ' and genre id is:' + gid + 'and media id is' + media_id);

//alert('media id in morevideo_preview is:' +media_id);

if ((start == '') || isNaN(start) || (start==undefined)) { start = 0; }
if ((gid == '') || isNaN(gid) || (gid==undefined)) { gid = defaultGenreID; }

//alert('genre id is:' + gid + 'and media id is: ' + media_id);

	if (media_id)
	{
		loadVmixMainArea(genreID,media_id)
	}
	loadVmixGridArea(gid,start,media_id);

	return;
}	

// -----------------------------------------------------------------

function prepVideoID() {
// Get request string element pairs	
//alert("Entering prepVideoID");
//g = parseGetVars(); 

//alert(g); 
	for (var i in g) {
		//alert(i+'='+g[i]);
		if (i == "media_id") {
			media_id = g[i];
		} else if (i == "genre_id") {
			genre_id = g[i];
		}
	}		
	if (genre_id) {
		//alert("genre_id query string: " + genre_id);
		genreID = genre_id;
	} else {
		//alert("No genre_id query string, assigning default genre: " + defaultGenreID);
		genreID = defaultGenreID;
	}
}

// -----------------------------------------------------------------

function parseGetVars() {
	var getVars = new Array();
	var qString = unescape(top.location.search.substring(1));
	//alert(qString);
	if (qString) { // Check that there is a query string
		//alert("qString");
		var pairs = qString.split(/\&/);
		for (var i in pairs) {
			var nameVal = pairs[i].split(/\=/);
			getVars[nameVal[0]] = nameVal[1];
			//alert("nameVal: "+nameVal[0]+", "+nameVal[1]);
		}
		//alert("getVars: "+getVars);
		return getVars;
	}
	else {
		return false;
	}
}

// -----------------------------------------------------------------

function sendRequest(url,callback,postData,start,genreID,media_id) {

	var req = createXMLHTTPObject();
	if (!req) return;
	var method = (postData) ? "POST" : "GET";
	req.open(method,url,true);
	req.setRequestHeader('User-Agent','XMLHTTP/1.0');

	if (postData)
req.setRequestHeader('Content-type','application/x-www-form-urlencoded');

req.onreadystatechange = function () {
		if (req.readyState != 4) return;
		if (req.status != 200 && req.status != 304) {
//			alert('HTTP error ' + req.status);
			return;
		}
		callback(req,start,genreID,media_id);
	}
	if (req.readyState == 4) return;
	req.send(postData);
}

// -----------------------------------------------------------------

function createXMLHTTPObject() {
	var xmlhttp = false;
	for (var i=0;i<XMLHttpFactories.length;i++) {
		try {
			xmlhttp = XMLHttpFactories[i]();
		}
		catch (e) {

			continue;
		}
		break;
	}
	return xmlhttp;

}

// -----------------------------------------------------------------

function getClip (req,start,genreID,media_id) {

	var myClip = eval('(' + req.responseText + ')');
	var title = "";
	var description = "";
	var author = "";
	if (myClip.title) {
		title = myClip.title;
		description = myClip.description;
		author = myClip.author;
	}
	var token = myClip.token;
	var media_id = myClip.id;
	var str='';
	str+='<div class="videoinfo"><h1>' + title + '<\/h1><\/br><p>' + author + '<\/p><\/div>';
	str+='<div class="box"><div class="box2"><div id="embed_player">';
	str+='<embed id="player_swf" src="http:\/\/media.miamiherald.com\/static\/multimedia\/channels\/VideoPlayer-SectionFront.swf" quality="high" width="640" height="392" name="UnifiedVideoPlayer" align="middle" play="true" loop="false" quality="high" allowScriptAccess="always" allowFullScreen="true" wmode="transparent" type="application\/x-shockwave-flash" flashvars="player_id=401b7ca7fd61e67bcb94ebabbacd1847&token=' + token + '&media_id=' + media_id + '" pluginspage="http:\/\/www.adobe.com\/go\/getflashplayer"><\/embed><\/div>';
	str+='<\/div><\/div>';
	str+='<div class="videoinfo"><p>' + description + '<\/p><\/div>';

	$('#vid_clip').html(str);
//window.location.hash="green_nav_grid";
}

// -------------------------------------------------------------------------------

function getClips(req,start,genreID,media_id) {

//if ((genreID == '') || isNaN(genreID) || (genreID==undefined)) 
//{ genreID = defaultGenreID; }
//alert('medai id is: ' + media_id);

        var myClips = eval('(' + req.responseText + ')');
	var media_array = myClips.media;
	var total = myClips.total_count;
	var str ='<ul class="media">';
	
	for (i=0; i < media_array.length; i++)
	{
        var token = media_array[i].token;
        var thumb_array = media_array[i].thumbnail;
        var thumb = thumb_array[0].url;
        var vmix_id = media_array[i].id;
        
        var id = "";
        var title = "";
        var description = "";
        var author = "";
        
		id = media_array[i].id;
		title = media_array[i].title;
		description = media_array[i].description;
		var full_description = description;
		
		//truncate desc to 150 chars
		description = (description.length > 165) ? description.substring(0,165)+'...' : description;
		author = media_array[i].author;
        
        if (((media_id == 'first_video') || (!media_id)) && (media_id != undefined)) {
//alert('media id in the if statement is: ' + media_id);
	        media_id = '1';
			var str2;
			str2='';
			str2+='<div class="videoinfo"><h1>' + title + '<\/h1><\/br><p>' + author + '<\/p></div>';
			str2+='<div class="box"><div class="box2"><div id="embed_player">';
			str2+='<embed id="player_swf" src="http:\/\/media.miamiherald.com\/static\/multimedia\/channels\/VideoPlayer-SectionFront.swf" quality="high" width="640" height="392" name="UnifiedVideoPlayer" align="middle" play="true" loop="false" quality="high" allowScriptAccess="always" allowFullScreen="true" wmode="transparent" type="application\/x-shockwave-flash" flashvars="player_id=401b7ca7fd61e67bcb94ebabbacd1847&token=' + token + '&media_id=' + vmix_id + '" pluginspage="http:\/\/www.adobe.com\/go\/getflashplayer"><\/embed><\/div>';
			str2+='<\/div><\/div>';
			str2+='<div class="videoinfo"><p>' + description + '<\/p></div>';
			$('#vid_clip').html(str2);
	}
        
var desc_esc = escape_quotes(full_description);
var title_esc = escape_quotes(title);
var author_esc = escape_quotes(author);

//desc_esc = '';
full_description = '';

        str += '\n\n<li>';
        str += '<div class="image_highlight">';
//        str += '<a href="/508/index.html?media_id=' + id + '&genre_id=' + genreID+ '">';
       str += "<a onclick='LoadUserImage("+'"'+id +'","'+ genreID+'","'+token+'","'+title_esc+'","'+author_esc+'","'+desc_esc+'"'+");' "+ ' href=#>';
        var thumburl = 'http://image.vmixcore.com/imgman.jpg?url=' + thumb + '&width=80&fill=000000000';
        str += '<img src="' + thumburl + '" alt="' + title + '" /></a></div>';
        str += "<h2><a onclick='LoadUserImage("+'"'+id +'","'+ genreID+'","'+token+'","'+title_esc+'","'+author_esc+'","'+desc_esc+'"'+");' "+ ' href=#>' + title + '</a></h2>';
        str += '<p>' + description + '</p></li>';
	}
	str += '</ul>';
//alert(str);
	//str += '<p><a href="/508/index.html?start=10&limit=20&total=' + total + '">Next &raquo;</a><p>';
    
var viewing = "<br><span id='viewvideos' style='text-align:center;padding:7px;'>";

    if (total < media_array.length) {
		viewing += '<b>Viewing videos 1-' + total + ' of ' + total + ' total.</b></span>';
    } else {
		viewing += '<b>Viewing videos 1-' + media_array.length + ' of ' + total + ' total.</b></span>';
	}      

if ((start == '') || isNaN(start)) { start = 0; }
start = parseInt(start) + 20;	

var prev = '';
var next = '';

if (start < total)
{
next = '<span style="vertical-align:top;text-align:right;padding-right:30px;right:0px;"><b> <a href="#green_nav_grid" onclick="javascript:switchVideoList(\''+genreID+'\',\''+start+'\');">Next</a> &gt;</b></span>';
//next = '<span style="vertical-align:top;text-align:right;padding-right:30px;right:0px;"><b> <a href="#" onclick="javascript:switchVideoList(\''+genreID+'\',\''+start+'\');">Next</a> &gt;</b></span>';
}

if (parseInt(start-40) >= 0)
{
var tempstart = parseInt(start);
var previous_start = tempstart - parseInt(40);
//var previous_start = 0;
//alert('previous start is:'+ previous_start + ':');
prev = '<span style="vertical-align:top;text-align:left;padding-left:30px;left:0px;"><b>&lt; <a href="#green_nav_grid" onclick="javascript:switchVideoList(\''+genreID+'\',\''+previous_start+'\');">Prev</a></b></span>';
//prev = '<span style="vertical-align:top;text-align:left;padding-left:30px;left:0px;"><b>&lt; <a href="#" onclick="javascript:switchVideoList(\''+genreID+'\',\''+previous_start+'\');">Prev</a></b></span>';
}

// ---------------  GETTING THE PAGES -----------------

var mypages = '';
mypages = pageinate(total, genreID,start);

var more_pages  = '<div style="width:400px;text-align:center;margin-left:300px;">' + prev  + ' &nbsp;&nbsp;' + mypages + ' &nbsp;&nbsp;' + next  + '</div>';

str =more_pages + '<br>' + str + '<br><br>' + more_pages;

//alert(genreID);
selectProperTab(genreID)
	$('#vid_clips').html(str);
}

function escape_quotes (mystring){
var etr = mystring.replace(/\n/g," ");
etr = etr.replace(/'/g,"%27");
etr = etr.replace(/"/g,"%27");
etr = etr.replace(/\//g,"");
return etr;
}

function selectProperTab(genreID){
	$("#4275").removeClass("x");
	$("#"+genreID).addClass("x");
	$("#"+genreID).parents(".subnav_bottom").show();
	var subnavTab1 = $("#"+genreID).children("a").attr("class");
	$("#"+subnavTab1).show();
	var subnavTab = $("#"+genreID).parents(".subnav_bottom");
	$("li:contains("+subnavTab+")").addClass("x");
}

function loadVmixMainArea(genreID,media_id){
	// Fills in top area
//alert('g: ' + genreID +  ' m: ' + media_id);
var start = '';
	sendRequest('/cgi-bin/ajax/apiproxy.php?vmix=media.php?action=getMedia&media_id=' + media_id, getClip,'',start,genreID,media_id);
}

function loadVmixGridArea(genreID,start,media_id){
	// Fills in bottom area
//alert('start in loadvmixgridarea: ' + start);	
var vmix_url = 'apiproxy_medialist.php?vmix=media.php?action=getMediaList&genre_ids='+genreID+'&limit=20&start='+start;
//alert('vmix url is: ' + vmix_url);
//alert('genre id in loadvmixgridarea is: ' + genreID);
sendRequest('/cgi-bin/ajax/apiproxy_medialist.php?vmix=media.php?action=getMediaList&genre_ids='+genreID+'&limit=20&start='+start, getClips,'',start,genreID,media_id);
//alert('after call to send request');
}

var g = parseGetVars(); // Prep array of request string pairs

prepVideoID();

var XMLHttpFactories = [ // Prep XML objects
	function () {return new XMLHttpRequest()},
	function () {return new ActiveXObject("Msxml2.XMLHTTP")},
	function () {return new ActiveXObject("Msxml3.XMLHTTP")},
	function () {return new ActiveXObject("Microsoft.XMLHTTP")}
];	

// ------------------------------------------------------
//                           PAGEINATE
// This function creates the digits for each page.
// Each digit is a link
// ------------------------------------------------------

function pageinate(total, genreID,start)
{
var pages = '';               // this var holds the 'digit' links
var limit = 20;               // the max # of videos that we're pulling per grid
var t;
var current_start;          // holds the start for the vmix api call
var div = total/limit;      // approx # of pages(grids) that we will have
var page = start/limit;   // current page that we're on
var mod = total%limit;  // this is the number of videos on the very last page

if (mod == 0)               // if the total perfectly divisible by 20
{
     laststart =  total - limit ;
     lastpage = div;
} else  {
      laststart = total - mod;
      lastpage = div + 1;
}

if (laststart < 0) { laststart = 0; lastpage = 1; }

var numofpages = lastpage;

if (numofpages > 1)
{
var t_start = page-4;
var t_end = page + 3;

   if (t_start <= 0)
   {
          t_end = 7;
          t_start = 0;
    }

    if (total < (limit * t_end))
    { 
        t_end = div; //Math.round(total/limit); 
     }

  for (t=t_start; t < t_end; t++)
  {
      if (t ==0) { t_show = 1; } else { t_show = t + 1; }

      current_start = limit * t;
      if (t ==0) { current_start = 0; }

       if (current_start > total)
      { current_start = laststart; }

      if (t_show == page)
     { pages += "&nbsp;<b>" + t_show + "</b>"; }
      else
      {
          // if (t <= numofpages)
                      
                pages += ' &nbsp;<a href="#" onclick="javascript:switchVideoList(\''+genreID+'\',\''+current_start+'\');">' + t_show +'</a> '; 
          //  } //if
      } // else
   } // for
} // if
//pages += '<br><br>t_start: ' + t_start + ' , t_end: ' + t_end;
return pages;
}
// ------------------------------------------------------
