var staticurl = 'http://62.216.251.201';
//  display block/none bonanza for 2 divs
function toggleDiv(div1,div2){
    a = document.getElementById(div1);
    b = document.getElementById(div2);
    var old = a.style.display;
    a.style.display = b.style.display;
    b.style.display = old;
    return false;
}


function ModuleTabs(tabs,contents,tab,content) {
    // do the tabs not the donkey
    for(var i=0; i<tabs.length; i++){
        document.getElementById(tabs[i]).style.fontWeight = "normal";
    }
    document.getElementById(tab).style.fontWeight = "bold";
    // do the contents not the donkey
    for(var i=0; i<contents.length; i++){
        document.getElementById(contents[i]).style.display = "none";
    }
    document.getElementById(content).style.display = "block";
}

// disable form button
function loading(obj,txt){
    obj.value=txt;
    obj.disabled = "disabled";
}

//popup FAQ
function faq(id){
var popurl='/faqpopup.php?id='+id;
    winpops=window.open(popurl,'','width=600,height=400,scrollbars,');
}
// TODO newer, needs checking which one is used
function faqPopup (q) {
    faq = window.open("/popups/faq.php?q="+q,"faq","toolbar=no, location=no, directories=no, status=no,menubar=no, scrollbars=yes, resizable=yes, width=350, height=400");
}

//any popup
function popup(url){
    faq = window.open(url,"faq","toolbar=no, location=no, directories=no, status=no,menubar=no, scrollbars=yes, resizable=yes, width=350, height=400");
}

// Small album display  bonanza
function smallAlbum(){
    a = document.getElementById("myAlbumsSmall");
    b = document.getElementById("myAlbumsBig");
    var old = a.style.display;
    a.style.display = b.style.display;
    b.style.display = old;
    return false;
}

pos = Array();

var scrollWidth = 520;
var steps = 8;
var cnt = 1;
var rDir = "";
var speed = 1;
var change = 1.7;


function confirmMessage(txt){
    var agree=confirm(txt);
    if (agree)
        return true ;
    else
        return false ;
}
        
function scrollDiv(o, dir) {
    rDir = dir;
    nextScroll(o);
}

function nextScroll (o) {
        cnt++;
        var scrollNow = parseInt(rDir+(scrollWidth/steps));
        moveH(o, scrollNow);
        if ( cnt <= steps ) {
                speed = speed*change;
                setTimeout("nextScroll('" + o + "')",speed);
        }
        else {
                cnt = 1;
                speed = 2;
        }
}

function moveH(o, l) {
        if (!pos[o])
            pos[o] = 0;
        pos[o] += l;
        if (pos[o] > 0)
            pos[o] = 0;
        //if (pos[o] < -5200) 
        //    pos[o] = -5200;
        
        getObj(o).style.left = pos[o] + "px"; 
}

function getObj(n) {
  return (document.getElementById) ? document.getElementById(n) : document.all.n;
}

function Terms() {
	var Terms = open(staticurl+"/terms.html","terms","Height=500,Width=400,scrollbars=yes,resizable=yes");
}

function CheckAll(state) {
	var formObj = document.getElementById("checkForm");
	elLength = formObj.elements.length;
	for (i=0; i < elLength; i++) {   
    	formObj.elements[i].checked=state;
	}
} 

function getSelectedCheckbox(buttonGroup) {
   // Go through all the check boxes. return an array of all the ones
   // that are selected (their position numbers). if no boxes were checked,
   // returned array will be empty (length will be zero)
   var retArr = new Array();
   var lastElement = 0;
   if (buttonGroup[0]) { // if the button group is an array (one check box is not an array)
      for (var i=0; i<buttonGroup.length; i++) {
         if (buttonGroup[i].checked) {
            retArr.length = lastElement;
            retArr[lastElement] = i;
            lastElement++;
         }
      }
   } else { // There is only one check box (it's not an array)
      if (buttonGroup.checked) { // if the one check box is checked
         retArr.length = lastElement;
         retArr[lastElement] = 0; // return zero as the only array value
      }
   }
   return retArr;
} // Ends the "getSelectedCheckbox" function

function getSelectedCheckboxValue(buttonGroup) {
   // return an array of values selected in the check box group. if no boxes
   // were checked, returned array will be empty (length will be zero)
   var retArr = new Array(); // set up empty array for the return values
   var selectedItems = getSelectedCheckbox(buttonGroup);
   if (selectedItems.length != 0) { // if there was something selected
      retArr.length = selectedItems.length;
      for (var i=0; i<selectedItems.length; i++) {
         if (buttonGroup[selectedItems[i]]) { // Make sure it's an array
            retArr[i] = buttonGroup[selectedItems[i]].value;
         } else { // It's not an array (there's just one check box and it's selected)
            retArr[i] = buttonGroup.value;// return that value
         }
      }
   }
   return retArr;
} // Ends the "getSelectedCheckBoxValue" function

function maxlength(obj,len) {
	if(obj.value.length > len) {
        // this alert() is on one line.
        var newValue = obj.value.substr(0,len);
        obj.value = newValue;
        alert('You can only enter '+ len +' letters. We have cut your message to the right size, please try again.')
        //alert('The maximum number of characters this field will accept is '
		//+ len + ' characters.\nIt currently contains ' + obj.value.length + '.
		//Please remove at least ' + (obj.value.length - len) + ' characters.');
        // this alert() is on one line.
        obj.focus();
    }
}

/* this belongs in right.js

function addToBookmarks (id,type,name,artist,jointype) {
	var idString = new String(id);
	var ids = idString.split(",");
	var nameString = new String(name);
	var names = nameString.split(",");
	
	switch (jointype) {
		case 1 : 
		var idtype = "bookmark";
		break;
		case 2 : 
		var idtype = "collected";
		break;
	}
	
	//// delete Help div when first entry gets added
	if ( helpNode = document.getElementById(idtype+"Help") ) {
		helpNodeid = idtype+"Help";
		removeNodeById (helpNodeid);
	}
	
	
	for ( i = 0; i < ids.length; i++ ) {
		// get parent node
		var parentNode = document.getElementById(idtype+"Container");
		// create new nodes
		var nodeDiv = document.createElement("div");
		nodeDiv.setAttribute("class", "ProfileItem" );
		nodeDiv.setAttribute("id", idtype+"-"+type+"-"+ids[i] );
		
		var nodeIconDiv = document.createElement("div");
		nodeIconDiv.setAttribute("class", "ProfileIcon" );
		
		
		//create new text node to hold info
		if ( artist != '' ) {
			var textContent = document.createTextNode(artist+" - "+names[i]);
		}
		else { 
			var textContent = document.createTextNode(names[i]);
		}
		var nodeA = document.createElement("a");
		
		switch (type) {
			case 6 : 
			var link = "artist.php?id=";
			var icon = "artist";
			break;
			case 8 : 
			var link = "album.php?id=";
			var icon = "album";
			break;
			case 9 : 
			var link = "track.php?id=";
			var icon = "song";
			break;
			case 4 : 
			var icon = "user";
			var link = "user?id=";
		}
		
		nodeA.setAttribute("href", link+ids[i] );
		
		var nodeImg = document.createElement("img");
		nodeImg.setAttribute("src", "http://static.last.fm:8000/images/icons/"+icon+"L.gif" );
		nodeImg.setAttribute("border", "0");
		nodeImg.setAttribute("alt", "");
		
		//create new text node to hold info
		if ( artist != '' ) {
			var textContent = document.createTextNode(artist+" - "+names[i]+" ");
		}
		else { 
			var textContent = document.createTextNode(names[i]+" ");
		}
		
		var nodeDel = document.createElement("a");
		nodeDel.setAttribute("href", "/resourceListActions.php?nodeid="+idtype+"-"+type+"-"+ids[i]+"&mode=delete&childid="+ids[i]+"&childtype="+type+"&jointype="+jointype );
		nodeDel.setAttribute("target", "ActionFrame" );
		var textDel = document.createTextNode("[del]");	
		
		nodeIconDiv.appendChild(nodeImg);
		nodeA.appendChild(textContent);
		nodeDel.appendChild(textDel);
		
		nodeDiv.appendChild(nodeIconDiv);
		nodeDiv.appendChild(nodeA);
		nodeDiv.appendChild(nodeDel);
		parentNode.insertBefore(nodeDiv,parentNode.childNodes[0]);
	}
}

function removeNodeById (nodeid) {
	var childNode = document.getElementById(nodeid);
    if(childNode){
    	var parentNode = childNode.parentNode;
    	parentNode.removeChild(childNode);
    }
}
*/
function removePreviewTrack(id){
    removeNodeById('previewplaylist-track-'+id);
}
function removePreviewTracks(){
    var p = document.getElementById('previewedContainer');
    while (p.firstChild)
        p.removeChild(p.firstChild);
    document.getElementById('PreviewPlaylistContainer').style.display = 'none';
}

function removeOndemandTrack(id){
    removeNodeById('ondemandplaylist-track-'+id);
}
function removeOndemandTracks(){
    var nodes = document.getElementById('ondemandedContainer').childNodes;
    for(var i=0; i<nodes.length;i++){
        var p = nodes[i].parentNode;
        if(p) removeNodeById(nodes[i].id);
    }
    document.getElementById('OndemandPlaylistContainer').style.display = 'none';
}

function addOndemandTrack(id,artist,track,cover){
    if(!cover) cover="http://static.last.fm/images/icons/songSG.gif";
    document.getElementById('OndemandPlaylistContainer').style.display = 'block';
    var n = document.createElement("div");
    n.setAttribute("class","RightItem");
    n.setAttribute("id","ondemandplaylist-track-"+id);
    var n1 = document.createElement("div");
    n1.setAttribute("class","RightIcon");
    var img = document.createElement("img");
    img.setAttribute("src",cover); 
    img.setAttribute("height",17); 
    img.setAttribute("border","0");
    n1.appendChild(img);
    n.appendChild(n1);
    var ri = document.createElement("div");
    ri.setAttribute("class","RightInfo");
    var ai = document.createElement("a");
    ai.setAttribute("href","/track.php?id="+id);
    var str = document.createElement("strong");
    str.appendChild(document.createTextNode(artist));
    ai.appendChild(str);
    ai.appendChild(document.createElement("br"));
    ai.appendChild(document.createTextNode(track));
    ri.appendChild(ai);
    var ai2 = document.createElement("a");
    ai2.setAttribute("href","/iframes/playlistActions.php?a=deleteondemand&track="+id);
    ai2.setAttribute("target","ActionFrame");
    ai2.appendChild(document.createTextNode(" [del]"));
    ri.appendChild(ai2);
    n.appendChild(ri);
    document.getElementById('ondemandedContainer').appendChild(n);
}
function addPreviewTrack(id,artist,track,cover,flp){
    //isn't DOM manipulation fun :>
    document.getElementById('PreviewPlaylistContainer').style.display = 'block';
    var n = document.createElement("div");
    n.setAttribute("class","RightItem");
    n.setAttribute("id","previewplaylist-track-"+id);
    var n1 = document.createElement("div");
    n1.setAttribute("class","RightIcon");
    var img = document.createElement("img");
    img.setAttribute("src",cover); 
    img.setAttribute("border","0");
    img.setAttribute("height","17");
    n1.appendChild(img);
    n.appendChild(n1);
    var ri = document.createElement("div");
    ri.setAttribute("class","RightInfo");
    var ai = document.createElement("a");
    ai.setAttribute("href","/track.php?id="+id);
    var str = document.createElement("strong");
    str.appendChild(document.createTextNode(artist));
    ai.appendChild(str);
    ai.appendChild(document.createElement("br"));
    ai.appendChild(document.createTextNode(track));
    if (flp == true) { // FLP icon if any
        var icon = document.createElement("img");
        icon.setAttribute("src",staticurl+'/images/icons/flpS.gif');
        icon.setAttribute("border","0");
        icon.setAttribute("class","middle");
        ri.appendChild(icon);
        ri.appendChild(document.createTextNode(" "));
    }
    ri.appendChild(ai);
    var ai2 = document.createElement("a");
    ai2.setAttribute("href","/iframes/playlistActions.php?a=deletepreview&track="+id);
    ai2.setAttribute("target","ActionFrame");
    ai2.appendChild(document.createTextNode(" [del]"));
    ri.appendChild(ai2);
    n.appendChild(ri);
    document.getElementById('previewedContainer').appendChild(n);
}

function visitIn(loc,ms){
  setTimeout("window.location.href='"+loc+"'",ms);
}


function CheckAll(name) {
    var formObj = document.getElementById(name);
    elLength = formObj.elements.length;
    for (i=0; i < elLength; i++) {
        formObj.elements[i].checked=!formObj.elements[i].checked;
    }
}

function doPlaylist(id){
    actionFrame("/iframes/playeraction.php?a=startplaylist&playlist="+id);
}

function doPlaylistInvitation(key){
    actionFrame("/iframes/playeraction.php?a=startplaylistinvitation&key="+key);
}

// Stuff for the playlist editor:

function remove(){
    with (document.getElementById('frm')) {
          for (var i=0;i<tracklist.length;i++) {
               if (tracklist.options[i].selected) {
                    tracklist.options[i]=null;
               }
          }
    }
}
function checkPlaylist(dosave){
    var tlist = document.getElementById('frm').tracklist;
    var str='';
    for(i=0; i<tlist.length; i++){
        str = str + tlist.options[i].value + ',';
    }
    setTrackList();
    if(dosave){
        miscFrame('/iframes/playlistcheck.php?dosave=yes&tracks='+str);
    }else{
        miscFrame('/iframes/playlistcheck.php?tracks='+str);
    }
    return false;
}

function submitPlaylist(){
    var f = document.getElementById('frm');
//    alert('tracks value: '+document.getElementById('tracks').value);
    f.submit(); 
}

function setTrackList(){
    var tlist = document.getElementById('frm').tracklist;
    var str='';
    for(i=0; i<tlist.length; i++){
        str = str + tlist.options[i].value + ',';
    }
    document.getElementById('tracks').value=str;
    return true; 

}
function move(d){
    with (document.getElementById('frm')) {
          for (var i=0;i<tracklist.length;i++) {
               if (tracklist.options && tracklist.options[i].selected) {
                    if((d<1 && i>0) || (d==1 && i<tracklist.length-1)){
                        var txt1 = tracklist.options[i+d].text;
                        var val1 = tracklist.options[i+d].value;
                        var txt2 = tracklist.options[i].text;
                        var val2 = tracklist.options[i].value;
                        tracklist.options[i+d]=new Option(txt2,val2);//tracklist.options[i];
                        tracklist.options[i]=new Option(txt1,val1);
                        tracklist.options[i+d].selected=true;
                    }
               }
          }
    }
}
function existsInPlaylist(id){
    var tracklist = document.getElementById('frm').tracklist;
    for (var i=0;i<tracklist.length;i++) {
        if (tracklist.options[i].value == id) return true;
    }
    return false;
}
function wipeFoundResults(){
    //while ((child = document.getElementById('SearchResults').firstChild) != null){
    //    document.getElementById('SearchResults').removeChild(child);
   // }
}
function notFoundError(txt){
    //wipeFoundResults();
    //va//r d = document.getElementById('SearchResults');
    //d.appendChild(document.createTextNode(txt));
    //d.appendChild(document.createElement("br"));
}
function displayFoundTrack(id,txt){
    var d=document.createElement("span");
    d.setAttribute("vertical-align","middle");
    document.getElementById('SearchResults').appendChild(d);
    var n = document.createElement('a');
    n.setAttribute("href","#");
    n.setAttribute("onclick","listTrack("+id+",'"+addSlashes(txt)+"'); return false;");
    n.appendChild(document.createTextNode(' [add] '));
    d.appendChild(n);
    var n2 = document.createElement('a');
    n2.setAttribute("href","#");
    n2.setAttribute("onclick","previewTrack("+id+"); return false;");
    n2.appendChild(document.createTextNode(' [prv] '));
    d.appendChild(n2);
    var n3 = document.createElement('a');
    n3.setAttribute("href","/track.php?id="+id);
    n3.setAttribute("target","Popup");
    n3.appendChild(document.createTextNode(txt));
    d.appendChild(n3);
    d.appendChild(document.createElement("br"));
}
function addSlashes(txt){
    //hope this works with all browsers ?
    var re = new RegExp ('\'', 'gi') ;
    var newstr = txt.replace(re, '\\\'') ;
    return newstr;
}
function listTrack(id,txt){
    if(existsInPlaylist(id)){
    //    notFoundError('Track already in playlist.');
        return false;   
    }
    document.getElementById('frm').tracklist.options[document.getElementById('frm').tracklist.length]=new Option(txt,id);
}

function search(){
  //  wipeFoundResults();
    //notFoundError('Searching... Please Wait...');
    var lid='';
    var x = document.getElementById('frm').label;
    if(x){
        lid = x.value;
    }
    document.getElementById("SearchFrame").src='/iframes/playlistsearch.php?a=search&artist=' + 
               document.getElementById('frm').artist.value+'&song='
              +document.getElementById('frm').song.value + '&label='+lid;
}
function searchSimilar(){
//    wipeFoundResults();
    notFoundError('Finding similar music... Please Wait...');
    document.getElementById("SearchFrame").src='/iframes/playlistsearch.php?a=searchsimilar&artist=' + 
               document.getElementById('frm').artist.value+'&song='
              +document.getElementById('frm').song.value;
}

function chooseArtist(id,txt,current){
    var win = window.open("/popups/chooseartist.php?id="+id+"&txt="+txt+"&currentid="+current, 'popupchooser', 'status=no,resizable=no,scrollbars=yes, width=370, height=500');
    if(!win) alert("The artist chooser works using a popup window, which failed to open :(");
}

function chooseSong(id,txt,current){
    var win = window.open("/popups/choosesong.php?id="+id+"&txt="+txt+"&currentid="+current, 'popupchooser', 'status=no,resizable=no,scrollbars=yes, width=370, height=500');
    if(!win) alert("The song chooser works using a popup window, which failed to open :(");
}
function chooseAlbum(id,txt,current){
    var win = window.open("/popups/choosealbum.php?id="+id+"&txt="+txt+"&currentid="+current, 'popupchooser', 'status=no,resizable=no,scrollbars=yes, width=370, height=500');
    if(!win) alert("The album chooser works using a popup window, which failed to open :(");
}

function chooseLabel(id,txt,current){
    var win = window.open("/popups/chooselabel.php?id="+id+"&txt="+txt+"&currentid="+current, 'popupchooser', 'status=no,resizable=no, width=370, height=500');
    if(!win) alert("The label chooser works using a popup window, which failed to open :(");
}

function eliminatealbums(idlist){
    var win = window.open("/popups/eliminatealbums.php?idlist="+idlist, 'popupchooser', 'status=no,resizable=no,scrollbars=yes, width=600, height=600');
    if(!win) alert("The album chooser works using a popup window, which failed to open :(");
}

function setChosenItem(id,txt,newid,newtxt){
    var idbox=document.getElementById(id);
    var txtspan=document.getElementById(txt);
    idbox.value=newid;
    txtspan.removeChild(txtspan.firstChild);
    var b = document.createElement("b");
    b.appendChild(document.createTextNode(newtxt));
    txtspan.appendChild(b);                
}



function middleTest(){
    alert('this is a test');
}

/*function swapShopDisplay(textclass, tagname, class1, class2) {
    var debug = false;
    debug ? alert("swapShopDisplay('"+textclass+"', '"+tagname+"', '"+class1+"', '"+class2+"')") : null;
    var tags = document.getElementsByTagName(tagname);
    var texttag = document.getElementsByTagName('span');
    var textpat = new RegExp(textclass);
    var thisclass1dis = null;
    var thisclass2dis = null;
    var pattern1 = new RegExp(class1);
    var pattern2 = new RegExp(class2);
    if(debug) {
        alert(class1dis+' '+class2dis);
        var debug = '';
        for(var prop in tags) {
            debug=debug+"Name: "+prop+"; value: "+tags[prop]+"\n";
        }//end for
        alert(debug);
    }//end if
    for(var i=0; i < tags.length; i++) {
        var tag = tags[i];
        var attr = null;
        if(isIE) {
            debug ? alert("It's IE "+tag.getAttribute('class')) : null;
            attr = tag.getAttribute('className');
        } else {
            attr = tag.getAttribute('class');
            debug ? alert("It's not IE") : null;
        }//end else

        
        if(attr) {  
            if(attr.match(pattern1) != null) {
                if(thisclass1dis == null) {
                    thisclass1dis = class1dis = swapDis(class1dis);
                }//end if
                debug ? alert(class1+":"+thisclass1dis) : null;
                tag.style.display = thisclass1dis;
            } else if(attr.match(pattern2) != null) {
                if(thisclass2dis == null) {
                    thisclass2dis = class2dis = swapDis(class2dis);
                }//end if
                debug ? alert(class2+":"+thisclass2dis) : null;
                tag.style.display = thisclass2dis; 
            }//end else
        }//end if
    }//end for
    //alert(thisclass1dis+' '+thisclass2dis);
    for(var i=0; i < texttag.length; i++) {
        var tag = texttag[i];
        var attr = null;
        if(isIE) {
            attr = tag.getAttribute('className');
        } else {
            attr = tag.getAttribute('class');
        }//end else
        if(attr) {
            if(attr.match(textpat) != null) {
                if(thisclass1dis == 'none') {
                    if(attr.match(/!/) != null) {
                        tag.innerHTML = 'New';
                    } else {
                        tag.innerHTML = 'Used';
                    }//end else
                } else {
                    if(attr.match(/!/) != null) {
                        tag.innerHTML = 'Used';
                    } else {
                        tag.innerHTML = 'New';
                    }//end else
                }//end else
            }//end if
        }//end if
    }//end for
}//end func*/

isIE = document.all && navigator.userAgent.indexOf('Opera') == -1;
//alert(navigator.appName+' '+navigator.appVersion);
//document.write("<div style=\"position:absolute; background-color:white;z-index:3\"><pre>"+print_r(navigator)+"</pre></div>");

var class1dis = 'none';
var class2dis = 'block';

// old one see above
function swapShopDisplay(on,off) {
    // switch tabs
    var ontab = document.getElementById(on+'tab');
    var offtab = document.getElementById(off+'tab');
    ontab.style.fontWeight = "bold";
    offtab.style.fontWeight = "normal";
    // switch lists
    var onlist = document.getElementById(on+'list');
    var offlist = document.getElementById(off+'list');
    onlist.style.display = "block";
    offlist.style.display = "none";
}//end func

function swapDis(dis) {
    switch(dis) {
        case 'none':
            return 'block';
            break;
        case 'block':
            return 'none';
            break;
    }
}

function print_r(input, depth)
{
    if(typeof(depth) == 'number') {
        if(depth>1) return "Too Far\n";
        var indent = '    ';
        for(var j=0; j<depth; j++) {
            indent += indent;
        }
        paren_indent -= '  ';
        depth++;
    } else {
        var depth = 1;
        var indent = '    ';
        var paren_indent = '';
    }
    switch(typeof(input)) {
        case 'boolean':
            var output = (input ? 'true' : 'false') + "\n";
            break;
        case 'object':
            if ( input===null ) {
                var output = "null\n";
                break;
            }
            var output = ((input.reverse) ? 'Array' : 'Object') + " (\n";
            for(var i in input) {
                try {
                    output += indent + "[" + i + "] => " + print_r(input[i], depth);
                } catch(ex) {
                    //alert(ex+"\n"+depth+"\n");
                }
            }
            output += paren_indent + ")\n";
            break;
        case 'number':
        case 'string':
        default:
            var output = "" + input  + "\n";
    }
    return output;
}

//var bar = new Object()
//bar.foo = 'blue'
//var foo = new Array()
//foo['a'] = 1
//foo['b'] = 2
//var num = 3
//var str = 'I am a string'
//var nul = null
//alert(print_r(foo));
//alert(print_r(bar));
//alert(print_r(num));
//alert(print_r(str));
//alert(print_r(nul));
