
/* ================================================================ 
This copyright notice must be untouched at all times.

The original version of this script and the associated (x)html
is available at http://www.stunicholls/gallery/left_right_click.html
Copyright (c) 2005-2007 Stu Nicholls. All rights reserved.
This script and the associated (x)html may be modified in any 
way to fit your requirements.
=================================================================== */
var request;
var videoName;
var selectedUser;
var selectedVideo;

function initSelectedVideo(gallery,video) {
    videoInfo = {};

    selectedVideo = document.getElementById(gallery).getElementsByTagName("LI")[0];

    if(window.location.hash){
	videoInfo = {'redirect':window.location.hash};
    }
    else{
	if(video['user'] || video['key']){
	    videoInfo = video;
	}else{
	    videoInfo = {'selectedVideo':selectedVideo,'autoplay':"0",'vertical':video['vertical'],'criterion':video['criterion']};
	}
    }
    getSelectedVideoInfo(videoInfo);
}

function hideExtraVideos(gallery, numVideos) {
        var getLi = document.getElementById(gallery).getElementsByTagName("LI");

        var num = (numVideos < getLi.length) ? numVideos : getLi.length;

        for (var x=1; x<num; x++){
            getLi[x].className=getLi[x].className.replace(/hide/g, "");
        }
        for (var x=getLi.length-1; x>num-1; x--) {
                    getLi[x].className = "hide";
        }
}

function leftArrowClick(gallery, numVideos) {
    var getLi = document.getElementById(gallery).getElementsByTagName("LI");
    for (var x=getLi.length-1; x > 0; x--) {
	if ((getLi[x].className.indexOf('chosen'))!=-1) {
	    getLi[x].className=getLi[x].className.replace("chosen", "");
	    //x--;
	    x -= numVideos;
            
	    if (x < 0) {
		x = 0;
	    }

	    if (x > -1){
		getLi[x].className+="chosen";
                if(gallery == "gallery_top"){
		    selectedVideo = getLi[x];
		}
		for(var i=0; i<getLi.length; i++){
		    if(i<x || (i >= x+numVideos)){
			getLi[i].className+=" hide";
		    }else{
			getLi[i].className=getLi[i].className.replace(/hide/g, "");
		    }
		}
	    }
	}
    }
}

function rightArrowClick(gallery, numVideos) {
    var getLi = document.getElementById(gallery).getElementsByTagName("LI");

    for (var x=0; x < getLi.length; x++) {
	//        alert ("for x "+ x);
        if ((getLi[x].className.indexOf('chosen')) != -1)	{
	    //	    alert("if x "+ x); 
	   getLi[x].className=getLi[x].className.replace("chosen", "");

           if(x == (getLi.length - 1 - numVideos)){ 
	       x = 0;
	       //               alert("getLi.length -1 - numVideos "+ x);
	   }else{
	   //x++;
	   //	   alert(Math.ceil(x/numVideos));
	   x = numVideos * (Math.floor(x/numVideos));

	   x += numVideos;
	   //           alert ("else x "+x);
	   }
	   //	   alert("x "+x);
	   if (x >= getLi.length -1) {
	       x = 0
	   }else {
	       if((getLi.length -1  - x) < numVideos){
		   x = getLi.length - numVideos ;
	       }
	   }
	   //	   alert("after x "+x);
	   if( x < getLi.length){
	      getLi[x].className+="chosen";
	      if(gallery == "gallery_top"){
		  selectedVideo = getLi[x]; 
	      }
              for(var i=0;i<getLi.length;i++){
		  //                  alert("last for "+x)
		  if(i < x || i >= x+ numVideos){		 
		      getLi[i].className+=" hide";
		  }else{
		      getLi[i].className=getLi[i].className.replace(/hide/g, "");
		  }
	      }
	   }
	}
    }
}


function clickMenu (gallery, numVideos) {
	var getImg = document.getElementById(gallery).getElementsByTagName("IMG");
	var getLi = document.getElementById(gallery).getElementsByTagName("LI");

	hideExtraVideos(gallery, numVideos);
}


function createRequest(){
    var request = null;
    try{
        request = new XMLHttpRequest();
    }catch(trymicrosoft){
	request = new ActiveXObject("Microsoft.XMLHTTP"); 
    }

    return request;
}

function selectVideo(selectedLi, vertical, videoInfo) {

    if (selectedVideo) {
       selectedVideo.className = selectedVideo.className.replace("chosen","");
    }
    selectedVideo = selectedLi;
    selectedVideo.className = "chosen";
    getSelectedVideoInfo({'selectedVideo':selectedVideo,'vertical':vertical,'semanticinfo':videoInfo});
}

function urlencode(str) {
    return escape(str).replace(/\+/g,'%2B').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
}

function urldecode(str) {
    return unescape(str.replace(/%2B/g,'+').replace(/%2A/g,'*').replace(/%2F/g,'/').replace(/%40/g,'@'));
}

function getSelectedVideoInfo(input){
    var requestSelected;

    var user, video, vertical, series_criterion, key = "", site = "", url_params;
    var autoplay = "1"

    if (input['autoplay']){
	   autoplay = input['autoplay'];
    }

    if (input['vertical']){
       vertical = input['vertical'];
    }

    if(input['redirect']){
	url_params = input['redirect'].substring(1);
	arr = url_params.split("&");
	for(i = 0 ; i < arr.length; i++){
	    if(arr[i].match("^video=")){
		video = urldecode((arr[i].split("="))[1]);
	    }
	}        
    }
    else{
	if (input['selectedVideo']){
	    selectedVideo = input['selectedVideo'];
	    user = selectedVideo.getElementsByTagName('input')[0].value;
	    video = selectedVideo.getElementsByTagName('input')[1].value;
	    series_criterion = selectedVideo.getElementsByTagName('input')[2].value;
	    key = selectedVideo.getElementsByTagName('input')[3].value;
	    site = selectedVideo.getElementsByTagName('input')[4].value;
	} else {
	    if(input['user']){
		user = input['user'];
	    }
	    if(input['video']){
		video = input['video'];
	    }
	    if(input['criterion']){
		series_criterion = input['criterion'];
	    }
	    if(input['key']){
		key = input['key'];
	    }
	    if(input['site']){
		site = input['site'];
	    }
	}
	view = input['view'];
	url_params = "vertical="+vertical+"&user="+urlencode(user)+"&video="+urlencode(video)+"&criterion="+series_criterion+"&key="+key+"&autoplay="+autoplay+"&view="+view+"&site="+site;

    }       
    setTitle(video);
    window.location.hash = url_params
    requestSelected = createRequest();


    var url="/SelectedVideo?"+url_params

    try{
    requestSelected.open('GET',url,true);
    }catch(error){
	alert(error);
    }
    //alert(video);
    requestSelected.onreadystatechange = function() {callBack(requestSelected,input['semanticinfo'],video); };
    requestSelected.send(null);
}

function setTitle(title){
    var title = title.replace(/&raquo;/g, "->");
    document.title = "Videonym: "+title.titleCase()
}

String.noLC = new Object
    ({the:1, a:1, an:1, and:1, or:1, but:1, aboard:1,
      about:1, above:1, across:1, after:1, against:1,
      along:1, amid:1, among:1, around:1, as:1, at:1,
      before:1, behind:1, below:1, beneath:1, beside:1,
      besides:1, between:1, beyond:1, but:1, by:1, 'for':1,
      from:1, 'in':1, inside:1, into:1, like:1, minus:1,
      near:1, of:1, off:1, on:1, onto:1, opposite:1,
      outside:1, over:1, past:1, per:1, plus:1,
      regarding:1, since:1, than:1, through:1, to:1,
      toward:1, towards:1, under:1, underneath:1, unlike:1,
      until:1, up:1, upon:1, versus:1, via:1, 'with':1,
      within:1, without:1});

String.prototype.titleCase = function () {
    var parts = this.split(' ');
    if ( parts.length == 0 ) return '';

    var fixed = new Array();
    for ( var i in parts ) {
	var fix = '';
	if ( String.noLC[parts[i]] )
	    {
		fix = parts[i].toLowerCase();
	    }
	else if ( parts[i].match(/^([A-Z]\.)+$/i) )
	    { // will mess up "i.e." and like
		fix = parts[i].toUpperCase();
	    }
	else if ( parts[i].match(/^[^aeiouy]+$/i) )
	    { // voweless words are almost always acronyms
		fix = parts[i].toUpperCase();
	    }
	else
	    {
		fix = parts[i].substr(0,1).toUpperCase() +
		    parts[i].substr(1,parts[i].length);
	    }
	fixed.push(fix);
    }
    fixed[0] = fixed[0].substr(0,1).toUpperCase() +
    fixed[0].substr(1,fixed[0].length);
    return fixed.join(' ');
}

function callBack(requestSelected,semanticinfo,video){
    if ((requestSelected.readyState == 4) && (requestSelected.status == 200)){
	//loadAdsense(video);
        document.getElementById('featured_video').innerHTML = requestSelected.responseText;
        clickMenu('featured_video', 5);

	//        videosurfResults("http://www.youtube.com/watch?v=UzxYlbK2c7E");
	//	makeRequest('http://www.videosurf.com/api/ext/services/videoLookupService.php?urls=http://www.youtube.com/watch?v=UzxYlbK2c7E', '');
    }

}

function showVideoPart(url,videoName){
    
    var playerContent = "<object width='600' height='340'><param name='movie' value='"+url+"'></param><param name='allowFullScreen' value='true'></param><param name='type' value='application/x-shockwave-flash'></param><param name='allowscriptaccess' value='never'></param><param name='allownetworking' value='internal'></param><param name='wmode' value='transparent'></param><param name='quality' value='autohigh'></param><embed src='"+url+"' type='application/x-shockwave-flash' allowfullscreen='true' allowscriptaccess='never' allownetworking='internal' wmode='transparent' quality='autohigh' width='600' height='340'></embed></object> <div class='featured_video_info'>"+videoName+"</div>";
    document.getElementById('player').innerHTML = playerContent;
    //loadAdsense(videoName);

}

function getTaggedVideos(vertical, tag){
    var requestTag = createRequest();
    var divId = "taggedVideos"+tag;

    if (document.getElementById(divId).className == "hide"){
	document.getElementById(divId).className = "chosen";
        if (!document.getElementById(divId).getElementsByTagName('ul')[0]){
	    var url="/TaggedVideos?vertical="+vertical+"&tag="+tag;

	    try{
		requestTag.open('GET',url,true);
	    }catch(error){
		alert(error);
	    }

	    requestTag.onreadystatechange=function(){tagCallBack(divId, requestTag);}
	    requestTag.send(null);
	}
    }else {
	document.getElementById(divId).className = "hide";
    }
}

function getCategoryVideos(vertical, category){
    var requestCategory = createRequest();
    var divId = "categoryVideos"+category;

    if (document.getElementById(divId).className == "hide"){
        document.getElementById(divId).className = "chosen";
        if (!document.getElementById(divId).getElementsByTagName('ul')[0]){
            var url="/CategoryVideos?vertical="+vertical+"&category="+category;
            try{
                requestCategory.open('GET',url,true);
            }catch(error){
                alert(error);
            }

            requestCategory.onreadystatechange=function(){tagCallBack(divId, requestCategory);}
            requestCategory.send(null);
        }
    }else {
        document.getElementById(divId).className = "hide";
    }
}


function tagCallBack(divId, requestTag){
    if ((requestTag.readyState == 4) && (requestTag.status == 200)){
        document.getElementById(divId).innerHTML = requestTag.responseText;
    }
}

function redirectUrl(){
    var initialParams = window.location.hash;
    
    if (initialParams){
	initialParams = initialParams.substring(1);
	window.location.href = "/VideosGallore?"+ initialParams;
    }
}  

var http_request = false;
function makeRequest(url, parameters) {

    try {
	netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
    } catch (e) {
	alert("Permission UniversalBrowserRead denied.");
    }

    http_request = false;
    http_request = new XMLHttpRequest();
    if (http_request.overrideMimeType) {
	http_request.overrideMimeType('text/xml');
    }
    if (!http_request) {
	alert('Cannot create XMLHTTP instance');
	return false;
    }

    alert("1");
    http_request.onreadystatechange = alertContents;
    try{
	http_request.open('GET', url + parameters, true);
    } catch(e){
	alert(e);
    }
    http_request.send(null);
}

function alertContents() {
    alert("4");
    if (http_request.readyState == 4) {
	if (http_request.status == 200) {

	    var string = http_request.responseText;
	    alert(string);

	} else {
	    alert('There was a problem with the request.');
	}
    }
}

function loadAdsense(keywords) {
    //alert("load :" + keywords);
    var currentTime = new Date();
      googlead.location = "/googleAds?unique_s=" +
	  currentTime.getTime() + "&kws=" + keywords;
}

