var ajaxCache = [];

function search(query)
{
	if (typeof query === 'string' && query.length > 0) {
		var url = '?do=ajax-search&query=' + query;
		doAjax(url, searchCallback);
	}
}

function searchCallback(response, url)
{
	if (!(typeof response === 'string' && response.length > 0)) {
		return false;
	}
	var videoList = document.getElementById('videos');
	if (videoList) {
		videoList.innerHTML = response;
	}
}

function shareOnFacebook(videoId)
{
	if (typeof videoId !== 'number') {
		alert("Ingen video er aktiv og kan derfor ikke deles.");
		return false;
	}
	var pageUrl = window.location['protocol'] + '//' + window.location['host'] + window.location['pathname'] + '?id=' +  videoId;
	window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(pageUrl) + '&amp;t=' + encodeURIComponent(document.title), 'sharer', 'toolbar=0,status=0,width=626,height=436');
	return false;
}

function shareOnNettby(videoId, title, description)
{
	if (typeof videoId !== 'number') {
		alert("Ingen video er aktiv og kan derfor ikke deles.");
		return false;
	}
	var pageUrl = window.location['protocol'] + '//' + window.location['host'] + window.location['pathname'] + '?id=' +  videoId;
	window.open('http://www.nettby.no/user/edit_link.php?name=' + title + '&url=' + pageUrl + '&description=' + description,'edit_link','scrollbars=no,width=450,height=430');	
	return false;
}

function fillDirectUrlField()
{
	var link = document.getElementById('link');
	link = link.getElementsByTagName('input');
	if (typeof link === 'object' && link && typeof link[0] === 'object') {
		link[0].value = window.location['protocol'] + '//' + window.location['host'] + window.location['pathname'] + link[0].value;
	} else {
		link[0].value = window.location['href'];
	}
}

function videoListCallback(response, url)
{
	if(typeof response === 'string') {
		if (typeof url === 'string' && url.length > 0) {
			ajaxCache[url] = response;
		}
		var videoList = document.getElementById('videos');
		if (videoList) {
			videoList.innerHTML = response;
		}
	}
}

/**
 * Sends of an XMLHttpRequest and calls the callback with the data as parameter
 */
function doAjax( url, callback )
{
	if ( typeof url !== 'string' || typeof callback !== 'function' ) {
		return false;
	}
	var xhr;
	try {
		xhr = new ActiveXObject( 'Msxml2.XMLHTTP' );
	} catch ( e ) {
		try {
			xhr = new ActiveXObject( 'Microsoft.XMLHTTP' );
		} catch ( e2 ) {
			try {
				xhr = new XMLHttpRequest();
			} catch ( e3 ) {
				xhr = false;
			}
		}
	}
	xhr.onreadystatechange = function() {
		if( xhr.readyState === 4 ) {
			if( xhr.status === 200 ) {
				callback( xhr.responseText, url );
			} else {
				return false;
			}
		}
	};
	xhr.open( 'GET', url, true );
	xhr.send( null );
} 


function menuClick(categoryId, isMainMenu, event)
{
	url = '?do=videolist';
	
	if(typeof categoryId === 'number') {
		url += '&category=' + categoryId;
	}
	else {
		categoryId = 'siste';
	}
	if(typeof ajaxCache === 'object' && typeof ajaxCache[categoryId] === 'string' && ajaxCache[categoryId] !== 'undefined') {
		videolist.innerHTML = ajaxCache[categoryId];
	}
	else {
		doAjax(url, videoListCallback);
	}
	if(event.currentTarget !== 'undefined' && typeof event.currentTarget === 'object' && event.currentTarget.href !== 'undefined') {
		if(typeof isMainMenu == 'boolean' && isMainMenu === true) {
			links = document.getElementById('menu').getElementsByTagName('a')
		}
		else {
			links = document.getElementById('submenu-list').getElementsByTagName('a')
		}
		if(links != 'undefined') {
			for(var elm in links) {
				
				if(typeof links[elm] === 'object' && links[elm] != 'undefined' && links[elm].className !== 'undefined' && links[elm].className === 'active') {
					links[elm].className = '';
				}
			}
		}
		event.currentTarget.setAttribute('class', 'active');
	}
	
	if(isMainMenu === true && typeof categoryId === 'number') {
		submenuMainParent = document.getElementById('submenu-list');
		submenuMainParent.innerHTML = '';
		ul = document.createElement('ul');
		submenuMainParent.appendChild(ul);

		li = document.createElement('li');
		a = document.createElement('a');
		a.setAttribute('href', '?category=' + categoryId);
		a.setAttribute('onclick', 'menuClick(' + categoryId + ', false, event);');
		a.innerHTML = 'Alle';
		li.appendChild(a);
		ul.appendChild(li);			
		
		if(typeof categories === 'object' && categories && typeof categories['c' + categoryId].subcategories === 'object') {				
			for(var cid in categories['c' + categoryId].subcategories) {
				li = document.createElement('li');
				a = document.createElement('a');
				a.setAttribute('href', '?category=' + cid.replace(/c/,""));
				a.setAttribute('onclick', 'menuClick(' + cid.replace(/c/,"") + ', false, event);');
				a.innerHTML = categories['c' + categoryId].subcategories[cid].name;
				li.appendChild(a);
				ul.appendChild(li);
			}
			if(categoryId === 52) {
				li = document.createElement('li');
				a = document.createElement('a');
				a.setAttribute('href', 'http://fotball.vgtv.no/?category=1');
				a.innerHTML = 'Eliteserien';
				li.appendChild(a);
				ul.appendChild(li);
				
				li = document.createElement('li');
				a = document.createElement('a');
				a.setAttribute('href', 'http://fotball.vgtv.no/?category=4');
				a.innerHTML = '1.div';
				li.appendChild(a);
				ul.appendChild(li);
				
				li = document.createElement('li');
				a = document.createElement('a');
				a.setAttribute('href', 'http://fotball.vgtv.no/?category=2');
				a.innerHTML = 'Før Avspark';
				li.appendChild(a);
				ul.appendChild(li);				
				
				li = document.createElement('li');
				a = document.createElement('a');
				a.setAttribute('href', 'http://fotball.vgtv.no/?category=3');
				a.innerHTML = 'Fotballfruer';
				li.appendChild(a);
				ul.appendChild(li);				
			} else if(categoryId === 3) {
				li = document.createElement('li');
				a = document.createElement('a');
				a.setAttribute('href', 'http://birken.vgtv.no/');
				a.innerHTML = 'Birken';
				li.appendChild(a);
				ul.appendChild(li);				
			}
		}
	}
	event.preventDefault();
	return false;
}

function paging(page, category, event)
{
	url = '?do=videolist';
	if (typeof category === 'number') {
		url += '&category=' + category;
	} else if (typeof category === 'string') {
		url = '?do=ajaxSearch&query=' + category;
	}	
	if (typeof page === 'number') {
		url += '&page=' + page;
	}
	if (typeof ajaxCache[url] === 'string') {
		var videoList = document.getElementById('videos');
		if (videoList) {
			videoList.innerHTML = ajaxCache[url];
		}
	} else {
		doAjax(url, videoListCallback);
	}
	event.preventDefault();
	return false;
}

function cycleMostSeenList() {
	var list = document.getElementById('mostseenvideoscontent');
	if (!(typeof list === 'object' && list && list.nodeType === 1 && list.childNodes.length > 1 )) {
		return;
	}
	for (var i = 0, iMax = list.childNodes.length; i < iMax; i++) {
		if (list.childNodes[i].nodeType === 1) {
			if (list.childNodes[i].className === 'active') {
				list.childNodes[i].className = '';
				var nextNode = null;
				if (list.childNodes[i].nextSibling && list.childNodes[i].nextSibling.nodeType === 1) {
					list.childNodes[i].nextSibling.className = 'active';
				} else if (list.childNodes[i].nextSibling && list.childNodes[i].nextSibling.nextSibling && list.childNodes[i].nextSibling.nextSibling.nodeType === 1) {
					list.childNodes[i].nextSibling.nextSibling.className = 'active';
				} else if (list.firstChild.nodeType === 1) {
					list.firstChild.className = 'active';
				} else if (list.firstChild.nextSibling && list.firstChild.nextSibling.nodeType === 1) {
					list.firstChild.nextSibling.className = 'active';
				}
				return;
			}
		}
	}
}

function eventListen( element, name, observer ) {
	if ( element.addEventListener ) {
		element.addEventListener( name, observer, false );
	}
	else if ( element.attachEvent ) {
		element.attachEvent( 'on' + name, observer );
	}
}

function showVideoIndexes(indexes) {
	var indexDiv = document.getElementById('indexes');
	if (typeof indexes === 'object' && typeof indexes.data === 'object' && indexes.data !== null && indexes.data.length > 0 && typeof indexes.seekFunction === 'function') {
		if (indexDiv) {
			var fragment = document.createDocumentFragment();
			var element = document.createElement('h3');
			element.appendChild(document.createTextNode('Hopp til:'));
			fragment.appendChild(element);
			element = document.createElement('ul');
			for (var i = 0, iMax = indexes.data.length; i < iMax; i++) {
				var indexLi = document.createElement('li');
				var indexAnchor = document.createElement('a');
				indexAnchor.appendChild(document.createTextNode(indexes.data[i].text));
				eventListen(indexAnchor, 'click', (function(idx) {
					return function() {
						indexes.seekFunction(indexes.data[idx].time);
					}
				}(i)));
				indexLi.appendChild(indexAnchor);
				element.appendChild(indexLi);
			}
			fragment.appendChild(element);
			indexDiv.appendChild(fragment);
		}
	} else {
		indexDiv.innerHTML = '';
	}
}

/**
 * @author Dan.Kare.Engebretsen@vg.no
 */
function createFacebookChat(vidid,categoryid,toplevel,element) {
	var f = document.createElement('iframe');
	f.setAttribute('src', 'http://www.vg.no/fbkommentarer/?vid=' + vidid + '&catid=' + categoryid + '&topid=' + toplevel);
	f.setAttribute('marginwidth', '0');
	f.setAttribute('marginheight', '0');
	f.setAttribute('frameborder', '0');
	f.setAttribute('scrolling', 'no');
	f.setAttribute('width', '288');
	f.setAttribute('height', '940');
	f.setAttribute('style', 'overflow-x: hidden;');
	document.getElementById(element).appendChild(f);
}

/**
 * @author lars@aptoma.com
 */
function createFacebookFanBox(parentElementId, linkUrl, linkText, profileId, init)
{
	var parentElement = document.getElementById(parentElementId);
	if (!parentElement) {
		return;
	}
	if (!('FB' in window)) {
		return;
	}
	FB.init(init);
	var fbElement = document.createElement('fb:fan');
	fbElement.setAttribute('profile_id', profileId);
	fbElement.setAttribute('stream', '');
	fbElement.setAttribute('connections', '15');
	fbElement.setAttribute('width', '180');
	fbElement.setAttribute('height', '500');
	fbElement.setAttribute('xtcz', 'facebookfanbox');
	var fanLink = document.createElement('a');
	fanLink.setAttribute('href', linkUrl);
	fanLink.appendChild(document.createTextNode(linkText));
	var fanLinkParent = document.createElement('div');
	fanLinkParent.style.fontSize = '10px';
	fanLinkParent.style.paddingLeft = '10px';
	fanLinkParent.appendChild(fanLink);
	parentElement.appendChild(fbElement);
	parentElement.appendChild(fanLinkParent);
}
