var page = getQueryString("page");
if (!page) {
	page = 1;
}
var vid = getQueryString("vid");
if (!vid) {
	vid = 0;
}
yid = getQueryString("yid");
if (!yid) {
	yid = "";
}
var tmpVid ="";
var titles=new Array();
var ids=new Array();
var thumbnails=new Array();
var playerUrls=new Array();
var ratings=new Array();
var votesArr=new Array();

var step=0;
var timerDown="" ;
var boolOverNews = false;

var nextVid = 0;
var prevVid = 0;

function getElm(id) {
	return document.getElementById(id);
}

function getQueryString(key) {
	var query = "";
	try {
		query = parent.location.search;
	} catch(err) {};
	if (query.length < 1) {
		query=document.URL;
	}
	if (query.length > 1) {
		query = query.substring(1, query.length); 
		for(var i=0; i < query.split("&").length; i++) {
			subQuery = query.split("&")[i];
			subQueryKey = subQuery.split("=")[0];
			subQueryValue = subQuery.split("=")[1];
			if (subQueryKey.toLowerCase()==key.toLowerCase()) {
				return subQueryValue;
			}
		}
	} else {
		return null;
	}
	return null;
}

function playVideo(videoNummer) {
  autoplay = true;
  
  var strRate = "";
  var strRest = 0;
  nextVid = videoNummer+1;
  if (nextVid = ids.length) { nextVid = ids.length-1 }
  prevVid = videoNummer-1;
  if (prevVid < 0) { prevVid = 0 }
  
  if (yid.length > 0 && yid != ids[videoNummer] ) {
	  	alert("http://gdata.youtube.com/feeds/api/videos/"+ yid +"?alt=json-in-script&format=5&callback=videoInfo");
		loadJSON("http://gdata.youtube.com/feeds/api/videos/"+ yid +"?alt=json-in-script&format=5&callback=videoInfo");
		var playingID = yid;
  } else {
	  
	  swfobject.embedSWF('http://www.youtube.com/v/'+ ids[videoNummer] + '&amp;rel=1&amp;border=0&amp;fs=1&amp;autoplay='+ (autoplay?1:0), 'player', '400', '320', '9.0.0', false, false, {allowfullscreen: 'true', wmode:'transparent'});
	  var playingID = ids[videoNummer];
	  prevbtn = '<img src="/graphics/prevbtn.png" id="btnPrev1" onclick="playVideo('+ prevVid +');" alt="Forrige" />'
	  nextptn = '<img src="/graphics/nextbtn.png" id="btnNext1" onclick="playVideo('+ nextVid +');" alt="N&aelig;ste" />'
	  
	
	  if (getElm("videos") != null) {
		var imgs = getElm("videos").getElementsByTagName("img");
		for (var t = 0; t < imgs.length; t++) {
			imgs[t].style.border ="1px solid #000000";
		}
	  }
	  var id = ids[videoNummer];
	  if (id.length > 2) {
		if (getElm(id) != null) {
			getElm(id).style.border = "1px solid #92000e";
		}
	  }
	  var vids = Math.round(ids.length/2);
	  if (videoNummer >= vids) { videoNummer = videoNummer - vids}
  }
}

function videoInfo(getData) {
	var entry = getData.entry;
	var title = entry.title.$t;
	alert(title);
	var	id = entry.id.$t.replace(/http:\/\/gdata.youtube.com\/feeds\/api\/videos\//g, "");
	swfobject.embedSWF("http://www.youtube.com/v/"+ id + '&amp;rel=1&amp;border=0&amp;fs=1&amp;autoplay='+ (autoplay?1:0), 'player', '400', '320', '9.0.0', false, false, {allowfullscreen: 'true', wmode:'transparent'});
	
	prevbtn = '';
	nextptn = '';
}

function videoArray(data) {
	var feed = data.feed;
  	var entries = feed.entry || [];
	var totalVids = feed.openSearch$totalResults.$t;
	
	
	
  	for (var i = 0; i < entries.length; i++) {
		var entry = entries[i];
		titles[i] = entry.title.$t;
		var links = entry.link || [];
		ids[i] = entry.link[links.length-2].href.replace(/http:\/\/gdata.youtube.com\/feeds\/api\/videos\//g,'');
		addVideo(ids[i]);
		thumbnails[i] = entry.media$group.media$thumbnail[0].url;
		playerUrls[i] = entry.media$group.media$content[0].url;
	}
	
	var html = ['<div id="list" style="width:'+ (totalVids*135)/2 +'px">'];
	for (var u = 0; u < ids.length; u++) {
		if (u == 0) {
			if (vid == null) {
				playVideo(0);
				
			} else {
				playVideo(vid);
				
			}
		}
		html.push('<div class="videoThumbs" onclick="playThisVideo(',u ,')">','<img id="', ids[u] , '" src="',thumbnails[u],'" width="95" /><br />', titles[u], '</div>');
	}
	html.push('</div>');
	getElm('videos').innerHTML = html.join('');
  	//getElm("list").style.width = Math.round((entries.length * 130)/2) +"px"
	
	if (yid.length > 0 && yid != ids[vid] ) {
	} else {
		var scrollToPos = vid;
		if (scrollToPos > parseInt(totalVids/2)) {scrollToPos = scrollToPos - parseInt(totalVids/2)-1}
		getElm("videos").scrollLeft=(scrollToPos*135)-115;
	}
	
	
	var pages = Math.round((totalVids / 30)+0.5)
		
	var nextPage = parseFloat(page)+1;
	if (page < pages) {	var nextCode = '<a href="javascript:void(0);" onclick="getPage('+nextPage+')">&raquo;</a>' } else {var nextCode = '&raquo;'}
	var prevPage = parseFloat(page)-1;
	if (page > 1) {	var prevCode = '<a href="javascript:void(0);" onclick="getPage('+ prevPage +')">&laquo;</a>' } else { var prevCode = '&laquo;'}
	
	getElm("sider").innerHTML = prevCode +' Side '+ page +' af '+ pages +' '+ nextCode;

}

function videoArrayNewPage(data) {
  	var feed = data.feed;
  	var entries = feed.entry || [];
	var totalVids = feed.openSearch$totalResults.$t;
  	for (var i = 0; i < entries.length; i++) {
		var entry = entries[i];
		titles[i] = entry.title.$t;
		ids[i] = entry.id.$t.replace(/http:\/\/gdata.youtube.com\/feeds\/videos\//g, "");
		addVideo(ids[i]);
		thumbnails[i] = entry.media$group.media$thumbnail[0].url;
		playerUrls[i] = entry.media$group.media$content[0].url;
		
	}
	
	var html = ['<span id="list">'];
	for (var u = 0; u < ids.length; u++) {
		if (u == 0) {
				playVideo(0);	
		}
		html.push('<div class="videoThumbs" onclick="playThisVideo(',u ,')">','<img id="', ids[u] , '" src="',thumbnails[u],'" width="95" /><br />', titles[u], '</div>');
	}
	html.push('</span>');
	getElm('videos').innerHTML = html.join('');
  	//getElm("list").style.width = Math.round((entries.length * 130)/2) +"px";
		
	var pages = Math.round((totalVids / 30)+0.5)
		
	var nextPage = parseFloat(page)+1;
	if (page < pages) {	var nextCode = '<a href="javascript:void(0);" onclick="getPage('+ nextPage +')">&raquo;</a>' } else {var nextCode = '&raquo;'}
	var prevPage = parseFloat(page)-1;
	if (page > 1) {	var prevCode = '<a href="javascript:void(0);" onclick="getPage('+ prevPage +')">&laquo;</a>' } else { var prevCode = '&laquo;'}
	
	getElm("sider").innerHTML = prevCode +' Side '+ page +' af '+ pages +' '+ nextCode;
	
}

function getPage(thisPage) {
	var startindex = (thisPage*30)-29;
	page = thisPage;
	loadJSON('http://gdata.youtube.com/feeds/users/motorstelevision/uploads?alt=json-in-script&format=5&max-results=30&start-index='+ startindex +'&callback=videoArrayNewPage');
}

function loadJSON(url) {
  var headID = document.getElementsByTagName("head")[0];         
  var newScript = document.createElement('script');
      newScript.type = 'text/javascript';
      newScript.src = url;
  headID.appendChild(newScript);
}

function scrollDivLeft(){
	el=getElm("videos");
	el.scrollLeft+=step;
	timerDown=setTimeout("scrollDivLeft()",20);
}
function funcOutNews() {
	step=0;
}
function funcOverForward() {
	step=-10;
}
function funcOverRewind() {
	step=10;
}

function ajaxObject(url, callbackFunction) {
  var that=this;      
  this.updating = false;
  this.abort = function() {
    if (that.updating) {
      that.updating=false;
      that.AJAX.abort();
      that.AJAX=null;
    }
  }
  this.update = function(passData,postMethod) { 
    if (that.updating) { return false; }
    that.AJAX = null;                          
    if (window.XMLHttpRequest) {              
      that.AJAX=new XMLHttpRequest();              
    } else {                                  
      that.AJAX=new ActiveXObject("Microsoft.XMLHTTP");
    }                                             
    if (that.AJAX==null) {                             
      return false;                               
    } else {
      that.AJAX.onreadystatechange = function() {  
        if (that.AJAX.readyState==4) {             
          that.updating=false;                
          that.callback(that.AJAX.responseText,that.AJAX.status,that.AJAX.responseXML);        
          that.AJAX=null;                                         
        }                                                      
      }                                                        
      that.updating = new Date();                              
      if (/post/i.test(postMethod)) {
        var uri=urlCall+'?'+that.updating.getTime();
        that.AJAX.open("POST", uri, true);
        that.AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        that.AJAX.setRequestHeader("Content-Length", passData.length);
        that.AJAX.send(passData);
      } else {
        var uri=urlCall+'?'+passData+'&timestamp='+(that.updating.getTime()); 
        that.AJAX.open("GET", uri, true);                             
        that.AJAX.send(null);                                         
      }              
      return true;                                             
    }                                                                           
  }
  var urlCall = url;        
  this.callback = callbackFunction || function () { };
}

function playThisVideo(id) {
	document.location = "/film/?vid="+id+"&page="+page+"&yid="+ids[id];
}

function addVideo(videoId) {
	xmlHttp=GetXmlHttpObject();
	if (xmlHttp==null) {
	  alert ("Your browser does not support AJAX!");
	  return;
  	};
	var url='/scripts/addvideotodb.php?videoid='+ videoId +'&id='+Math.random();
	xmlHttp.onreadystatechange=videoAdded;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

function videoAdded() {
}

function GetXmlHttpObject() {
	try { xmlhttp = new XMLHttpRequest(); } catch (e) {
	    var XMLHTTP_IDS = new Array("MSXML2.XMLHTTP.5.0",   
		"MSXML2.XMLHTTP.4.0",   
		"MSXML2.XMLHTTP.3.0",   
		"MSXML2.XMLHTTP",   
		"Microsoft.XMLHTTP" );   
		var success = false;   
		for (var i=0;i < XMLHTTP_IDS.length && !success; i++) { try { xmlhttp = new ActiveXObject(XMLHTTP_IDS[i]); success = true; } catch (e) {} }   
		if (!success) { throw new Error("Unable to create XMLHttpRequest."); }   
	}   
   return xmlhttp;   
}

function createUser() {
	document.getElementById('doLogin').style.display = "none";
	document.getElementById('doCreateUser').style.display = "block";
	document.getElementById("votetype").value="CreateUser";
}



