﻿var d = document;

function PrepareXML( xmlText )
{
    var xmlDoc;
    var rText = new String( xmlText );
    rText = rText.replace(/&gt;/g, ">");
    rText = rText.replace(/&lt;/g, "<");
    
    if (window.ActiveXObject)
    {
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async=false;
        xmlDoc.loadXML( rText );
    }
    // code for Mozilla, etc.
    else if (document.implementation && document.implementation.createDocument)
    {
        var oParser = new DOMParser();
        xmlDoc = oParser.parseFromString(rText, "text/xml");
    }
    else
    {
        alert('Your browser cannot handle this script');
    }
    return xmlDoc;
}

function getXmlNode(xml, name)
{
    var value = "";
    
    if(xml)
    {
        var nodes = xml.getElementsByTagName(name);
        
        if(nodes && nodes.length > 0 && nodes[0].firstChild)
        {
            value = nodes[0].firstChild.nodeValue;
        }
    }
    return value;
}

///
// realigns a table that is composed of <td><span>...<span><span></td>
// where you want the spans to line up as if they were in their own td
///
function realignTable(tblId, tblHeaderId)
{
    var tbl = document.getElementById(tblId);
    
    if(!tbl)
    {
        return;
    }
    
    if(tbl.rows.length < 1)
    {
        return;
    }
    
    var tr = tbl.rows[0];
    var numSpans = tr.getElementsByTagName("span");
    
    if(!numSpans || !numSpans.length)
    {
        return;
    }

    var COLUMNS = numSpans.length;
    var maxWidths = new Array(COLUMNS);
    
    for(var i = 0; i < COLUMNS; i++)
    {
        maxWidths[i] = 0;
    }
    
    var spans;

    //loop through the rows of the table to find the widest columns
    for(var i = 0; i < tbl.rows.length; i++)
    {
        spans = tbl.rows[i].getElementsByTagName("span");
        
        for(var j = 0; j < spans.length; j++)
        {
            if(spans[j].offsetWidth > maxWidths[j%COLUMNS])
            {
                maxWidths[j%COLUMNS] = spans[j].offsetWidth;
            }
        }
    }
    
    var header = document.getElementById(tblHeaderId);
    
    spans = header.getElementsByTagName("span");

    //reset the spans in the tblHead
    for(var i = 0; i < spans.length; i++)
    {
        if(i == (spans.length - 1))
        {
            spans[i].style.marginRight = 0 + "px";
        }
        else
        {
            spans[i].style.marginRight = maxWidths[i] - spans[i].offsetWidth + "px";
        }
        //spans[i].style.marginRight = (maxWidths[i%COLUMNS] - spans[i].offsetWidth) + "px";
    } 
    
    //reset the spans in the tblBody
    spans = tbl.getElementsByTagName("span");
    for(var i = 0; i < spans.length; i++)
    {
        if(i == (spans.length - 1))
        {
            spans[i].style.marginRight = 0 + "px";
        }
        else
        {
            spans[i].style.marginRight = (maxWidths[i%COLUMNS] - spans[i].offsetWidth) + "px";
        }
    } 
}

function clearTable(tbodyId)
{
	var tbody = d.getElementById(tbodyId);

    	var element;

    	while(element = tbody.firstChild)
    	{
        	tbody.removeChild(element);
    	}
}

function createCoverDiv()
{
    if(!document.getElementById("divCover"))
    {
        var divCover = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
        divCover.className = "divCover";
        divCover.id = "divCover";
    
        // make sure its as tall as it needs to be to overlay all the content on the page
        divCover.style.height = d.documentElement.scrollHeight + "px";
        
        return divCover;
    }
    else
    {
        return d.getElementById("divCover");
    }
}

function removeCoverDiv()
{
    //check if div exists
    if(d.getElementById("divCover"))
    {
        //remove the div
        d.getElementsByTagName("body")[0].removeChild(d.getElementById("divCover"));
    }
}

function removePopupDiv(val)
{
	var divCover = d.getElementById("divCover");

	//check if div exists
    	if(divCover && d.getElementById(val))
    	{	
        	//remove the div
        	divCover.removeChild(d.getElementById(val));
    	}	
}

function createButton(id, text)
{
    var btn = document.createElement("input");
    btn.type = "button";
    btn.id = id;
    btn.value = text;
    
    return btn;
}

function centerObject(obj)
{
    // MSIE doesnt treat position:fixed correctly, so this compensates for positioning the alert
    if(d.all && !window.opera)
    {
         obj.style.top = d.documentElement.scrollTop + "px";
    }
    
    // center the alert box
    obj.style.left = ((d.documentElement.scrollWidth - obj.offsetWidth)/2) + "px";

    //hard code 50px from the top
    obj.style.top = "50px";
}

function getTitleDiv(text, titleText, divCoverId, titleTblId)
{
    if(text.length > 30)
    {
        text = text.substring(0, 30) + "...";
    }
    
    var div = d.createElement("div");
    div.className = "embeddedBackground";
    
    //float this label to the left
    span = div.appendChild(d.createElement("span"));
    span.className = "embeddedPopupTitleBar"
    
    spanText = d.createElement("span");
    spanText.appendChild(d.createTextNode(text));
    spanText.className = "spanText";
    span.appendChild(spanText);
    
    /*imgX = d.createElement("img");
    imgX.id = "imgX";
    imgX.src = "img/btn_closeWin.gif";
    imgX.className = "spanX";
    imgX.onclick = function()
	{
	    if(!divCoverId)
	    {
		    //debugger;
		    closeWarning("divCover");
		}
		else
		{
		    closeWarning(divCoverId);
		}
	}
	
	span.appendChild(imgX);*/
   
    //return span;
    return div;
}


//gives the absolute position of the obj
function findPos(obj) 
{
	var curleft = curtop = 0;
	if (obj.offsetParent) 
	{
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		
		while (obj = obj.offsetParent) 
		{
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}

	
	return [curleft,curtop];
}

function escapeSpecialChars(str)
{
    var index = 0;

    //replace ampersand
    while(index < str.length && str.indexOf("&", index) >= 0)
    {
        index = str.indexOf("&", index);
        
        //split the string at the index
        var str1 = str.substr(0, index + 1);
        var str2 = str.substring(index + 1, str.length)
        
        str = str1 + "amp;" + str2;
        index = index + 4;
    }
    
    //replace >
    while(str.indexOf(">") >= 0)
    {
        str = str.replace(">", "&gt;");
    }
    
    //replace <
    while(str.indexOf("<") >= 0)
    {
        str = str.replace("<", "&lt;");
    }
    
    //replace %
    while(str.indexOf("%") >= 0)
    {
        str = str.replace("%", "&#37;");
    }
    
    //replace '
    while(str.indexOf("'") >= 0)
    {
        str = str.replace("'", "&apos;");
    }
    
    //replace \
    while(str.indexOf("\"") >= 0)
    {
        str = str.replace("\"", "&quot;");
    }
    
    //alert(str);
    return str;
}

function escapeforXML(str)
{
	var re = new RegExp("&", "g");
	str = str.replace(re, "&amp;");
    
	var re1 = new RegExp(">", "g");
	str = str.replace(re1, "&gt;");
    
	var re2 = new RegExp("<", "g");
	str = str.replace(re2, "&lt;");
    
	var re3 = new RegExp("'", "g");
	str = str.replace(re3, "&apos;");
    
	var re4 = new RegExp("\"", "g");
	str = str.replace(re4, "&quot;");
    
    return str;
}

function replaceSpecialChars(str)
{
    var index = 0;
	
    while(str.indexOf("&gt;") >= 0)
    {
        str = str.replace("&gt;", ">");
    }
	//str.replace(/&gt;/g, ">");
    
    while(str.indexOf("&lt;") >= 0)
    {
        str = str.replace("&lt;", "<");
    }
	//str.replace(/&lt;/g, "<");
	
    while(str.indexOf("&#37;") >= 0)
    {
        str = str.replace("&#37;", "%");
    }
    //str.replace(/&#37;/g, "%");
	
    while(str.indexOf("&apos;") >= 0)
    {
        str = str.replace("&apos;", "'");
    }
    //str.replace(/&apos;/g, "'");
	
    while(str.indexOf("&quot;") >= 0)
    {
        str = str.replace("&quot;", "\"");
    }
    //str.replace(/&#37;/g, "%");
	
    str = replaceAmps(str);
    
    return str;
}

function replaceAmps(str)
{
    while(str.indexOf("&amp;") >= 0)
    {
        str = str.replace("&amp;", "&");
    }
    
    return str;
}

function checkForHTML(str) 
{

    //var str = document.getElementById("taText").value;
    //alert(str);
    //replace line breaks with <br>
    while (str.indexOf("\n") >= 0) 
    {
        str = str.replace("\n", '<br>');
    }

    //check to see if any links are within the comment


    //var link_matches = str.match(/^http:\/\/(.)*\s|\shttp:\/\/(.)*\s|\shttp:\/\/(.)*$/);

    if (str.match(/http:\/\/[\w\.]+/))
    {
        var comment = "";
        
        var lines = str.split("<br>");

        for (var i = 0; i < lines.length; i++)
        {
            if (lines[i].match(/http:\/\/[\w\.]+/))
            {
                //alert("we have a link");
                //now tokenize string and loop through tokens and replace any urls with the correct anchor tag

                var line = "";
                
                var words = lines[i].split(" ");

                for (var j = 0; j < words.length; j++)
                {
                    //alert(words[j]);
                    //alert(words[i]);
                    if (words[j].match(/http:\/\/[\w\.]+/) || words[j].match(/[.]+\.com/))
                    {
                        if (words[j].length > 50)
                        {
                            var link = "<a href='" + words[j] + "' target='_blank'>" + words[j].substring(0, 50) + "..." + "</a>";
                            line += link + " ";
                        }
                        else
                        {
                            //create anchor tag
                            var link = "<a href='" + words[j] + "' target='_blank'>" + words[j] + "</a>";
                            line += link + " ";
                        }
                    }
                    else
                    {
                        line += words[j] + " ";
                    }
                }

                comment += line + "<br>";
            }
            else
            {
                comment += lines[i] + "<br>";
            }
        }

        str = comment;
    }
    
    

    /*for (var i = 0; i < link_matches.length; i++)
    {
        alert(link_matches[i]);
    }

    str = str.replace(/http:\/\/(.)*\s/, "<a href='http://www.youtube.com' target='_blank'>http://www.indiestreetcred.com</a>");

    alert(str);*/

    /*var search_str = str;
    var final_str = "";

    var start_pos = 0;

    str = "";


    //check for hyperlinks
    while (search_str.match(/http:\/\/[\w\.]+/)) 
    {
        var url = search_str.match(/http:\/\/[\w\.]+/) + "";

        final_str += search_str.replace(/http:\/\/[\w\.]+/, "<a href='" + url + "' target='_blank'>" + url + "</a>");

        start_pos += 31 + 2 * url.length;

        alert("start pos: " + new_start);

        search_str = final_str.substr(new_start);

        alert("SS: " + search_str);
    }
    alert(str);*/
    
    return str;
}

function getWindowSize()
{
    var myWidth = 0, myHeight = 0;
    
    if( typeof( window.innerWidth ) == "number" ) 
    {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } 
    else if(d.documentElement && (d.documentElement.clientWidth || d.documentElement.clientHeight)) 
    {
        //IE 6+ in 'standards compliant mode'
        myWidth = d.documentElement.clientWidth;
        myHeight = d.documentElement.clientHeight;
    } 
    else if(d.body && (d.body.clientWidth || d.body.clientHeight)) 
    {
        //IE 4 compatible
        myWidth = d.body.clientWidth;
        myHeight = d.body.clientHeight;
    }
    
    return [myWidth, myHeight];
}

function createCookie(name,value,days) 
{
	if (days) 
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else
	{   
	    var expires = "";
	}
	
	d.cookie = name+"="+value+expires+"; path=/";
}

function removeCookie(name) 
{
	createCookie(name, "", -1);
}

function readCookie(name) 
{
	var nameEQ = name + "=";
	var ca = d.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 getDomain()
{
    //look at the current domain
    if(document.domain == "grant.blacklightnewmedia.com")
    {
        return "grant.blacklightnewmedia.com/sotd";
    }
    else
    {   
        return document.domain;
    }
}

function findPos(obj) 
{
	var curleft = curtop = 0;
	if (obj.offsetParent) 
	{
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		
		while (obj = obj.offsetParent) 
		{
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	
	return [curleft,curtop];
}

function roundAvg(avg)
{
    return Math.round(avg*10)/10;
}

function getAlbumArt(id)
{
    var tr = d.getElementById(id);
    
    if(tr == null)
    {
        return "";
    }
    
    var hiddens = tr.getElementsByTagName("input");
    
    //albumart is the second
    return hiddens[1].value;
}

function getFullAlbumText(id)
{
    var tr = d.getElementById(id);
    
    if(tr == null)
    {
        return "";
    }
    
    var spans = tr.getElementsByTagName("span");
    
    var artist = spans[1].firstChild.nodeValue;
    var album = spans[2].firstChild.nodeValue;
    
    return artist + " - " + album;
}