/*
 * MusicSearchMain.js
 * (c)2009 Bell Systems LLC
 * 
 * License: http://bellspace.net/licenses/non-commercial.html (Non-Commercial) 
 * Licensing: http://bellspace.net/licensing/index.html 
 * 
 * pageMain() program for tab_slang index.php
 *
 */

dojo.addOnLoad(pageMain)

function pageMain()
{
	//add keyboard enter submit 
    initForms(document.getElementById("search_button"));
}

function musicSearchErrorFunction(response)
{
    ERR.innerHTML = "MusicSearchMain.js: ajaxCall() error. Please try again.";
	ERR.innerHTML += "<br/>"
	ERR.innerHTML += response
};  

//default search is for tabs
var gSearchType = "tabs";
var gSearchButton = false;
function musicSearch(buttonObj)
{
	gSearchButton = buttonObj;
	
 	//START SEARCH BUTTON LOADING INDICATOR
 	gSearchButton.original_value = gSearchButton.value;
 	startLoadingIndicator(gSearchButton);    
 	
	var tabsRadio = document.getElementById("tabs_radio");
	tabsRadio.onclick = function()
	{
		gSearchType = "tabs";
	}
	var lyricsRadio = document.getElementById("lyrics_radio");
	lyricsRadio.onclick = function()
	{
		gSearchType = "lyrics";
	}
	
	if(lyricsRadio.checked)
	{
		gSearchType = "lyrics";
	}

	var searchStringInput = document.getElementById("search_string");
	
	if(searchStringInput.value == "")
	{
		alert("Sorry, at least 1 character needs to be typed.");
		return;
	}
	
	//get our containing divs and hide them
	document.getElementById("artists_div").style.display = "none";
	document.getElementById("tabs_div").style.display = "none";
	document.getElementById("lyrics_div").style.display = "none";
	
	//reset any errors/debugging shown
	DBUG.innerHTML = "";
	ERR.innerHTML = "";
		
	//initialize and run the search
    var successFunction = function(response)
    {
		if(response != "")
		{
			var t = response.split(",");
			for(var i=0; i<t.length; i++)
			{
				updateTable(t[i]);
			}
		}     
    };  
	    
    var param = "http://" + myHost + "/tab_slang/lib/php/ajax/MusicSearch.php?search_string=" + searchStringInput.value + "&search_type="+gSearchType;
    ajaxCall(param, successFunction, musicSearchErrorFunction);	
	//alert("tab search is on hiatus. check back soon")
}

var lastSelectedRowObj = false;
function loadArtistContent(trObj, artistId)
{
	trObj.className = "spring_green_row" //spring green

	if(lastSelectedRowObj)
	{
		//this little if statement essentially means we can only have
		//one spring green row per artist table
		lastSelectedRowObj.className = lastSelectedRowObj.original_className;
	}
	lastSelectedRowObj = trObj;
	
    //highlight the row that we clicked
    /*var nameSpan = trObj.childNodes[0].childNodes[0];
    nameSpan.original_innerHTML = nameSpan.innerHTML;
    nameSpan.innerHTML = "Loading..."
    nameSpan.style.fontWeight = "bold";
    nameSpan.style.color = "red";*/   
		
    //get our containing divs and hide them
    //document.getElementById("tabs_div").style.display = "none";
    
    //initialize and run the search
    var successFunction = function(response)
    {
        updateTable(gSearchType);
		//nameSpan.style.color = ""; 
		//nameSpan.style.fontWeight = ""; 
		//nameSpan.innerHTML = nameSpan.original_innerHTML;
    };  
    
	if(gSearchType == "tabs")
	{
        var param = "http://" + myHost + "/tab_slang/lib/php/ajax/MusicSearch.php?get_tabs_by_artist_id=true&artist_id="+artistId;
	}
	else if(gSearchType == "lyrics")
	{
        var param = "http://" + myHost + "/tab_slang/lib/php/ajax/MusicSearch.php?get_lyrics_by_artist_id=true&artist_id="+artistId;		
	}
    ajaxCall(param, successFunction, musicSearchErrorFunction);	
}

function updateTable(tableName, sortCol, extendedType)
{
    var response;
    
    if(!sortCol)
    {
        sortCol= "";
    }	
	
    if(!extendedType)
    {
        extendedType = "";
    }
    
    if(extendedType == "refresh")
    {
        var editButton = document.getElementById("edit_selected");
        var deleteButton = document.getElementById("delete_selected");  
        editButton.style.display = "none";
        deleteButton.style.display = "none";        
    }
	
	//alert("in updateTable()")
	
    //first we update the table
    var onSuccessUpdateTable = function(response)
    {
		//stop search button loading indicator
		resetLoadingIndicator(gSearchButton) 
    	
        var tableContainer = document.getElementById(tableName + "_table_container")
        if(tableContainer)
        {
            tableContainer.innerHTML = response;
			if(sortCol == "")
			{
				//if we are sorting the height of the container will not change
                tableContainer.style.height = "auto";
			}
            var table = tableContainer.getElementsByTagName("table")[0];
            
            //sometimes the table is not there because there are no results
            if(table)
            {           
                //add the onmouseover/onmouseout highlighting
                tableHighlight(tableContainer.getElementsByTagName("table")[0]);
                
                //add onclick/onmouseover/onmouseout functionality to <input> elements
                addTableExtensions(tableContainer.getElementsByTagName("table")[0]);   
                
                if(extendedType == "edit")
                {
                    //fetchCurrentNav();
                }
			
                document.body.style.overflow = "hidden";
                
				//make the results visible in the document
				if(browserDetect.browser == "Explorer")
				{
					//ie sucks.. it cant reset the scrollbars like
					//the rest of the browsers
                    tableContainer.style.height = 164 + "px";					
				}
				
				tableContainer.parentNode.style.display = "block";
				//alert(tableContainer.offsetHeight)
				//the table container height cant be greater than 164
				//if it is we set it to 164 so it can overflow with scrollbars
				if(tableContainer.offsetHeight > 164)
				{
					tableContainer.style.height = 164 + "px";
				}
				document.body.style.overflow = "auto";
				//tableContainer.parentNode.style.visibility = "visible";				
            }
        }
        
        //then we update the table_header
        var onSuccessUpdateTableHeader = function(response)
        {
			var headerContainer = document.getElementById(tableName+"_header_container");
            headerContainer.innerHTML = response;
			var tableContainer = document.getElementById(tableName+"_table_container");
			
			//a cool peice of code that can tell if a scrollbar is present
			//this is needed in mac browsers because the scrollbar
			//squishes content to the left
			if(browserDetect.OS == "Mac")
			{
				if((tableContainer.clientHeight < tableContainer.scrollHeight) && (!headerContainer.macResizedHack))
				{
					//scrollbar width is 15... so we extend the width 15
					headerContainer.style.width = headerContainer.clientWidth + 13 + "px";
					
					//dont resize this again
					headerContainer.macResizedHack = true;
				}
			}
        };  
        
        var param = "http://" + myHost + "/tab_slang/lib/php/ajax/LoadTable.php?table_name="+tableName+"&table_header=true&extendedType=" + extendedType;
        //DBUG.innerHTML += param + "<br>";        
		ajaxCall(param, onSuccessUpdateTableHeader, musicSearchErrorFunction);
    };
    
    var param = "http://" + myHost + "/tab_slang/lib/php/ajax/LoadTable.php?table_name="+tableName+"&table=true&sortCol=" + sortCol + "&extendedType=" + extendedType;
    //DBUG.innerHTML += "START " + param + "<br>";
	//alert(param);
	ajaxCall(param, onSuccessUpdateTable, musicSearchErrorFunction);
}

var gClientX;
var gClientY;

function loadContentIntoFloater(trObj, e, contentId)
{
	
	if(navigator.userAgent.match(/iPhone/i))
	{
		window.location.href = ""
	}
	
    theEvent = getEventObject(e);
	gClientX = theEvent.clientX;
	gClientY = theEvent.clientY;
		
	//get the tab name (first col in the trObj)	
	var rowCols = trObj.getElementsByTagName("td");
	//open tab in new window
    if(gSearchType == "tabs")
	{	
        var tabName = '<a target="_blank" href="lib/php/ajax/getContent.php?tab_id='+contentId+'">'+rowCols[0].innerHTML + '</a>';
        var tabNameNoHtml = rowCols[0].childNodes[0].innerHTML;
        var tabType = rowCols[1].innerHTML;
        var tabRating = rowCols[2].innerHTML;
        var tabArtist = rowCols[3].innerHTML;
        var downloadLink = document.createElement('span');
        downloadLink.innerHTML = '<a style="float:right; margin-right:2px;" href="lib/php/ajax/getContent.php?tab_id='+contentId+'&download_file=true&file_name='+tabNameNoHtml+'">Download</a>';
        var titleBarContent = tabArtist + " |&nbsp;" + tabName + "&nbsp;|&nbsp;" + tabType + "&nbsp;|&nbsp;Rating:&nbsp;" + tabRating; 	   
    }
	else if(gSearchType == "lyrics")
	{
		var lyricName = '<a target="_blank" href="lib/php/ajax/getContent.php?lyric_id='+contentId+'">'+rowCols[0].innerHTML +'</a>';
        var lyricNameNoHtml = rowCols[0].childNodes[0].innerHTML;
        var lyricArtist = rowCols[1].innerHTML;
        var downloadLink = document.createElement('span');
        downloadLink.innerHTML = '<a style="float:right; margin-right:2px;" href="lib/php/ajax/getContent.php?lyric_id='+contentId+'&download_file=true&file_name='+lyricNameNoHtml+'">Download</a>';
        var titleBarContent = lyricArtist + " | " + lyricName;   						
	}
	
    //highlight the row that we clicked
    var nameSpan = trObj.childNodes[0].childNodes[0];
    nameSpan.original_innerHTML = nameSpan.innerHTML;
    nameSpan.innerHTML = "Loading..."
	nameSpan.style.fontWeight = "bold";
    nameSpan.style.color = "red";	
	
    //get the tab content and put it into a floater
    var successFunction = function(response)
    {
        if(response != "")
        {
            createdFloater = brandNewFloater(titleBarContent, response);
			createdFloater.clickedRowObj = trObj;
			
			nameSpan.style.color = "";
			nameSpan.style.fontWeight = "";
			nameSpan.innerHTML = nameSpan.original_innerHTML;

			trObj.className = "spring_green_row" //spring green
			
			//unhighlight the row because we closed the window
			createdFloater.resetRowHighlight = function()
			{
				this.clickedRowObj.className = this.clickedRowObj.original_className;
			}
			dojo.connect(createdFloater, "close", createdFloater, "resetRowHighlight")

			//right aligned titleBar stuff 
			//currently we have the "Download" <a>
			var closeIcon = getElementByClassName("dojoxFloatingCloseIcon", createdFloater.domNode);
			//alert(closeIcon.parentNode.childNodes.length);

			//digitInline is a <span> that contains the title
			var digitInline = getElementByClassName("dijitInline dijitTitleNode", createdFloater.domNode)
			digitInline.parentNode.insertBefore(downloadLink, digitInline);
			
            createdFloater.windowShadeMinimize = function()
			{
                var titlePane = getElementByClassName("dojoxFloatingPaneTitle", this.domNode);
				this.domNode.original_domNodeHeight = this.domNode.offsetHeight-1;
				this.domNode.original_domNodeWidth = this.domNode.offsetWidth-1;
				this.domNode.style.height = titlePane.offsetHeight-1 + "px";
				this.domNode.style.width = digitInline.offsetWidth + 110 + "px";
			}

            createdFloater.windowShadeMaximize = function()
			{
				this.domNode.style.height = this.domNode.original_domNodeHeight + "px";
				this.domNode.style.width = this.domNode.original_domNodeWidth + "px";
			}
			
			//everything is backwards from dojo... we convert the maximize function
			//to a minimize function
            createdFloater.maximize = function()
            {
                this.windowShadeMinimize();
                var theMinimizeIcon = getElementByClassName("dojoxFloatingMaximizeIcon", this.domNode);
                theMinimizeIcon.style.display = "none";
				var theMaximizeIcon = getElementByClassName("dojoxFloatingMinimizeIcon", this.domNode);
				theMaximizeIcon.style.display = "inline";
            }
			
			//convert the maximize function to a minimize function;
			createdFloater.minimize = function()
			{
				this.windowShadeMaximize();
                var theMinimizeIcon = getElementByClassName("dojoxFloatingMaximizeIcon", this.domNode);
                theMinimizeIcon.style.display = "inline";
                var theMaximizeIcon = getElementByClassName("dojoxFloatingMinimizeIcon", this.domNode);
                theMaximizeIcon.style.display = "none";				
			}					
                
			//below are two more ways to do what I did with dojo.connect() above
			
			/*dojo.extend(dojox.layout.FloatingPane,{ attr: function(){}, attr2:....})*/
			
			/*createdFloater.close = function()
			{
				if(!this.closable)
				{
					return;
				}
				dojo.unsubscribe(this._listener);
				this.hide(dojo.hitch(this,"destroyRecursive",arguments));
				this.clickedRowObj.className = this.clickedRowObj.original_className;	
			}*/
		}       
    };  	

    if(gSearchType == "tabs")
	{
        var param = "http://" + myHost + "/tab_slang/lib/php/ajax/getContent.php?tab_id="+contentId;
	}
	else if(gSearchType == "lyrics")
	{
        var param = "http://" + myHost + "/tab_slang/lib/php/ajax/getContent.php?lyric_id="+contentId;		
	}

	if(navigator.userAgent.match(/iPhone/i))
	{
		//simple view for iphone only
		//window.location.href = param;
		window.open (param, titleBarContent,"menubar=1,resizable=1,width=600,height=480");
	}

    //DBUG.innerHTML += "START " + param + "<br>";
    ajaxCall(param, successFunction, musicSearchErrorFunction);		
}

function brandNewFloater(titleBarContent, Content)
{
    var node = document.createElement('div');
    var myPaneContainer = document.createElement("div");
	
	if(browserDetect.browser == "Explorer")
	{
        //if not "inline" scrollbars will build up when they should not
        myPaneContainer.style.display = "inline";
        myPaneContainer.style.margin = "0 auto";
	}
         
	var xmp = document.createElement("xmp");
	xmp.style.marginLeft = "7px";
	if(browserDetect.browser == "Explorer")
	{
		xmp.style.overflow = "auto";
		xmp.innerText = Content;
	}
	else
	{
	   xmp.innerHTML = Content;
	}
    node.appendChild(xmp);
    document.body.appendChild(myPaneContainer);
    myPaneContainer.appendChild(node);
    
    var floater = new dojox.layout.FloatingPane(
    {
        title:titleBarContent,
        dockable: false,
        maxable: true,
        closable: true,
        resizable: false
    },node);
	//open where cursor is
    //floater.domNode.style.top = gClientY + "px";
    //floater.domNode.style.left = gClientX + "px";          
	
	//open in center of window
    if(browserDetect.browser == "Explorer")
    {
        floater.domNode.style.top = (document.documentElement.clientHeight/2)-(400/2) + "px";
		floater.domNode.style.left = (document.documentElement.clientWidth/2)-(650/2) + "px";
    }
    else
    {
        floater.domNode.style.top = (window.innerHeight/2)-(400/2) + "px";
		floater.domNode.style.left = (window.innerWidth/2)-(650/2) + "px";
    }   	        
    
	floater.startup();
    floater.resize({ w:650, h:400 });   
    floater.bringToTop();
	 
	return floater;
}