(function(){if(window.XMLHttpRequest)return;var o=null,s,
a=["MSXML2.XMLHTTP.5.0","MSXML2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0","Msxml2.XMLHTTP","Microsoft.XMLHTTP"];
for(var i=0,j=a.length;i<j;s=a[i],i++){try{if(o=new ActiveXObject(s))break}
catch(e){}}window.XMLHttpRequest=o?function(){return new ActiveXObject(s)}:null;o=null})()


var serviceUrl = "/template/v1-1/components/nationentv/nationentv_service.jsp";


function childNodeValue(o){

    if(o.firstChild){
        return o.firstChild.nodeValue;
    }
    else{
        return "";
    }
}

function minLogin(a,b) {
    if (a==""){a=" ";}
    if (b==""){b=" ";}

    var oHttp = new XMLHttpRequest();
    oHttp.open("post", "/template/v1-1/components/ajax/testLogin.jsp", true);
    oHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
    oHttp.onreadystatechange = function(){ myCallBack(oHttp) };
    oHttp.send("username="+a+"&passw="+b);
}

function myCallBack(oHttp) {
    if (oHttp.readyState < 4) {
        return;
    }

    var xmlDoc=oHttp.responseXML.documentElement;

    fejl  ="For at uploade videoer på nationen.tv, skal du være nationen-medlem, og have angivet både fornavn, efternavn, samt aktiveret e-mail og mobilnummer. <br /><br />Du manger at:<br />";

    if(childNodeValue(xmlDoc.getElementsByTagName("login_ok")[0])=="T"){

        var visfejl=false;
        var fejlbesked="";

        if(!childNodeValue(xmlDoc.getElementsByTagName("firstname")[0])!=""){
            fejlbesked+="indtaste dit fornavn i din profil<br />";
            visfejl=true;
        }
        if (!childNodeValue(xmlDoc.getElementsByTagName("lastname")[0])!=""){
            fejlbesked+="indtaste dit efternavn i din profil<br />";
            visfejl=true;
        }
        if (childNodeValue(xmlDoc.getElementsByTagName("email_verified")[0])=="F"){
            fejlbesked+="verificere din e-mail<br />";
            visfejl=true;
        }
        if (childNodeValue(xmlDoc.getElementsByTagName("cellphone_verified")[0])=="F"){
            fejlbesked+="verificere din mobil<br />";
            visfejl=true;
        }

        if(visfejl){
            errorText=fejl+fejlbesked+"<br /><p class='ntv-klik'><a href='http://ekstrabladet.dk/minside/?source=NATIONEN&origin=nationen&campaign=ebnet_nationen_minside' style='padding-left:-12px;'>Klik her</a></p>";
            document.getElementById("loginfejlbesked").innerHTML=errorText;
        }
        else{
            var ticketcookie = xmlDoc.getElementsByTagName("ticket")[0].childNodes[0].nodeValue;
            var userid       = xmlDoc.getElementsByTagName("userid")[0].childNodes[0].nodeValue;

            setCookies("ticketcookie", ticketcookie);
            setCookies("userid", userid);

            window.location = window.location.pathname + getUniqueQString();

        }
    }

    else{
        document.getElementById("loginfejlbesked").innerHTML="Et eller flere felter er udfyldt forkert - pr&oslash;v venligst igen";
    }
    oHttp = null;
}


function getUniqueQString() {
    /* hack  to avoid squid cache */
    var rand = new Date().getTime();
    var ntvQ = "ntv-uni";
    var newQuery = "";

    var query = window.location.search.substring(1);

    if (query != "") {
        // already set, replace the whole querystring
        if (getQueryVariable(ntvQ)) {
            var reg = eval("/^(.*" + ntvQ + "=)\\d+(.*)$/");
            newQuery = query.replace(reg, "$1" + rand + "$2");

        }
        else {
            newQuery = query + "&" + ntvQ + "=" + rand;
        }
    } else {
        newQuery = ntvQ + "=" + rand;
    }
    return "?" + newQuery;
}

function rateClip(mmid,rating) {
    var userid=getCookie('userid');

    var oHttp = new XMLHttpRequest();

    oHttp.open("post", "/template/v1-1/components/ajax/rating.jsp", true);
    oHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
    oHttp.onreadystatechange =  function(){ myCallBack1(oHttp) };
    oHttp.send("mmid="+mmid+"&userid="+userid+"&rating="+rating);
}

function myCallBack1(oHttp) {

    if (oHttp.readyState < 4) {
        return;
    }

    if( isValidUser() && oHttp.responseText.replace(/^\s+|\s+$/g,"")=="OK") {
            document.getElementById("bedomcontainer").style.display="none";
            document.getElementById("takforrating").style.display="block";
    }
    else if ( !isValidUser() ){
            document.getElementById("skalvaereloggetind").style.display="block";
    }
    else{
            document.getElementById("bedomcontainer").style.display="none";
            document.getElementById("takforrating").style.display="none";
            document.getElementById("allerederated").style.display="block";
    }

    oHttp = null;
}

var detect = navigator.userAgent.toLowerCase();
var OS,browser,version,total,thestring;

if (checkIt('konqueror')) {
    browser = "Konqueror";
    OS = "Linux";
}
else if (checkIt('safari')) browser = "Safari"
else if (checkIt('omniweb')) browser = "OmniWeb"
else if (checkIt('opera')) browser = "Opera"
else if (checkIt('webtv')) browser = "WebTV";
else if (checkIt('icab')) browser = "iCab"
else if (checkIt('msie')) browser = "Internet Explorer"
else if (!checkIt('compatible')) {
    browser = "Netscape Navigator"
    version = detect.charAt( 8 );
}
else browser = "An unknown browser";

if (!version) version = detect.charAt(place + thestring.length);

if (!OS) {
    if (checkIt('linux')) OS = "Linux";
    else if (checkIt('x11')) OS = "Unix";
    else if (checkIt('mac')) OS = "Mac"
    else if (checkIt('win')) OS = "Windows"
    else OS = "an unknown operating system";
}

function checkIt(string) {
    place = detect.indexOf(string) + 1;
    thestring = string;
    return place;
}

function createCookie(name, value, days) {
    //var path ="/nationentv/";
	var path ="/";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else
        var expires = "";

    if(days != -1)
         document.cookie = name + "=" + escape(value) +
         ((expires == null) ? "" : "; expires=" + expires) +
         ((path == null)    ? "" : "; path=" + path);
    else
        document.cookie = name + "=" + escape(value) + ((path == null)    ? "" : "; path=" + path);
}

function getCookie( name ) {
    var start = document.cookie.indexOf( name + "=" );
    var len = start + name.length + 1;
    if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
        return null;
    }

    if ( start == -1 )
        return null;

    var end = document.cookie.indexOf( ";", len );
    if ( end == -1 )
        end = document.cookie.length;

    return unescape( document.cookie.substring( len, end ) );
}

function setCookies(n,f){
    createCookie(n,f,1);
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}


function eraseCookie(name) {
    createCookie(name,"",-1);
}


function readmycookies(){
    var x = readCookie('ticketcookie');
    if (x) {
    //document.getElementById("loggetind").style.display="block";
        document.getElementById("ikkeloggetind").style.display="none";
    //document.getElementById('playboxtap2').style.display='block';
    }
    else{
    //document.getElementById("playlisteknapper").style.display="none";
    }
}

function readmycookiess(id){
    var x = readCookie(id);
    if (x) {
        document.write(x);
    }
    else{
    //document.getElementById("playlisteknapper").style.display="none";
    }
}

var mylist   =new Array();
var mytitle  =new Array();
var mytid    =new Array();
var myrating =new Array();

var mycheckbokse =new Array();

var cookieName = "list";

function clearArray() {
    mylist   =new Array();
    mytitle  =new Array();
    mytid    =new Array();
    myrating =new Array();
}


function updateLister() {
    for(var i = 0; i < mylist.length; i++){
        document.getElementById(mylist[i]).style.display="block";
        mylist.splice(i, 1);
        mytitle.splice(i, 1);
        mytid.splice(i, 1);
        myrating.splice(i, 1);

        saveArrayToCookie();
    }
}

function init() {
    loadArrayFromCookie();

    // not logged in
    if( ! isLoggedIn() ) {


        document.getElementById('tablogin').style.display='inline';
        document.getElementById('upload-tab-loggedout').style.display='inline';
        //document.getElementById('ikkeloggetind').style.display='block';

        try{
            // div for bedom
            bedomObj = document.getElementById('bedom');

            // if defined and visible
            if (bedomObj) {
                if (bedomObj.style.display != "none") {
                    document.getElementById('skalvaereloggetind').style.display='block';
                }
            }

        }
        catch (E){}

        try{
            if (document.getElementById("bedomcontainer")) {
                document.getElementById("bedomcontainer").style.display="none";
            }
        }

        catch (E){}


    }
    else {
        // only show this after a successful login

        document.getElementById('tablogout').style.display='inline';
        document.getElementById('upload-tab-loggedin').style.display='inline';

        showRedirectLinks()

    }

    for(var i = 0; i < mylist.length; i++){

        try{
            if (document.getElementById(mylist[i])) {
                document.getElementById(mylist[i]).style.display="none";
            }
        }
        catch (E){}
    }// for slut

    try{
        if (document.getElementById('bedom')) {
            document.getElementById('bedom').style.display='block';
        }
    }
    catch (E){}

    try{
        if (document.getElementById('midlertid')) {
            document.getElementById('midlertid').style.display='block';
        }
    }
    catch (E){}

    try{
        if (document.getElementById('playboxtap2')) {
            document.getElementById('playboxtap2').style.display='none';
        }
    }
    catch (E){}

    try{
        if (document.getElementById('ownerbruger')) {
            document.getElementById('ownerbruger').style.display='block';
        }
    }
    catch (E){}

    readmycookies();
}

   function saveArrayToCookie()
   {
       var strArray = "";
       for(var i = 0; i < mylist.length; i++)
           strArray += mylist[i] + ((i < mylist.length-1) ? "\\" : "");

       strArray +="|"

       for(var i = 0; i < mytitle.length; i++)
           strArray += mytitle[i] + ((i < mytitle.length-1) ? "\\" : "");

       strArray +="|"

       for(var i = 0; i < mytid.length; i++)
           strArray += mytid[i] + ((i < mytid.length-1) ? "\\" : "");

       strArray +="|"

       for(var i = 0; i < myrating.length; i++)
           strArray += myrating[i] + ((i < myrating.length-1) ? "\\" : "");

       createCookie(cookieName, strArray, -1);
   }

   function loadArrayFromCookie()
   {
       clearArray();
       var strArray = getCookie(cookieName);

       if(strArray == null || strArray == "" )
           return;

             lists = strArray.split('|');
       if(lists[0].split('\\')!=""){

       mylist   = lists[0].split('\\');
       mytitle  = lists[1].split('\\');
       mytid    = lists[2].split('\\');
       myrating = lists[3].split('\\');
       }

   }

   function addToKvikListe(id,titel,tid,rating)
   {
       // alert(id.substring(0,id.length-1));

       for (var i=0; i < mylist.length; i++){

       if ( id.substring(0,id.length-1)==mylist[i].substring(0,mylist[i].length-1) ){
         alert("clip allerede tilføjet!!");
         return false;
         }
       }
       mylist.push(id);
       mytitle.push(titel);
       mytid.push(tid);
       myrating.push(rating);

       saveArrayToCookie();
       return false;
   }

   function removeFromKvikListe(id)
   {
       try{
       document.getElementById(mylist[id]).style.display="block";
       }
       catch(E){}

       mylist.splice(id, 1);
       mytitle.splice(id, 1);
         mytid.splice(id, 1);
         myrating.splice(id, 1);

       saveArrayToCookie();
   }

   function tomKvikListe(id)
   {
       eraseCookie(id);
       mylist = new Array();

       window.location=document.URL.replace("#","");
   }


   function scrollToElement(elm) {
         var intPosX = 0;
         var intPosY = -125;
         var element = elm;
         while(elm != null)
         {
           intPosX += elm.offsetLeft;
           intPosY += elm.offsetTop;
           elm = elm.offsetParent;
         }

       window.scrollTo(intPosX,intPosY);
       element.focus();
   }


    function udskriv() {
        return;
    }

    function clearNode(node) {
        while(node.childNodes.length > 0) {
            node.removeChild(node.childNodes[0]);
        }
    }


function addEvent(elm, evType, fn) {
    if (elm.addEventListener) {
        elm.addEventListener(evType, fn, false);
        return true;
    }
    else {
        var r = elm.attachEvent('on' + evType, fn);
        return r;
    }
}


function logUd(name) {
    createCookie(name,"",-1);
    createCookie("userid","",-1);
    eraseCookie("ticketcookie");

    url = document.URL.replace(window.location.hash, "");
    window.location.href = window.location.pathname + getUniqueQString();
}

function loginLinks(name, linkUrl) {

    var forwardUrl = "";

    forwardUrl =  window.location.search;

    if (name == 'klips') {
        forwardUrl = "/nationentv/myclips/";
    }

    if (linkUrl) {
        forwardUrl = linkUrl;
    }

    //forwardUrl += "&ntv-tab=" + name;
    window.location = forwardUrl + getUniqueQString();
}

function cheche(){
  var chks = document.getElementsByName("cat"), chck = document.getElementsByName("alle")[0].checked;
  for(i=0,im=chks.length;im>i;i++)
      chks[i].checked = chck;
}

function vaelgtap(id) {
    var objs = document.getElementsByTagName('li');
    var t = 1;
    for(var i=0;i<objs.length;i++){
        if(objs[i].id.indexOf('pt')==0){
            objs[i].className = 'pt'+t;
            t=t+1;
        }
    }
    document.getElementById(id).className='ptselect '+id;
}

function visTap(id) {
    document.getElementById('bedom').style.display='none';
    document.getElementById('send').style.display='none';
    document.getElementById('anmeld').style.display='none';
    document.getElementById('komment').style.display='none';
    document.getElementById('embed').style.display='none';

    document.getElementById(id).style.display='block';

    if (id == 'bedom') {

        if (document.getElementById(id).style.display != "none") {
            if ( ! isLoggedIn() ) {
                document.getElementById('skalvaereloggetind').style.display='block';
            }
        }
    }
}


function playboxtap(id) {
    var objs = document.getElementsByTagName('li');
    var t = 1;
    for(var i=0;i<objs.length;i++){
        if(objs[i].id.indexOf('playbox')==0){
            objs[i].className = 'playbox'+t;
            t=t+1;
        }
    }
    document.getElementById(id).className='logcurrent';
}

function visplayboxTap(id) {
    document.getElementById('midlertid').style.display='none';
    document.getElementById('playlists').style.display='none';
    document.getElementById(id).style.display='block';
}

function ownerboxtap(id) {
    var objs = document.getElementsByTagName('li');
    var t = 1;
    for(var i=0;i<objs.length;i++){
        if(objs[i].id.indexOf('ownerbox')==0){
           objs[i].className = 'ownerbox'+t;
           t=t+1;
        }
    }
    document.getElementById(id).className='logcurrent';
}

function visownerboxTap(id) {
    document.getElementById('ownerbruger').style.display='none';
    document.getElementById('ownerklip').style.display='none';
    document.getElementById('ownerplaylists').style.display='none';
    document.getElementById(id).style.display='block';
}

function getVisKlip(id){
     return function() {
        location.href=id;
     }
}

function CheckboxCookie(o){
    setCookies(o.getAttribute("name"),o.value);
 }


function validateform(o){

    var str = escape(o.sogeord.value);

    str = str.replace(/\//g,"%2F");
    str = str.replace(/\?/g,"%3F");
    str = str.replace(/=/g,"%3D");
    str = str.replace(/&/g,"%26");
    str = str.replace(/@/g,"%40");

    o.escapedsogeord.value=str;
}


function isValidEmail(val) {

    if (!val.match(/^[a-z0-9\-_\.]+@[a-z0-9\-_\.]+\.\w{2,4}$/i)) {
        return false;
    }

    return true
}


function validate(o){

    navn = o.ditnavn.value;
    tilEmail = o.tilemail.value;


    var reg = /,/;

    //ccontains a comma
    if (reg.test(tilEmail)) {
        var singleEmails = tilEmail.split(",");

        for (var i = 0; i < singleEmails.length; i++) {
            singleEmail = singleEmails[i];
            singleEmail = singleEmail.replace(/^\s+|\s+$/, '') ;

            if ( ! isValidEmail(singleEmail) ) {
                alert("'" + singleEmail + "'" + " er ikke en valid e-mailadresse");
                o.tilemail.focus();
                return false;
            }
        }
    } else {
        if ( ! isValidEmail(tilEmail) ) {
            alert("'" + tilEmail + "'" + " er ikke en valid e-mailadresse");
            o.tilemail.focus();
            return false;
        }
    }

    if (navn.length<1){
        alert("Skriv dit navn");
        o.ditnavn.focus();
        return false;
    }

    if (!o.dinmail.value.match(/^[a-z0-9\-_\.]+@[a-z0-9\-_\.]+\.\w{2,4}$/i)) {
        alert("Skriv en e-mailadresse");
        o.dinmail.focus();
        return false;
    }

    alert('Din mail er sendt');
    return true;
}

function anmeld(clipid, comment){
    if (confirm("Er du sikker p\u00E5 indsende en klage over dette klip?")) {
//  jQuery.post("http://web.ekstrabladet.dk/VisArtikel.asp?TemplateID=14629&clipid=" + clipid +"&comment="+ comment, function(data){ alert("Din klage er modtaget!" + data); }) }
    jQuery.post("/template/v1-1/components/nationentv/flagClip.jsp?TemplateID=14629&clipid=" + clipid +"&comment="+ comment, function(data){ alert("Din klage er modtaget!" + data); }) }
}

function showComment(clipid) {
    jQuery("#komment").empty();
    jQuery("#komment").prepend("<iframe src=\"http://web.ekstrabladet.dk/VisArtikel.sasp?TemplateID=14682&id=" + clipid + "\" width=\"425\" height=\"400\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" allowtransparency=\"true\" scrolling=\"auto\" /></iframe>");
    jQuery("#komment").show();
}


function ntvToggle(arg, forced) {
    var objStyle = document.getElementById(arg);

    // forced
    if (forced) {
        objStyle.style.display = forced;
    }

    // othwerwise toogle
    else {
        objStyle.style.display == "none" ? objStyle.style.display = 'block' : objStyle.style.display = 'none';
    }

    var objText = document.getElementById('advToggleText');

    var catddObj = document.getElementById('catdd');

    // then show text depending on display state
    var fritekstId = "sogeord";
    var categoryId = 'catdd';
    if ( objStyle.style.display == "none") {
        objText.innerHTML = 'Avanceret s&oslash;gning';

        if (catddObj) {
            checkForEmptiness(fritekstId, categoryId, fritekstId);
            //catddObj.disabled = false;
        }
    } else {
        objText.innerHTML = "Simpel s&oslash;gning";
        if (catddObj) {
            checkForEmptiness(fritekstId, categoryId, fritekstId);
            catddObj.disabled = true;
        }
    }
}

function ntvSetValues() {
    // always first set tags
    document.getElementById('tags').value = document.getElementById('sogeord').value;

    var obj = document.getElementById('adv_soeg');
    // then possibly clear the non-displayed fields
    if (obj.style.display == "none") {
        ntvResetSearch();
    }
}


function ntvResetSearch() {

    // clear the cookies
    eraseCookie("cat")
    eraseCookie("sortering")
    eraseCookie("interval")

    var array = $("#adv_soeg").find("input:checkbox");

    // reset all checkboxes
    array.each(function(i) {
        $(this).attr('checked', '');
    });


    var array2 = $("#adv_soeg").find("input:radio");
    // reset all radios
    array2.each(function(i) {
        var str = $(this).attr('value');

        if (str == 'altid') {
            $(this).attr('checked', 'checked');
        }

    });

    // date sort
    document.getElementById("date-desc").checked = true;

}



/* controlling tabs and login and messages */
function genericDisplay(elementId, notLoggedIn, msg) {
    var loggedIn = false;
    var login = isLoggedIn();


    if (login || notLoggedIn) {

        if (login) {
            loggedIn = true;
        }

        // display the relevant div
        var objId = document.getElementById(elementId);
        if (objId) {
            objId.style.display = 'block';
        }

        // show a login error messsage
        if (notLoggedIn && msg ) {
            var msgId = document.getElementById('loginfejlbesked');
            if (msgId) {
                msgId.innerHTML = msg;
            }
        }
    }
    // not logged in, show the login box with a message
    else {
        displayLoginMsg( msg );
        loggedIn = false;
    }

    return loggedIn;
}

function displayClips(linkUrl) {
    createCookie("ntv-tab", 'klips', 1);

    // if logged in, otherwise just display error msg
    if ( genericDisplay(null, 0, "Du skal være logget ind for se dine klips") ) {
        eraseCookie("ntv-tab");
        loginLinks('klips', linkUrl);
    }
}

function displayUpload() {
    createCookie("ntv-tab", 'upload', 1);
    genericDisplay("upload", 0, "Du skal være logget ind for at uploade videoer");
}

function displayLoginMsg(msg) {
    displayLogin(msg);
}

function displayLogin(msg) {
    var loggedIn = genericDisplay("ikkeloggetind", 1, msg);
    if (! loggedIn ) {
        $("#ikkeloggetind #username").focus();
    }
}


function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }
}


function verifyInput(startingPointId, appendingPointId, clipId) {

    var isValid = true;
    var appendToId = "";
    if (clipId) {
        appendToId = "_" + clipId;
    }

    // check for emptiness
    var reg = /^\s*$/;

    // get fields from this point
    var idFields = $(startingPointId).find(":input");

    // then validate
    idFields.each(function(i) {
        var inpType = $(this).attr('type');
        var id = $(this).attr('id');
        var val = $(this).attr('value');


        var msg = "";

        if (inpType == "checkbox") {

            var isChecked = $(this).attr('checked');
            if (! isChecked) {
                isValid = false;
                msg = " Du skal være indforstået med Ekstra Bladets regler!";
            }
        }

        else {
            if ( reg.test( val) ) {
                isValid = false;
                if (id == "fil" + appendToId) {
                    msg = "Du mangler at vælge en fil!";
                }
                if (id == "title" + appendToId) {
                    msg = "Du mangler at udfylde titel!";
                }
                if (id == "tags" + appendToId) {
                    msg = "Du mangler at udfylde tags!";
                }
                if (id == "ingress" + appendToId) {
                    msg = "Du mangler at udfylde beskrivelse!";
                }
                if (id == "category" + appendToId) {
                    msg = "Du mangler at vælge en kategori!";
                }
            }
        }


        if (msg != "") {
            var chunk = '<span class=\"ntv-sklip2\"><strong>' + msg + '</strong></span>';
            //console.log (chunk);

            //$("#error_msg_" + clipId).append(chunk);
            $(appendingPointId).append(chunk);
        }
    });

    return isValid
}

function isValidUser() {
    isValid = false;
    var userId = getCookie('userid');
    var reg = /^\d+$/;

    if (userId != null) {
        if (reg.test(userId)) {
            isValid = true;
        }
    }
    return isValid;
}


function isLoggedIn() {
    var loggedIn = false;
    var ticket = getCookie('ticketcookie');

    if(ticket != null ) {
        if ( ticket.length > 0 ) {
            if ( isValidUser()) {
                loggedIn = true;
            }
        }
    }
    return loggedIn;
}


function showRedirectLinks() {
    var showTabContentId = getCookie('ntv-tab');

    // no cookie, so we might look at the uri, if coming from external source
    if (! showTabContentId != "") {
        showTabContentId = getQueryVariable('ntv-tab');

        // lasr resort
        if (! showTabContentId != "") {
            showTabContentId = getQueryVariable('tab');
        }
    }


    if (showTabContentId && showTabContentId != "") {
        eraseCookie("ntv-tab");
        if (showTabContentId == 'klips') {
            loginLinks(showTabContentId);
        } else {
            genericDisplay(showTabContentId);
        }
    }
}


/*
    upload
*/

function validateUploadForm() {
    var isValid = false;
    var startingPointId = "#uploadForm";
    var appendingPointId = "#uploadMsg";

    if (! isLoggedIn() ) {
        $(appendingPointId).html("");
        var chunk = '<span class=\"ntv-sklip2\"><strong>Du er ikke logget ind</strong></span>';
        $(appendingPointId).append(chunk);
        displayUpload();
        $(startingPointId).hide();
        // bail out no need to validate  if not logged in
        return;
    }
    else {
        // first possibly empty the fields
        $(appendingPointId).html("");
        isValid = verifyInput(startingPointId, appendingPointId, "upload");
    }

    if (! isValid) {
        $(appendingPointId).show();
    } else {

        // show progress text
        $(appendingPointId).html("");
        var chunk = '<span class=\"ntv-sklip2\"><strong>Dit klip uploades. Vent venligst ...</strong></span>';
        $(appendingPointId).append(chunk);

        // encode
        if ($.browser.msie ) {
            transform();
        }

        // hide the form fields, show progress
        $(startingPointId).hide("slow");

    }
    return isValid;
}

UTF8 = {
    encode: function(s){
        for(var c, i = -1, l = (s = s.split("")).length, o = String.fromCharCode; ++i < l;
        s[i] = (c = s[i].charCodeAt(0)) >= 127 ? o(0xc0 | (c >>> 6)) + o(0x80 | (c & 0x3f)) : s[i]
    );
        return s.join("");
    },

    decode: function(s){
        for(var a, b, i = -1, l = (s = s.split("")).length, o = String.fromCharCode, c = "charCodeAt"; ++i < l;
        ((a = s[i][c](0)) & 0x80) && (s[i] = (a & 0xfc) == 0xc0 && ((b = s[i + 1][c](0)) & 0xc0) == 0x80 ? o(((a & 0x03) << 6) + (b & 0x3f)) : o(128), s[++i] = "")
    );
        return s.join("");
    }
};

// escape certain fields value for IE
function transform() {

    var formFields = $("#uploadForm").find(":input");

    formFields.each(function(i) {
        var id = $(this).attr('id');
        var inValue = $(this).attr('value');

        var reg = /^(title_upload|tags_upload|ingress_upload)$/;
        if (reg.test(id)) {
            if ( inValue != ""  ) {
                var esc = UTF8.encode ( inValue );
                $(this).attr('value', esc);
            }
        }
    });
}


 /*
    myclips
 */

function getBlue(clipId, strEvent) {
    strClass = "ntv-bb";

    if (isExpanded("editclip_" + clipId) ) {
        if (strEvent) {
            strClass = "ntv-bbedit";
        }
    }
    else {
        if (strEvent) {
            strClass = "ntv-bb";
        }
    }
    $("#singleclip_" + clipId).attr("class", "");
    $("#singleclip_" + clipId).addClass("ntv-kliplist " + strClass + " clearfix");
}

function getWhite(clipId) {
    if ( isExpanded("editclip_" + clipId) ) {
        getBlue(clipId, 1);
    } else {
        $("#singleclip_" + clipId).attr("class", "");
        $("#singleclip_" + clipId).addClass("ntv-kliplist ntv-wb clearfix");
    }
}

function showDeleteMsg(clipId) {
    $("#genericDelMsg_" + clipId).html("");
    $("#genericDelMsg_" + clipId).hide();


    if ( ! isExpanded("confirm_msg_" + clipId) ) {
        $("#confirm_msg_" + clipId).show();
        // then close the edit field

        if ( isExpanded("editclip_" + clipId) ) {
            $("#editclip_" + clipId).hide();
        }
    } else {
        $("#confirm_msg_" + clipId).hide();
    }
}


function isExpanded(id) {
    objId = document.getElementById(id);
    if (objId.style.display != "none") {
        return true;
    }
    return false;
}

function hideDeleteMsg(clipId) {
    $("#confirm_msg_" + clipId).hide();
}

function editClip(clipId) {

    if ( ! isExpanded("editclip_" + clipId) ) {
        $("#editclip_" + clipId).show();

        // expanding the form, stay blue in the whole div
        getBlue(clipId, 1);

        if ( isExpanded("confirm_msg_" + clipId) ) {
            $("#confirm_msg_" + clipId).hide();
        }
    } else {
        getBlue(clipId);
        $("#editclip_" + clipId).hide();
    }
}

function getMsgHTML(type, status, append) {
    var msg= '';
    if (type == "update") {
        msg= 'Klippet er nu opdateret!';
        if (status.toUpperCase() != "OK") {
            msg= 'Klippet kunne ikke opdateres. Prøv venligst senere!';
        }
    }
    else if (type == "delete") {
        msg= 'Klippet er nu slettet!';
        if (status.toUpperCase() != "OK") {
            msg= 'Klippet kunne ikke slettes. Prøv venligst senere!';
        }
    }

    if (append) {
        msg += " " + append;
    }
    var chunk = "<span class=\"ntv-sklip3\"><strong>" + msg + "</strong></span>";
    return chunk;
}

function updateClip(clipId) {
    var startingPointId = "#edit_form_" + clipId;
    var appendingPointId = "#error_msg_" + clipId;

    // first possibly empty the fields
    $(appendingPointId).html("");
    $(appendingPointId).hide();

    var isValid = verifyInput(startingPointId, appendingPointId, clipId);

    if (! isValid) {
        $(appendingPointId).show();
        return false;
    }


    $("#genericMsg_" + clipId).html("");
    $("#genericMsg_" + clipId).show();

    // basically convert the POST to a GET
    var qString = "";
    var formFields = $("#edit_form_" + clipId).find(":input");
    var newTitle = "";
    formFields.each(function(i) {
        var name = $(this).attr('name');
        var value = $(this).attr('value');

        // show for dynmaic display
        if (name == "title") {
            newTitle = value;
        }

        // then escape for IE/safari
        if ($.browser.msie || $.browser.safari ) {
            value = escape(value);
        }

        //finally append to query string
        qString += "&" + name + "=" + value;
    });

    qString = "action=update" + "&clipid=" + clipId + "&userid=" + getCookie('userid') + qString;
    // show a message

    var xStreamStatus = "NOT OK";

    $.ajax({
        url: serviceUrl,
        type: 'POST',
        data: qString,
        dataType: 'xml',
        timeout: 5000,
        success: function(xml){
            // close this doen if shown
            deleteId = document.getElementById("confirm_msg_" + clipId);
            if (deleteId.style.display != "none") {
                deleteId.style.display = 'none';
            }

            if ( $(xml).find('RESULT').text() ) {
                xStreamStatus = $(xml).find('RESULT').text();
            }

            if (xStreamStatus.toUpperCase() != "OK") {
                var chunk = getMsgHTML("update", xStreamStatus);
                $("#genericMsg_" + clipId).append(chunk);
            } else {
                // all went well hide the form
                $("#htmltitle_" + clipId).html("");
                $("#htmltitle_" + clipId).append(newTitle);
                $("#editclip_" + clipId).hide();
            }


        },
        error: function (xhr, status, e) {
            var chunk = getMsgHTML("update", xStreamStatus);
            $("#genericMsg_" + clipId).append(chunk);
        }

    });

}
function deleteClip(clipId) {
    $("#genericDelMsg_" + clipId).html("");
    $("#genericDelMsg_" + clipId).hide();

    var xStreamStatus = "NOT OK";

    $.ajax({
        url: serviceUrl,
        type: 'GET',
        data: "action=delete" + "&clipid=" + clipId + "&userid=" + getCookie('userid'),
        dataType: 'xml',
        timeout: 5000,
        success: function(xml){
            if ( $(xml).find('status').text() ) {
                xStreamStatus = $(xml).find('status').text();
            }

            if (xStreamStatus.toUpperCase() != "OK") {
                var chunk = getMsgHTML("delete", xStreamStatus, "[1001]");
                $("#genericDelMsg_" + clipId).append(chunk);
                $("#genericDelMsg_" + clipId).show();
            } else {
                // provided deletion went well, shut the clicked clipid
                if ( isExpanded("singleclip_" + clipId) ) {
                    $("#singleclip_" + clipId).hide();
                }

                if ( isExpanded("confirm_msg_" + clipId) ) {
                    $("#confirm_msg_" + clipId).hide();
                }
            }

        },
        error: function (xhr, status, e) {
            var chunk = getMsgHTML("delete", xStreamStatus, "[1002]");
            $("#genericDelMsg_" + clipId).append(chunk);
            $("#genericDelMsg_" + clipId).show();
        }
    });
}
