//env variables
var urlBasePath = '/v3/';
var fullURL = 'http://keertan.panthic.net/v3/';

//other useful globals
var parentDir = 0;
var XMLData;
var isSearch = 0;
var isIE = false;

//check if user logged in
//var ISLOGGEDIN = 0;

//run playlist, or is it an edit button?
var RUNPLAYLIST = 1;

function getSecondElement(myArry)
{
	return myArry[1];
}


function getElementsByClass(oElm, strTagName, strClassName){
    var arrElements = (strTagName == "*" && oElm.all)? oElm.all :
        oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    strClassName = strClassName.replace(/\-/g, "\\-");
    var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
    var oElement;
    for(var i=0; i<arrElements.length; i++){
        oElement = arrElements[i];
        if(oRegExp.test(oElement.className)){
            arrReturnElements.push(oElement);
        }
    }
    return (arrReturnElements)
}


function getStyleClass(className) {
	for (var s = 0; s < document.styleSheets.length; s++)
	{
		if(document.styleSheets[s].rules)
		{
			for (var r = 0; r < document.styleSheets[s].rules.length; r++)
			{
				if (document.styleSheets[s].rules[r].selectorText == '.' + className)
				{
					return document.styleSheets[s].rules[r];
				}
			}
		}
		else if(document.styleSheets[s].cssRules)
		{
			for (var r = 0; r < document.styleSheets[s].cssRules.length; r++)
			{
				if (document.styleSheets[s].cssRules[r].selectorText == '.' + className)
					return document.styleSheets[s].cssRules[r];
			}
		}
	}

	return null;
}

function checkIfIE()
{
        return /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
}


//checkbox play stuff

function checkall()
{
	void(d=document);
	void(el=d.getElementsByTagName('INPUT'));
	for(i=0;i<el.length;i++)
	void(el[i].checked=1)
}
function uncheckall()
{
	void(d=document);
	void(el=d.getElementsByTagName('INPUT'));
	for(i=0;i<el.length;i++)
	void(el[i].checked=0)
}
function save()
{
	checkall();
	document.getElementById('playForm').save.value = 1;
	document.getElementById('playForm').submit();
	document.getElementById('playForm').save.value = 0;
	uncheckall();
}
function playall()
{
	checkall();
	document.getElementById('playForm').submit();
	uncheckall();
}

function getFlashPlayer(objectId) {
  return (window[objectId]) ? window[objectId] : document[objectId];
}

function createPlayer(xml)
{
        var flashvars = {keertan: urlBasePath+xml};
        var params = {wmode: "transparent"};
        var attributes = {id:"flashPlayer",name:"flashPlayer"};
        document.getElementById("flashPlayerContainer").innerHTML = '<div id="flashPlayer"><center><br><a href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a></center></div>';
        swfobject.embedSWF(urlBasePath+"flash/player_pl_int.swf", "flashPlayer", "161", "225", "8.0.0", urlBasePath+"flash/expressInstall.swf", flashvars, params, attributes);
}

function loadFlashPl(playlist)
{
        (playlist=="rand")? playlist += "=1" : playlist = "plID=" + playlist;
        getFlashPlayer("flashPlayer").keertan(urlBasePath+'viewTracks.php5?XML=1&'+playlist,true);
}

function add2playlist()
{
        if(!document.getElementById('playForm')['files[]'])
        {
                alert('You must select tracks to add to your playlist.');
                return false;
        }
        
        url = "";
        count = 0;
        if(document.getElementById('playForm')['files[]'].length == undefined)
        {
                url = '&files[]='+document.getElementById('playForm')['files[]'].value;
        }
        else
        {
                for (var i=0; i < document.getElementById('playForm')['files[]'].length; i++)
                {
                        if (document.getElementById('playForm')['files[]'][i].checked)
                        {
                                url = url+'&files[]='+document.getElementById('playForm')['files[]'][i].value;
                                count = count + 1;
                        }
                }
        }
        ajaxpage('myplfuncs.php5?act=add2pl'+url,'dummydiv', 0, "alert(document.getElementById('dummydiv').innerHTML)");
        loadFlashPl(CURRENTPL);
}

function newpl()
{
        ajaxpage('myplfuncs.php5?act=newpl','dummydiv', 0, 'CURRENTPL=document.getElementById("dummydiv").innerHTML; playlists(CURRENTPL)');
}

function PlEditBox(folderName){
        RUNPLAYLIST = 0;
        folderName.parentNode.onclick = function(){return false};
        getStyleClass('plEdit').style.display='none';
        getStyleClass('plDelete').style.display='none';
        name = folderName.innerHTML;
        folderName.innerHTML = '<input type=text id="folderNameChange" value="'+name+'" onkeypress="return PlDoEdit(this.value, document.getElementById(\'dummydiv\').innerHTML, event);" onBlur="PlDoEdit(this.value, document.getElementById(\'dummydiv\').innerHTML, \'blur\')">';
        document.getElementById('folderNameChange').focus();
}

function PlDelete(id,folderName){
        RUNPLAYLIST = 0;
        folderName.parentNode.onclick = function(){return false};
        RUNPLAYLIST = 1;
        if(confirm('Are you sure you want to delete this playlist?'))
        {
                loadingmsg('topBlock');
                ajaxpage('myplfuncs.php5?act=delpl&ID='+id,'dummydiv', 0, 'CURRENTPL=document.getElementById("dummydiv").innerHTML; playlists(CURRENTPL)');
        }
}

function PlDeleteTrack(id,plid)
{
        if(confirm('Are you sure you want to remove this track from your playlist?'))
        {
                loadingmsg('botBlock');
                ajaxpage('myplfuncs.php5?act=delpltrack&ID='+id+'&PL='+plid,'dummydiv', 0, 'playlists('+plid+')');
        }
}

function submitPlay()
{
return true;
        if(RUNPLAYLIST)
        {
                return true;
        }
        else
        {
                PlDoEdit(document.getElementById('folderNameChange').value, document.getElementById('dummydiv').innerHTML);
                return false;
        }
}

function PlDoEdit(value, id, e)
{
        var keycode;
        if (window.event) keycode = window.event.keyCode;
        else if (e && e != blur) keycode = e.which;
        else keycode = '';

        if (keycode == 13 || e == 'blur')
        {
                RUNPLAYLIST = 1;
                loadingmsg('topBlock');
                ajaxpage('myplfuncs.php5?act=PlDoEdit&ID='+id+'&val='+value, 'dummydiv', 0, 'playlists()');
                getStyleClass('plEdit').style.display='inline-block';
                getStyleClass('plDelete').style.display='inline-block';
                return false;
	}
	else return true;

}

function setCurrentPl(id, newcurrent)
{
        ajaxpage('myplfuncs.php5?act=setCurrentPl&ID='+id,'dummydiv');
        
        //dumb ie doesnt support this so we have to use a custom func if its not there
        if (document.getElementsByClassName != undefined)
        {
                selected = document.getElementById('topBlock').getElementsByClassName('playlistSelected');
        }
        else
        {
                selected = getElementsByClass(document.getElementById('topBlock'),'a','playlistSelected');
        }
        if(isIE)
        {
                selected[0].setAttribute("className", 'playlist');
                newcurrent.setAttribute("className", "playlistSelected");
        }
        else
        {
                selected[0].setAttribute("class", 'playlist');
                newcurrent.setAttribute("class", "playlistSelected");
        }
        CURRENTPL = id;
        loadFlashPl(id);
        return true;
}

//this function will load the top and bottom boxes at once
function loadTopAndBottom(url1, url2) {
    loadingmsg('topBlock');
    loadingmsg('botBlock');
    ajaxpage(url1, 'topBlock');
    ajaxpage(url2, 'botBlock');
}

function loadTop(url) {
    loadingmsg('topBlock');
    ajaxpage(url, 'topBlock');
}

function loadHome(){
        loadTop('blog/index.php');
        permalink();
        hideBotBar();
}

function showUpload(){
        permalink('upload');
        hideBotBar();
        if(ISLOGGEDIN)
        {
                showIFrame('http://media.panthic.net/upload/');
        }
        else
        {
                document.getElementById('topBlock').innerHTML = "You must be logged in to upload tracks.";
        }
}

function init()
{
        membarPost();
        Custom.init();
        isIE = checkIfIE();
        document.getElementById('butDirUp').href=urlBasePath+'category/'+parentDir;
}

function showIFrame(site)
{
                document.getElementById('topBlock').style.display='none';
                document.getElementById('botBlock').style.display='none';
                document.getElementById('topIFrame').src=site;
                document.getElementById('topIFrame').style.display='block';
}

function hideTopBar() {
        document.getElementById('topIFrame').style.display='none';
        document.getElementById('topBlock').style.display='none';
        document.getElementById('dirBar').style.display='none';
        document.getElementById('botBlock').style.height='650px';
}

function hideBotBar() {
        document.getElementById('topBlock').style.display='block';
        document.getElementById('topIFrame').style.display='none';
        document.getElementById('botBlock').style.display='none';
        document.getElementById('dirBar').style.display='none';
        document.getElementById('topBlock').style.height='650px';
}

function hideTop() {
        document.getElementById('topBlock').style.display='none';
        document.getElementById('botBlock').style.height='610px';
        document.getElementById('topIFrame').style.display='none';
}

function hideBottom() {
        if(document.getElementById('topBlock').style.display!='none')
        {
                document.getElementById('topIFrame').style.display='none';
                document.getElementById('botBlock').style.display='none';
                document.getElementById('topBlock').style.height='610px';
        }
        else
        {
                if (isSearch==0)
                {
                        document.getElementById('botBlock').innerHTML="This Directory is empty.";
                }
                else
                {
                        document.getElementById('botBlock').innerHTML="Your search returned no results.";
                }
        }
}

function read(trackID, shabad, catID, CatParent, VAL1){
        if(!shabad){shabad='';}
        if(!CatParent){CatParent='';VAL1='';}
        if (!document.getElementById('readBlock')) {
                document.getElementById('topBlock').innerHTML=document.getElementById('botBlock').innerHTML;
        }
        loadingmsg('botBlock');
        document.getElementById('topIFrame').style.display='none';
        document.getElementById('dirBar').style.display='block';
        document.getElementById('botBlock').style.display='block';
        document.getElementById('topBlock').style.display='block';
        document.getElementById('topBlock').style.height='260px';
        document.getElementById('botBlock').style.height='350px';
        ajaxpage('read.php5?ID='+trackID+'&CatID='+catID+'&Shabad='+shabad+'&VAL1='+VAL1+'&CatParent='+CatParent,'botBlock');
        if(shabad==''){shabad='list';}
        if(CatParent!=''){smart='/'+CatParent+'/'+VAL1;}
        else{smart='';}
        permalink('read/'+catID+'/'+trackID+'/'+shabad+smart);
}

function loadCat(catID) {
        loadingmsg('topBlock');
        loadingmsg('botBlock');
        idString = catID+' ';
        if(idString.indexOf("Query")>=0)
        {
                loadSearch();
        }
        else
        {
                permaCatID = catID;
                if(isNaN(catID))
                {
                        permaCatID = permaCatID.replace(/&CatParent=/i, '/').replace(/&VAL1=/i, '/');
                }
                permalink('category/'+permaCatID);
                document.getElementById('butDirUp').style.display='block';
                document.getElementById('curDirLabel').innerHTML='Current Directory:';
                isSearch = 0;
        }
        document.getElementById('butNewPL').style.display='none';
        document.getElementById('topBlock').style.height='260px';
        document.getElementById('botBlock').style.height='350px';
        document.getElementById('dirBar').style.display='block';
        document.getElementById('botBlock').style.display='block';
        document.getElementById('topBlock').style.display='block';
        document.getElementById('topIFrame').style.display='none';
        loadCatXML(catID);
        loadTracks(catID);
}

function playlists(plID) {
        if(RUNPLAYLIST==0)
        {
                RUNPLAYLIST = 1;
                return false;
        }
        
        plID = (plID)? plID : CURRENTPL;

        loadingmsg('topBlock');
        loadingmsg('botBlock');

        ajaxpage('myplaylists.php5', 'topBlock', 0, 'playlistsInit()');
        permalink('playlists/'+plID);
        document.getElementById('butDirUp').style.display='none';
        document.getElementById('butNewPL').style.display='block';
        document.getElementById('curDirLabel').innerHTML=' ';
        
        isSearch = 0;
        loadTracks(plID,'plID');

        (plID==CURRENTPL)? loadFlashPl(plID) : 0;
        
        document.getElementById('topBlock').style.height='260px';
        document.getElementById('botBlock').style.height='350px';
        document.getElementById('dirBar').style.display='block';
        document.getElementById('topIFrame').style.display='none';
        document.getElementById('botBlock').style.display='block';
        document.getElementById('topBlock').style.display='block';
        document.getElementById('curDirTxt').innerHTML='My Playlists';
        document.getElementById('curDirTxt').title='My Playlists';
}

function playlistsInit()
{
        Custom.init(document.getElementById('topBlock'));
}

//call the XML
function loadCatXML(ID) {
    ajaxpage('viewCats.php5?ID='+ID, '', 1, 'loadCatData()');
}

//Data has arrived load it into the page
function loadCatData(){
        parentDir=XMLvar('Parent');
        document.getElementById('butDirUp').href=urlBasePath+'category/'+XMLvar('Parent');
        if (isSearch==0)
        {
                document.getElementById('curDirTxt').innerHTML=XMLvar('CatName');
                document.getElementById('curDirTxt').title=XMLvar('FullCatName');
        }
        var Cats = XMLvar('Cats');
        if(Cats.length > 5)
        {
                document.getElementById('topBlock').innerHTML=Cats;
                Custom.init(document.getElementById('topBlock'));
        }
        else
        {
                hideTop();
        }
}

//call the ajax
function loadTracks(ID,field) {
        if(!field){field = 'ID';}
        ajaxpage('viewTracks.php5?'+field+'='+ID, 'botBlock', 0, 'loadTracksPost(page_request.responseText)');
}

//Data has arrived load it into the page
function loadTracksPost(response){
        if(response.length > 5)
        {
                Custom.init(document.getElementById("botBlock"));
        }
        else
        {
                hideBottom();
        }
}

function searchInt(Query,page)
{
        if(Query.length < 4)
        {
                alert('Your search must be at least 4 characters long.');
        }
        else
        {
                page = page? page : 1;
                loadCat('&Query='+Query+'&Page='+page);
        }
}

function searchWWW(Query,page)
{
        if(Query.length < 4)
        {
                alert('Your search must be at least 4 characters long.');
        }
        else
        {
                document.getElementById('botBlock').style.display='block';
                loadingmsg('botBlock');
                page = page? page : 1;
                isSearch=1;
                hideTop();
                permalink('searchWWW/'+Query+'/'+page);
                ajaxpage('sphider/index.php?query='+Query+'&start='+page+'&search=1&category=-1&mark=markblue&results=25&media_only=1&type=and', 'botBlock', 0, 'loadTracksPost(page_request.responseText);');
        }
        loadSearch();
}

function loadSearch()
{
        document.getElementById('butDirUp').style.display='none';
        document.getElementById('curDirLabel').innerHTML='Your Search:';
        theQuery = document.getElementById('queryBox').value;
        document.getElementById('curDirTxt').title=theQuery;
        permalink('search/'+escape(theQuery));
        if(theQuery.length>47)
        {
                theQuery = theQuery.substr(0,47);
        }
        document.getElementById('curDirTxt').innerHTML=theQuery;
        isSearch = 1;
}

function permalink(link)
{
        if(!link) link = '';
        document.getElementById('permaLinkTxt').value = fullURL+link;
        document.getElementById('butPermaLink').href=fullURL+link;
        
}
function permaLinkPop()
{
        if(document.getElementById('permaLinkPop').style.display!='block')
        {
                blanket_size();
                document.getElementById('blanket').style.display='block';
                document.getElementById('permaLinkPop').style.display='block';
        }
        else
        {
                document.getElementById('permaLinkPop').style.display='none';
                document.getElementById('blanket').style.display='none';
        }
}

function embedCodePop(plID,track)
{
        if(document.getElementById('embedCodePop').style.display!='block')
        {
                blanket_size();
                track? page="trackEmbedCode" : page="embedCode";
                document.getElementById('embedCode').src=urlBasePath+page+".php5?ID="+plID;
                document.getElementById('blanket').style.display='block';
                document.getElementById('embedCodePop').style.display='block';
        }
        else
        {
                document.getElementById('embedCodePop').style.display='none';
                document.getElementById('blanket').style.display='none';
        }
}
function blanket_size() {
	if (typeof window.innerWidth != 'undefined') {
		viewportheight = window.innerHeight;
	} else {
		viewportheight = document.documentElement.clientHeight;
	}
	if ((viewportheight > document.body.parentNode.scrollHeight) && (viewportheight > document.body.parentNode.clientHeight)) {
		blanket_height = viewportheight;
	} else {
		if (document.body.parentNode.clientHeight > document.body.parentNode.scrollHeight) {
			blanket_height = document.body.parentNode.clientHeight;
		} else {
			blanket_height = document.body.parentNode.scrollHeight;
		}
	}
	var blanket = document.getElementById('blanket');
	blanket.style.height = blanket_height + 'px';
}


function CreateBookmarkLink(title,url) {

	if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url,"");
	} else if( window.external ) { // IE Favorite
		window.external.AddFavorite( url, title); }
	else if(window.opera && window.print) { // Opera Hotlist
		return true; }
 }

//functions to get rid of membar errors
function goLite(){}
function goDim(){}

//membarajax
function login()
{
        thisForm = document.getElementById("membarLogin");
        params = 'user='+thisForm.user.value+'&pass='+thisForm.pass.value;
        loadingmsg('membarContainer');
        ajaxpage('membar.php5','membarContainer', 0, 'membarPost()', 'POST', params);
}

function logout()
{
        ajaxpage('membar.php5?logout=1','membarContainer', 0, 'membarPost()');
}

function membarPost()
{
        if(document.getElementById('membarLoggedIn') != null)
        {
                ISLOGGEDIN = 1;
        }
        else
        {
                ISLOGGEDIN = 0;
        }
}

function copy2Clipboard(myText) {
        myText = myText.replace(/<br>/i, "\\r\\n");
  if (window.clipboardData) {
    window.clipboardData.setData("Text",myText);
  }
  else {
    var flashcopier = 'flashcopier';
    if(!document.getElementById(flashcopier)) {
      var divholder = document.createElement('div');
      divholder.id = flashcopier;
      document.body.appendChild(divholder);
    }
    document.getElementById(flashcopier).innerHTML = '';
    var divinfo = '<embed src="http://images.panthic.net/_clipboard.swf" FlashVars="clipboard='+encodeURIComponent(myText)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
    document.getElementById(flashcopier).innerHTML = divinfo;
  }
}

// YES I USED A PREMADE SCRIPT FOR DOING THE DYNAMIC PAGE THING. SUE ME!

/***********************************************
* Dynamic Ajax Content- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

var bustcachevar=1 //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadedobjects=""
var rootdomain="http://"+window.location.hostname
var bustcacheparameter=""
var topurl=""
var bottomurl=""

function loadingmsg(containerid) {
    document.getElementById(containerid).innerHTML='<div class="loadmsg"><img src="'+urlBasePath+'images/loading.gif" />Loading...</div>';
}

function ajaxpage(url, containerid, xml, func, method, params){

    var page_request = false
    url = urlBasePath+url;
    
    if(!method)
    {
        method='GET';
    }

    if (window.XMLHttpRequest) // if Mozilla, Safari etc
        page_request = new XMLHttpRequest()
    else if (window.ActiveXObject){ // if IE
        try {
            page_request = new ActiveXObject("Msxml2.XMLHTTP")
        }
        catch (e){
            try{
                page_request = new ActiveXObject("Microsoft.XMLHTTP")
            }
            catch (e){}
        }
    }
    else
        return false
if (bustcachevar) {//if bust caching of external page
    bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
    page_request.open(method, url+bustcacheparameter, true)
    if(method=='GET')
    {
        page_request.send(null)
    }
    else
    {
        //Send the proper header information along with the post request
        page_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        page_request.setRequestHeader("Content-length", params.length);
        page_request.setRequestHeader("Connection", "close");
        page_request.send(params);
    }

}
    page_request.onreadystatechange=function(){
        if(xml==1)
        {
                loadXML(page_request,func);
        }
        else
        {
                loadpage(page_request, containerid, func);
        }
    }

}

function loadpage(page_request, containerid, func){
        if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)){
                document.getElementById(containerid).innerHTML=page_request.responseText;
                if(func) {eval(func);}
        }
}

function loadXML(page_request, func){
    if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)){
        // store the server's XML response
        window.XMLData = page_request.responseXML;
        eval(func);
        }
}

function XMLvar(theVar){
        return window.XMLData.getElementsByTagName(theVar)[0].firstChild.data;
}

function loadobjs(){
    if (!document.getElementById)
        return
    for (i=0; i<arguments.length; i++){
        var file=arguments[i]
        var fileref=""
        if (loadedobjects.indexOf(file)==-1){ //Check to see if this object has not already been added to page before proceeding
            if (file.indexOf(".js")!=-1){ //If object is a js file
                fileref=document.createElement('script')
                fileref.setAttribute("type","text/javascript");
                fileref.setAttribute("src", file);
            }
            else if (file.indexOf(".css")!=-1){ //If object is a css file
                fileref=document.createElement("link")
                fileref.setAttribute("rel", "stylesheet");
                fileref.setAttribute("type", "text/css");
                fileref.setAttribute("href", file);
            }
        }
    if (fileref!=""){
        document.getElementsByTagName("head").item(0).appendChild(fileref)
        loadedobjects+=file+" " //Remember this object as being already added to page
    }
}
}
