$(document).ready(function() {

		// create tabbed content areas
		// uses jQuery UI tabs plugin - http://ui.jquery.com/
			$('div.tabbed>ul').tabs({ remote: true });
			$('div.tabbed ul.tabs li a').focus(function(){
				this.blur();
			});
		// create tabbed content areas
		// uses jQuery UI tabs plugin - http://ui.jquery.com/
			$('div#regtabbed>ul').tabs({ remote: true });
			$('div#regtabbed ul.tabs li a').focus(function(){
				this.blur();
			});


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];
}

var genres = gup('genres');
var section = parseInt(gup('section'));
var media_id = parseInt(gup('media_id'));
var start = parseInt(gup('start'));
var limit = parseInt(gup('limit'));
var total = parseInt(gup('total'));
var page_title = unescape(gup('page'));

if (page_title) {
        $('#vid_title').html('<h3>' + page_title + ' Videos</h3>');
}

if (!section) {

        if (set_section) {
                var section = set_section;
                }
                else {section = '106';}
                //alert('Section = ' + section);
}

if (!genres) {
        var cat = '&group_ids=6029';
        genres = '';
        $('#vid_title').html('<h3>All Videos</h3>');
}
else {
        var cat = '&genre_ids=' + genres;
}

if (media_id) {
        //var start = 0; var limit = 10;
        userCred(media_id);
        sendRequest('/cgi-bin/php/ajax/apiproxy.php?vmix=media.php?action=getMedia&media_id=' + media_id, getClip);
        sendRequest('/cgi-bin/php/ajax/apicommentproxy.php?vmix=comments.php?action=getComments&target_id=' + media_id, getComments);
        $('#firstVideo').show();
}

if (!start) {
        var start = 0; var limit = 10;
    }
    
var proxy = '/cgi-bin/php/ajax/apiproxy_medialist.php?vmix=media.php?action=getMediaList' + cat + '&limit=' + limit + '&start=' + start;
//alert(proxy);
getClips(page_title, section, genres, start, limit, proxy);

var options = {
target: '#vid_addcomments', // target element(s) to be updated with server response
dataType: 'json',
success: function() {
var message = '<b>Thank you for your comment! Your comment will be reviewed and once approved be made visible.</b>';
$("#vid_addcomments").html(message);
}
};
$('#comment_form').submit(function() {
$(this).ajaxSubmit(options);
return false;
});


$('.auto-submit-star').rating({
required:true,
callback: function(value, link){
$("#vid_user_rate").html('<b>Thank you for your vote!</b>').hide("slow");
}});

$('.scrollpane').jScrollPane({showArrows:true, scrollbarWidth: 15, arrowSize: 16});

    $("#vid_genres").change(function () {
          var str = '';
          $("select option:selected").each(function () {
                str += $(this).val();
                page_title = escape(jQuery.trim($(this).text()));
                var url = 'http://pubsys2.thatsracin.com/' + section + '/index.html?genres=' + str + '&section=' + section + '&media_id=&start=&limit=&total=&page=' + page_title;                
                window.location = url;
              });
        })

// END DOCUMENT READY

});

//Request Functions
function sendRequest(url,callback,postData) {
	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);
	}
	if (req.readyState == 4) return;
	req.send(postData);
}

var XMLHttpFactories = [
	function () {return new XMLHttpRequest()},
	function () {return new ActiveXObject("Msxml2.XMLHTTP")},
	function () {return new ActiveXObject("Msxml3.XMLHTTP")},
	function () {return new ActiveXObject("Microsoft.XMLHTTP")}
];

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) {
	var myClip = eval('(' + req.responseText + ')');
	var title = myClip.title;
	var description = myClip.description;
	var token = myClip.token;
        newgenre_desc = getGenres(myClip.genres);
	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="620" height="349" name="UnifiedVideoPlayer" align="middle" play="true" loop="false" quality="high" allowScriptAccess="always" allowFullScreen="true" wmode="transparent" type="application\/x-shockwave-flash" flashvars="player_id=a148634ee30b037db8c7c796857ff919&token=' + token +'" pluginspage="http:\/\/www.adobe.com\/go\/getflashplayer"><\/embed><\/div>';
	str+='<div class="videoinfo"><h3>' + title + '<\/h3>';
        str+='<div class="">' + myClip.duration + ' Seconds | ' + myClip.total_views +' Total Views | <a href="http://pubsys2.thatsracin.com/106/index.html?media_id=' + myClip.id + '">Permalink</a> | ' + newgenre_desc +'</div>';
	str+='<p>' + description + '<\/p></div>';
	str+='<\/div><\/div>';

    $('#vid_clip').html(str);
	}

function getComments(req) {
var myObject = eval('(' + req.responseText + ')');
var comments_array = myObject.comment;
        var str = '';
	if (comments_array) {
        $('#vid_comments').css('height','130px');
	str = '<div class="holder osX"><div class="scrollpane"><table class="zebra">';
		jQuery.each(comments_array, function() {
                    createDate = this.date_created;
                    myDate = createDate.split(" ");
                    myDateParts = myDate[0].split("-");
                    newDate = myDateParts[1] + '/' + myDateParts[2] + '/' + myDateParts[0];
			str += '<tr><td><b>Posted by: ' + this.username + '</b><br/>';
	                str += this.value;
			str += ' <i>(' + newDate + ' at ' + myDate[1] + ')</i></td></tr>';
		});
                        str += '</table></div></div>';
	} else {
                $('#vid_comments').css('height','20px');
		str += '<div id="first_comment">Click the Add Comment tab above and be the first!</div>';
	}
        
    $('#vid_comments').html(str);
}

function getRatings(req) {
                var str = '<b>Popularity: </b>';
                var c = 1;
                var myRatings = eval('(' + req.responseText + ')');
                var stars = Math.round(myRatings.average);
                while(c <= 5) {
                    if (c == stars) {
                        str += '<input name="star1" type="radio" class="star" checked="checked" disabled="disabled"/>';
                    } else {
                        str += '<input name="star1" type="radio" class="star" disabled="disabled"/>';
                    }
                    c = c + 1;
                }
                $('#vid_ratings').html(str);
}

function addComment(req){
    var myComment = eval('(' + req.responseText + ')');
    alert('Comment added!');
}

function getClips(page_title, section, genres, start, limit, proxy) {


var str='';
str+='<script type="text/javascript">';
str+='$(document).ready(function() {';
str+='      $(\'div#vid_clips li\').hover(';
str+='      function () {';
str+='        $(this).css({\'border-color\':\'#eb272b\', \'background\':\'#F6FCFF\'});';
str+='      }, ';
str+='      function () {';
str+='        $(this).css({\'border-color\':\'#cccccc\', \'background\':\'#ffffff\'});';
str+='      }';
str+='    );';
str+='});';
str+='<\/script>';


        sendRequest(proxy, function(req) {
                var myClips = eval('(' + req.responseText + ')');
                console.log('MY CLIPS: ', myClips);
                var media_array = myClips.media;
                var total = myClips.total_count - 1;
                str += '<div class="contentlist-horz">';
				str += '<ul>';
                jQuery.each(media_array, function() {
                var token = this.token;
                id = this.id; title = this.title; description = this.description;

                // Get other Genres
                newgenre_desc = getGenres(this.genres, section);

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

function getGenres(genre_list, section) {
                var genre_desc = '';
                jQuery.each(genre_list, function() {
                genre_desc += '<a href="http://pubsys2.thatsracin.com/' + section +'/index.html?genres=' + this.genre_id + '&section=' + section + '&media_id=&start=&limit=10&total=&page=' + escape(this.name) + '">' + this.name + '</a>, ';
                });
                var newgenre_desc = genre_desc.substring(0, genre_desc.length-2);
                return newgenre_desc;
}

function userCred(media_id) {
var insiteUser = getInsiteUserName(insitecookie);
//var insiteUser = -1;
//alert('INSITE: ' + insiteUser);
if ( -1 == insiteUser) {
    $('#vid_addcomments').html('You must <a href="/member_services">login</a> to comment.');
    }
    else {
        var str='';
        str+='<form id="comment_form" action="/cgi-bin/php/ajax/commentproxy.php">';
        str+='<input type="hidden" name="vmix" value="comments.php?action=addComment"\/>';
        str+='<input type="hidden" name="target_id" value="' + media_id + '"\/>';
        str+='<b>Your Name:</b><br \/>';
        str+='<input type="hidden" name="user_id" value="' + insiteUser + '"\/>';
        str+='<b>' + insiteUser + '</b>';
        str+='<br \/><br \/>';
        str+='<b>Your Comment:</b><br \/>';
        str+='<textarea name="value" cols="45" rows="3"><\/textarea><br \/>';
        str+='<input type="button" value="Cancel"\/> <input type="submit" value="Submit"\/>';
        str+='<\/form>';
        $('#vid_addcomments').html(str);
        }
}

function buildNav(section, genres, start, limit, total, page_title) {
        var endpoint = start + limit;
        var prevpoint = start - limit;
        var prev = ''; 
        var next = '';
        var nav = '';
        var place = '';
        
        //alert('buildNav: start ' + start + ' | limit ' + limit + ' | total ' + total + ' | endpoint ' + endpoint + ' | prevpoint ' + prevpoint);

        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="http://pubsys2.thatsracin.com/' + section +'/index.html?genres=' + genres + '&section=' + section + '&media_id=&start=' + prevpoint +'&limit=' + limit +'&total=' + total + '&page=' + escape(page_title) + '">&laquo; Previous</a>';
                }
        
        if (total > endpoint) {
                next += '<a href="http://pubsys2.thatsracin.com/' + section +'/index.html?genres=' + genres + '&section=' + section + '&media_id=&start=' + endpoint +'&limit=' + limit +'&total=' + total + '&page=' + escape(page_title) + '">Next &raquo; </a>';
                }

        if (prev && next) {
                nav += prev + ' | ' + next;
        }
        else {
                nav += prev + next;
        }

        $('#vid_clips').append(nav);
}

function getNewclip(media_id) {
        //alert(media_id);
        $('#firstVideo').hide();
        sendRequest('/cgi-bin/php/ajax/apiproxy.php?vmix=media.php?action=getMedia&media_id=' + media_id, getClip);
        sendRequest('/cgi-bin/php/ajax/apicommentproxy.php?vmix=comments.php?action=getComments&target_id=' + media_id, getComments);
        userCred(media_id);
        $('#firstVideo').show();
        window.scrollTo(0,0);
        return false;
}

