// Nogle brugbare variabler
var currentClip = null;
var clipCount = 0;
var prevPage = null;
var internClipCount = 0;
var internPrevPage = null;

// The ultimate AJAX Object
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 () { };
}


// Change CSS class on DIV 
function changeClassName(eId, cName) 
{
	document.getElementById(eId).className = cName;
}
	

function showHideMenu(eId, cName, cNameIa, eId1, cName1, cName1Ia, scrollToBottom) 
{
	if( document.getElementById(eId).className ==  cName )
	{
		document.getElementById(eId).className = cNameIa;
		document.getElementById(eId1).className = cName1Ia;
	}
	else
	{
		document.getElementById(eId).className = cName;
		document.getElementById(eId1).className = cName1;
	}
	
	if(scrollToBottom)
	{
		var objDiv = document.getElementById("v_comments");
		objDiv.scrollTop = objDiv.scrollHeight;

	}
}

/* Skriver en kommentar til klippet */
function createMyComment(formId, clipId)
{
	var error = false;
	
	var fra_navn = document.getElementById('c_' + formId + '_name');
	var bot_email = document.getElementById('c_' + formId + '_email');
	var fra_email = document.getElementById('c_' + formId + '_pykalov');
	var comment_text = document.getElementById('c_' + formId + '_text');
	var notify = document.getElementById('c_' + formId + '_notify');
	var the_facebook = document.getElementById('c_' + formId + '_fb');

	if( fra_navn.value == "" || fra_navn.value == "Du glemte at indtaste dit navn")
	{
		error = true;
		fra_navn.className = "writecommentInput error";
		fra_navn.value = "Du glemte at indtaste dit navn";
	}
	else
		fra_navn.className = "writecommentInput";
		
	if( fra_email.value == "" || fra_email.value == "Du glemte at indtaste din e-mail adresse")
	{
		error = true;
		fra_email.className = "writecommentInput error";
		fra_email.value = "Du glemte at indtaste din e-mail adresse";
	}
	else
		fra_email.className = "writecommentInput";		
		
	if( comment_text.value == "" || comment_text.value == "Du glemte at indtaste din kommentar")
	{
		error = true;
		comment_text.className = "writecommentTextArea error";
		comment_text.value = "Du glemte at indtaste din kommentar";
	}
	else
		comment_text.className = "writecommentTextArea";				
		

	var subscribe = 0;
	if( notify.checked )
		subscribe = 1;
		
	if( !error )
	{
		var myRequest = new ajaxObject('/res/xhr_create_comment.php');
		sendString = 'email='+bot_email.value+'&author_name='+fra_navn.value+'&author_subscribe='+subscribe+'&author_email='+fra_email.value+'&text='+comment_text.value+'&clip='+clipId;
		myRequest.update(sendString,'POST');	
		myRequest.callback = function(responseText) {
		  
		  var msg = eval("(" + responseText + ")");
		  if(msg.success == true)
		  {
		  	var d=new Date();
		  	var dstring = d.toLocaleString();
		  	var html = '<div class="commentPost">';
				html = html + '<div class="commentPostRow1"><h1>' + fra_navn.value + '</h1><h2>' + dstring.substring(0, (dstring.length - 3)) + '</h2></div>';
				html = html + '<div class="commentContent">';
				html = html + comment_text.value.replace("\n", "<br />");
				html = html + '</div>';

				
		  	// facebook
		  	if( the_facebook != null )
		  	{
					if( the_facebook.checked )
						showFacebokDialog(clipId, comment_text.value);
						
					the_facebook.checked = false;
				}
		  	// facebook end

				fra_navn.value = "";
				bot_email.value = "";
				fra_email.value = "";
				comment_text.value = "";
				notify.checked = false;
				
				document.getElementById("theComments").innerHTML = document.getElementById("theComments").innerHTML + html;				
		  	showHideMenu('open_writecomment_' + formId, 'writeCommentLink active', 'writeCommentLink',  'writecomment_' + formId, 'writeCommentContent_show', 'writeCommentContent', false)
		  	

		  }
		  else
		  	alert(responseText);
		  
		  
		  
		}
		
	}
}

/* Viser en facebook dialog boks */
function showFacebokDialog( clipId, comment )
{
var myRequest = new ajaxObject('/res/xhr_clip_info.php');
		sendString = 'clipId='+clipId;
		myRequest.update(sendString,'POST');	
		myRequest.callback = function(responseText) 
		{	
			
				var data = eval("(" + responseText + ")");
				FB.ui({
					method: 'feed',
					name: data.name,
					link: data.url,
					picture: data.image,
					caption: data.name,
					display: 'iframe',
					description: data.teaser,
					message: comment
					},
					function(response) 
					{	
						if (response && response.post_id) 
						{
							//alert('Post was published.');
						} 
						else 
						{
							//alert('Post was not published.');
						}						
					}
				);
		}
}


/* "Send til en ven" funktionen */
function sendToFriend( clipId )
{
	var error = false;
	var til = document.getElementById('recipient_mail'); //Du glemte at indtaste e-mail adressen
	var fra_navn = document.getElementById('your_name');
	var fra_email = document.getElementById('your_email');
	var besked = document.getElementById('your_message');
	var my_copy = document.getElementById('copy_tip');
	
	if( til.value == "" || til.value == "Du glemte at indtaste e-mail adressen" )
	{
		error = true;
		til.className = "tipInput error";
		til.value = "Du glemte at indtaste e-mail adressen"
	}
	else
		til.className = "tipInput";
	
	if( fra_navn.value == "" || fra_navn.value == "Du glemte at indtaste dit navn" )
	{
		error = true;
		fra_navn.className = "tipInput error";
		fra_navn.value = "Du glemte at indtaste dit navn"		
	}
	else
		fra_navn.className = "tipInput";	
		
	if( fra_email.value == "" || fra_email.value == "Du glemte at indtaste din e-mail adresse" )
	{
		error = true;
		fra_email.className = "tipInput error";
		fra_email.value = "Du glemte at indtaste din e-mail adresse"		
	}
	else
		fra_email.className = "tipInput";			
		
	var copy_to_sender = 0;
	if( my_copy.checked )
		copy_to_sender = 1;
	
	if( !error )
	{
		var myRequest = new ajaxObject('/res/xhr_notify_friend.php');
		sendString = 'email_message='+besked.value+'&sender_name='+fra_navn.value+'&copy_to_sender='+copy_to_sender+'&recipient_email='+til.value+'&sender_email='+fra_email.value+'&clip_id='+clipId;
		myRequest.update(sendString,'POST');	
		
		var myRequest = new ajaxObject('/res/xhr_share_counter.php');
		sendString = 'clip_id='+clipId;
		myRequest.update(sendString,'POST');			
		myRequest.callback = function(responseText) 
		{	
			var obj = eval("(" + responseText + ")");
			if(obj.error == false)
				_gaq.push(['_trackEvent', 'Sharing', 'Tip en ven', obj.name]);				
		}

		
		
		document.getElementById('tip_form').className = "tipForm_hide";
		document.getElementById('tip_feedback').className = "tipFeedback";
		document.getElementById('sentToMail').innerHTML = til.value;
	}
	
}

/* Knappen der skjuler feedback boksen fra tip-en-ven */
function okFeedback()
{
	document.getElementById('tip_form').className = "tipForm";
	document.getElementById('tip_feedback').className = "tipFeedback_hide";
	
	document.getElementById('recipient_mail').value = '';
	document.getElementById('your_message').value = '';
	
}

/* Skifter mellem tabs */
function openTab(tabId)
{
	
	$(".tabLink").each(function(){
		$(this).attr("class", "tabLink");
	});
	
	document.getElementById('v_chapters').style.display = 'none';
	document.getElementById('v_share').style.display = 'none';
	document.getElementById('v_description').style.display = 'none';
	document.getElementById('v_comments').style.display = 'none';
	
	document.getElementById('v_' + tabId).style.display = 'block';
	document.getElementById('a_' + tabId).className = "tabLink active";
	
}

/* Henter klips fra den pågældende kategori ud */
function getCategoryClips( categoryId, page )
{
		if( prevPage != null)
			document.getElementById("page_" + prevPage).className = "counterLink";
				
		document.getElementById("page_" + page).className = "counterLink active";
		
		prevPage = page;
		
		if( page == 1 )
		{
			document.getElementById("pageRew").className = "pageRew phantom";
			document.getElementById("pageRew").onclick = function()
			{
				return false;
			}
		}
		else
		{
			document.getElementById("pageRew").className = "pageRew";
			document.getElementById("pageRew").onclick = function()
			{
				getCategoryClips( categoryId, (page - 1) )
			}			
		}
		var no_pages = clipCount / 10;
		
		if( page == Math.ceil(no_pages))
		{
			document.getElementById("pageFwd").className = "pageFwd phantom";
			document.getElementById("pageFwd").onclick = function()
			{
				return false;
			}
		}
		else
		{
			document.getElementById("pageFwd").className = "pageFwd";
			document.getElementById("pageFwd").onclick = function()
			{
				getCategoryClips( categoryId, (page + 1) )
			}			
		}		
		
		
		var myRequest = new ajaxObject('/res/xhr_category_clips.php');
		sendString = 'category_id='+categoryId+'&page='+page;
		myRequest.update(sendString,'POST');	
		myRequest.callback = function(responseText) 
		{
			var data = eval("(" + responseText + ")");
			processClips(data);		
		}
}

function processClips( data )
{
	var html = "";
	for(clipKey in data)
	{
		var clip = data[clipKey];		
		
		if( currentClip != null && clip.clipId == currentClip)
		{
			html = html + '<div class="clipPost active" id="catClip_' + clip.clipId + '" onclick="document.location.href=\'' + clip.url + '\';">\n';
			html = html + '<div class="clipPost_thumbnail" style="background: url(' + clip.thumbnail + ');"><h1>Afspiller...</h1></div>\n';		
		}
		else
		{
			html = html + '<div class="clipPost" id="catClip_' + clip.clipId + '" onclick="document.location.href=\'' + clip.url + '\';">\n';
			html = html + '<div class="clipPost_thumbnail" style="background: url(' + clip.thumbnail + ');"><h1></h1></div>\n';
		}
		
		html = html + '<h2>' + clip.name + '</h2>\n';
		html = html + '<h3>' + clip.pf_date_format + '</h3>\n';
		html = html + '<!-- clipPost END --></div>\n\n\n';
		
	}
	
	document.getElementById("categoryClips").innerHTML = html;
}

/* Henter klips fra den pågældende kategori ud */
function getInternClips( page )
{
		if( internPrevPage != null)
			document.getElementById("intern_page_" + internPrevPage).className = "counterLink";
				
		document.getElementById("intern_page_" + page).className = "counterLink active";
		
		prevPage = page;
		
		if( page == 1 )
		{
			document.getElementById("internPageRew").className = "pageRew phantom";
			document.getElementById("internPageRew").onclick = function()
			{
				return false;
			}
		}
		else
		{
			document.getElementById("internPageRew").className = "pageRew";
			document.getElementById("internPageRew").onclick = function()
			{
				getInternClips( (page - 1) )
			}			
		}
		var no_pages = internClipCount / 10;
		
		if( page == Math.ceil(no_pages))
		{
			document.getElementById("internPageFwd").className = "pageFwd phantom";
			document.getElementById("internPageFwd").onclick = function()
			{
				return false;
			}
		}
		else
		{
			document.getElementById("internPageFwd").className = "pageFwd";
			document.getElementById("internPageFwd").onclick = function()
			{
				getInternClips( (page + 1) )
			}			
		}		
		
		
		var myRequest = new ajaxObject('/res/xhr_intern_clips.php');
		sendString = 'page='+page;
		myRequest.update(sendString,'POST');	
		myRequest.callback = function(responseText) 
		{
			var data = eval("(" + responseText + ")");
			processInternClips(data);		
		}
}

function processInternClips( data )
{
	var html = "";
	for(clipKey in data)
	{
		var clip = data[clipKey];		
		
		if( currentClip != null && clip.clipId == currentClip)
		{
			html = html + '<div class="clipPost active" id="catClip_' + clip.clipId + '" onclick="document.location.href=\'' + clip.url + '\';">\n';
			html = html + '<div class="clipPost_thumbnail" style="background: url(' + clip.thumbnail + ');"><h1>Afspiller...</h1></div>\n';		
		}
		else
		{
			html = html + '<div class="clipPost" id="catClip_' + clip.clipId + '" onclick="document.location.href=\'' + clip.url + '\';">\n';
			html = html + '<div class="clipPost_thumbnail" style="background: url(' + clip.thumbnail + ');"><h1></h1></div>\n';
		}
		
		html = html + '<h2>' + clip.name + '</h2>\n';
		html = html + '<h3>' + clip.pf_date_format + '</h3>\n';
		html = html + '<!-- clipPost END --></div>\n\n\n';
		
	}
	
	document.getElementById("internClips").innerHTML = html;
}

/* Henter powerformat clips ud, undtagen for den kategori der bliver medsendt */
function getPowerformatsClips(categoryId)
{

		var myRequest = new ajaxObject('/res/xhr_powerformats_clips.php');
		sendString = 'category_id='+categoryId;
		myRequest.update(sendString,'POST');	
		myRequest.callback = function(responseText) 
		{
			var data = eval("(" + responseText + ")");
			var html = "";
			for(clipKey in data)
			{
				var clip = data[clipKey];
				html = html + '<div class="clipPost" onclick="document.location.href=\'' + clip.url + '\';">\n';
				html = html + '<div class="clipPost_thumbnail" style="background: url(' + clip.thumbnail + ');"><h1></h1></div>\n';
				html = html + '<h2>' + clip.name + '</h2>\n';
				html = html + '<h3>' + clip.pf_name + '</h3>\n';
				html = html + '<!-- clipPost END --></div>\n\n\n';
			}
			
			document.getElementById("powerformatsClips").innerHTML = html;

		}
	

}

function emailSubscription ( categoryId, subtype )
{
		var email = document.getElementById("subEmail");
		email.className = "gadgetInput mail";
		var myRequest = new ajaxObject('/res/xhr_powerformat_subscriptions.php');
		sendString = 'category_id='+categoryId+'&email='+email.value+'&type='+subtype;
		myRequest.update(sendString,'POST');	
		myRequest.callback = function(responseText) 
		{
			var data = eval("(" + responseText + ")");
			document.getElementById("gadgetInputHolder").style.display = 'none';
			document.getElementById("gadgetInputHolder_ok").style.display = 'block';
			document.getElementById("gadgetThanx").innerHTML = data.message;
			
			if(data.success == "true")
				document.getElementById("gadgetThanx").className = "gadgetInput mail info";
			else
				document.getElementById("gadgetThanx").className = "gadgetInput mail error";
				
			
		}
} 

function emailSubscriptionOK()
{
				document.getElementById("gadgetInputHolder").style.display = 'block';
				document.getElementById("gadgetThanx").innerHTML = '';			
				document.getElementById("gadgetInputHolder_ok").style.display = 'none';	
}

// Fix til DEL knap i playeren
function showFlashShareBox()
{
	openTab('share');
}


	/* Søgefunktionalitet */
	function search_submit()
	{
		$('#topsearchinput').val($('#topsearchinput').val().replace(/^\s+/, '').replace(/\s+$/, ''));
		if ($('#topsearchinput').val() != '' && $('#topsearchinput').val() != 'Find indslag...')
			window.location.href = '/soeg/?q='+encodeURIComponent($('#topsearchinput').val());
	}
	
	
// setClass funktionen
function setClass( elem, input_className )
{
	elem.className = input_className;
}
