var isWorking = 0;  // This is an event handler variable.  It helps account for the delay from Amazon and ensures that a new request won't receive old request results.
var hoverdiv = "";
var hoverlink = "";
var amazonlink = "";
var addMovieLink = "";
var addNetflixLink = "";
var watchNowLink = "";

var hoverobject=0;

function delayawsReq(asid, hoverdivstring, datemovie, addMovieLinkString, addNetflixLinkString, watchNowLinkString, hoverlinkstring, amazonlinkstring, userID) {
    userIDforHover=userID;

    var pattern = /\_.*$/;
    var temp = hoverdivstring.replace(pattern, "");
    addMovieLink = addMovieLinkString;
    addNetflixLink = addNetflixLinkString;
    watchNowLink = watchNowLinkString;
    hoverlink = hoverlinkstring;
    amazonlink = amazonlinkstring;
    hoverobject = document.getElementById(temp);
    var awstimer = awsReq.delay(900, null, [asid, hoverdivstring, datemovie]);
    hoverobject.addEvent('mouseleave', function() {
        if($defined(awstimer))
        {
            $clear(awstimer);
        }
    });
    hoverobject.addEvent('click', function() {
        if($defined(awstimer))
        {
            $clear(awstimer);
        }
    });
}

/***********************************************************************************************************************************************************
* This function manages the hover tooltip.
* It takes in an Amazon product number from the target object, looks up the information from Amazon (via a php script), and updates the Tooltip dynamically.
*
* http.send(null) starts an event that processes in the background while the javascript continues.
* The tooltip is initially set with an "In Progress" type message.
************************************************************************************************************************************************************/

function awsReq(asid, hoverdivstring, datemovie) {    // Added in datemovie so we use our date for the movie, not Amazon's date for the movie.
    trimrelease = datemovie;			    // Added for the same reason as comment for the line above.
    hoverdiv=hoverdivstring;
	if (asid != isWorking)
	{
		isWorking = asid;
        if (http) {
            var awsUrl = "/hover/movie/asin/" + asid;
            if (awsUrl == '999')
            {
                return 'testing...';
            }
            else
            {
                http.open('GET', awsUrl);
                http.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                http.onreadystatechange = handleAWSResponse;
                http.send(null);
                return '';
            }
		}
		else
		{
			return 'testing...';
		}
	}
    return 'Test';
}


/*****************************************************************************************************************************************
* This is function runs in the background. It processes the xml file returned from the php script and forms html to be displayed.
* If a new request hasn't been initiated, it updates the tooltip dynamically with the html formatted from the xml file.
*****************************************************************************************************************************************/

function handleAWSResponse()
{
    if(http.readyState == 4)
    {
            var xmlDocument = http.responseXML;
            if (xmlDocument)
            {
                var formatted_html="";
                var items = xmlDocument.getElementsByTagName('Item');

                for (var i = 0; i < items.length; i++)
                {
                    var child_element = "";
                    var current_asin = "";
                    var mediumimg = "";
                    var title="No title found.";
                    var releasedate = "";
                    var actorindex = 0;
                    var actors = new Array();
                    var creators = [];
                    var creatorindex = 0;
                    var creatorsrole = [];
                    var directors = [];
                    var directorindex = 0;
                    var roleindex = 0;
                    var ean = "None retrieved.";
                    current_asin = "None retrieved.";
                    var formats = [];
                    var formatindex = 0;
                    var isbn = "None retrieved.";
                    var aspectratio = "None retrieved.";
                    var brand = "None retrieved.";
                    var audiencerating = "None retrieved.";
                    var source = [];
                    var sourceindex = 0;
                    var content = [];
                    var contentindex = 0;
                    var smallimg = "/public/images/notfound_small.jpg";

                    //Iterate through child elements until node name = "MediumImage".
                    //Get an array consisting of all the current Item's children.
                    child_elements = items[i].childNodes;
                    for (x = 0; x < child_elements.length; x++)
                    {
                        child_element = child_elements[x].nodeName;

                        switch (child_element)
                        {
                            case "ASIN":
                            {
                                current_asin = child_elements[x].firstChild.nodeValue;
                            }
                            break;
                            case "MediumImage":
                            {
                                parenting = child_elements[x].firstChild;  //  Gets me to "URL" the parenting node for the value we want.
                                mediumimg = parenting.firstChild.nodeValue;
                            }
                            break;
                            case "SmallImage":
                            {
                                parenting = child_elements[x].firstChild;  //  Gets me to "URL" the parenting node for the value we want.
                                smallimg = parenting.firstChild.nodeValue;
                            }
                            break;

                            case "ItemAttributes":
                            {
                                ItemAttributes_children = child_elements[x].childNodes;   // Get all the root children nodes that are subset of ItemAttributes.
                                for (y = 0; y < ItemAttributes_children.length; y++)
                                {
                                    IA_child = ItemAttributes_children[y].nodeName;

                                    switch (IA_child)
                                    {
                                        case "Actor":
                                        {
                                            actors[actorindex] = ItemAttributes_children[y].firstChild.nodeValue;
                                            actorindex++;
                                        }
                                        break;
                                        case "Creator":
                                        {
                                            creators[creatorindex] = ItemAttributes_children[y].firstChild.nodeValue;
                                            creatorindex++;
                                            creatorsrole[roleindex] = ItemAttributes_children[y].getAttribute('Role');
                                            roleindex++;
                                        }
                                        break;
                                        case "Director":
                                        {
                                            directors[directorindex] = ItemAttributes_children[y].firstChild.nodeValue;
                                            directorindex++;
                                        }
                                        break;
                                        case "EAN":
                                        {
                                            EAN=ItemAttributes_children[y].firstChild.nodeValue;
                                        }
                                        break;
                                        case "Format":
                                        {
                                            formats[formatindex] = ItemAttributes_children[y].firstChild.nodeValue;
                                            formatindex++;
                                        }
                                        break;
                                        case "ISBN":
                                        {
                                            isbn = ItemAttributes_children[y].firstChild.nodeValue;
                                        }
                                        break;
                                        case "AspectRatio":
                                        {
                                            aspectratio = ItemAttributes_children[y].firstChild.nodeValue;
                                        }
                                        break;
                                        case "AudienceRating":
                                        {
                                            audiencerating = ItemAttributes_children[y].firstChild.nodeValue;
                                        }
                                        break;
                                        case "Binding":
                                        {
                                            binding = ItemAttributes_children[y].firstChild.nodeValue;
                                        }
                                        break;
                                        case "Brand":
                                        {
                                            brand = ItemAttributes_children[y].firstChild.nodeValue;
                                        }
                                        break;
                                        case "Title":
                                        {
                                            temptitle = ItemAttributes_children[y].firstChild.nodeValue;
                                            title=temptitle.replace(/\s\(.*\)/g, "")
                                        }
                                        break;
                                    }
                                }
                            }
                            break;
                            case "EditorialReviews":
                            {
                                EditorialReviews_children = child_elements[x].childNodes;   // Get all the root children nodes that are subset of EditorialReviews.
                                for (z = 0; z < EditorialReviews_children.length; z++)
                                {
                                    ER_child = EditorialReviews_children[z].nodeName;  // This is EditorialReview's name.
                                    if (ER_child == "EditorialReview")
                                    {

                                        ER_children = EditorialReviews_children[z].childNodes;  // Get the children of Editorial Review.
                                        for (s = 0; s < ER_children.length; s++)
                                        {
                                            ER_children_node = ER_children[s].nodeName;
                                            switch (ER_children_node)
                                            {
                                                case "Source":
                                                {
                                                    source[sourceindex] = ER_children[s].firstChild.nodeValue;
                                                    sourceindex++;
                                                }
                                                break;
                                                case "Content":
                                                {
                                                    content[contentindex] = ER_children[s].firstChild.nodeValue;
                                                    contentindex++;
                                                }
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                            break;
                        }
                    }

                    if (current_asin == isWorking)  // start of check.
                    {
                        //Output completed tooltip... I.e. Build the html for the hover.
                        if (smallimg == "")
                        {
                            formatted_html += '<p><img src="./images/notfound.jpg" alt = "'
                                + title + '" hspace="4" vspace="4" border="0" align="left" /><strong>'
                                + title + '</strong> ('+trimrelease+') ';
                        }
                        else
                        {
                            formatted_html += '<p><img src="' + smallimg + '" alt = "' + title
                                + '" hspace="4" vspace="4" border="0" align="left" /><strong>'
                                + title + '</strong> ('+trimrelease+') ';
                        }
                        var numcharstograb = 0;
                        //  Begin modification area for hover fixes
                        var pattern = 0;
                        if (($defined(content[0])) && (content[0].length != 0))
                        {
                            pattern = /<br><b>Genre:.*$/;
                            content[0] = content[0].replace(pattern, "");
                            pattern = /Studio:.*$/;
                            content[0] = content[0].replace(pattern, "");
                            pattern = /<b>DVD Features:.*$/;
                            content[0] = content[0].replace(pattern, "");
                            pattern = /No Track Information Available.*$/;
                            content[0] = content[0].replace(pattern, "");
                            pattern = /<b>Media Type:.*$/;
                            content[0] = content[0].replace(pattern, "");
                            pattern = /<br>/g;
                            content[0] = content[0].replace(pattern, " ");
                            pattern = /<p>/g;
                            content[0] = content[0].replace(pattern, " ");
                            pattern = /<P>/g;
                            content[0] = content[0].replace(pattern, " ");
                            /* ttodd 20091015 begin Hover and TellmeMore Fix */
                            pattern = /<i>/g;
                            content[0] = content[0].replace(pattern, "");
                            pattern = /<\/i>/g;
                            pattern = /<I>/g;
                            content[0] = content[0].replace(pattern, "");
                            pattern = /<\/I>/g;
                            content[0] = content[0].replace(pattern, "");
                            pattern = /0000000000000000000000000000000000000000000000000000000000000000/g;
                            content[0] = content[0].replace(pattern, "");
                            numcharstograb=321 - title.length;
                            content[0] = content[0].substring(0,numcharstograb);
                            if (content[0].length >= 95)
                            {
                                if (content[0].length >= (319 - title.length))
                                {
                                    formatted_html += content[0] + '...<br />';
                                }
                                else
                                {
                                    if (content[0].length < 15)
                                    {
                                        formatted_html += '<br />' + content[0] + '<br />';
                                    }
                                    else
                                    {
                                        formatted_html += content[0] + '<br />';
                                    }
                                /* ttodd 20091015 end Hover and TellmeMore Fix */
                                }
                            }
                            else
                            {
                                if (($defined(content[1])) && (content[1].length != 0))
                                {
                                    pattern = /Genre:.*$/;
                                    content[1] = content[1].replace(pattern, "");

                                    pattern = /Studio:.*$/;
                                    content[1] = content[1].replace(pattern, "");
                                    pattern = /<b>DVD Features:.*$/;
                                    content[1] = content[1].replace(pattern, "");
                                    pattern = /No Track Information Available.*$/;
                                    content[1] = content[1].replace(pattern, "");
                                    pattern = /<b>Media Type:.*$/;
                                    content[1] = content[1].replace(pattern, "");
                                    pattern = /<p>/g;
                                    content[1] = content[1].replace(pattern, " ");
                                    pattern = /<P>/g;
                                    content[1] = content[1].replace(pattern, " ");
                                    /* ttodd 20091015 begin Hover and TellmeMore Fix */
                                    pattern = /<i>/g;
                                    content[1] = content[1].replace(pattern, "");
                                    pattern = /<\/i>/g;
                                    content[1] = content[1].replace(pattern, "");
                                    pattern = /<I>/g;
                                    content[1] = content[1].replace(pattern, "");
                                    pattern = /<\/I>/g;
                                    content[1] = content[1].replace(pattern, "");
                                    pattern = /<br>/g;
                                    content[1] = content[1].replace(pattern, " ");
                                    pattern = /0000000000000000000000000000000000000000000000000000000000000000/g;
                                    content[1] = content[1].replace(pattern, "");
                                    numcharstograb=321 - title.length;
                                    content[1] = content[1].substring(0,numcharstograb);

                                    if (content[1].length >= (319 - title.length))
                                    {
                                        formatted_html += content[1] + '...<br />';
                                    }
                                    else
                                    {
                                        if (content[1].length < 15)
                                        {
                                            formatted_html += '<br />' + content[1] + '<br />';
                                        }
                                        else
                                        {
                                            formatted_html += content[1] + '<br />';
                                        }
                                        /* ttodd 20091015 end Hover and TellmeMore Fix */
                                    }
                                }
                            }
                        }
                        else
                        {
                            formatted_html += '<br /><br />';
                        }

                        actors_html = "";
                        if (actors.length != 0)
                        {
                            formatted_html += '<strong style="padding-left:10px">Starring:</strong> ';
                            i = 0;
                            for(i = 0; i < actors.length; i++)
                            {
                                if (i != (actors.length - 1))
                                {
                                    actors_html += actors[i] + ', ';
                                }
                                else
                                {
                                    actors_html += actors[i];
                                }
                            }
                            numcharsinactors = 157;
                            actors_html = actors_html.substring(0, numcharsinactors);
                            actors_html += '...<br />';
                            formatted_html += actors_html;
                        }

                        if (directors.length != 0)
                        {
                            formatted_html += '<strong style="padding-left:10px">Director: </strong>';
                            i = 0;
                            for(i = 0; i < directors.length; i++)
                            {
                                if (i != (directors.length - 1))
                                {
                                    formatted_html += directors[i] + ', ';
                                }
                                else
                                {
                                    formatted_html += directors[i];
                                }
                            }
                        }

                        regpattern = new RegExp (".*?index\/id\/", "g");
                        hoverMovieID = hoverlink.replace(regpattern ,"");
                        doesMovieExist = 0;
                        width = 107;
                        add2myMoviesHoverButtonID = hoverMovieID + 'add2myMoviesHover';
                        addNetflixHoverButtonID = hoverMovieID + 'addNetflixHover';

                        var req = new Request({
                            method: 'get',
                            url: '/mymovies/checkvisible/userID/' + userIDforHover + '/movieID/' + hoverMovieID,
                            onRequest: function() { /*alert('Request made. Please wait...'); */},
                            onComplete: function(response) {
                                formatted_html += '</p>' + '<ul>';
                                if (addMovieLink == "")
                                {
                                    formatted_html += '<li><a href="#">In myMovies</a></li>';
                                }
                                else
                                {
                                    formatted_html += '<li><a href="http://' + addMovieLink + '">myMovies - add</a></li>';
                                }
                                // if the url indicates that netflix should be searched, set up the display text to indicate search for netflix.
                                // otherwise set up the display text to add to netflix.
                                netflixSearch = addNetflixLink.indexOf("/Search?v1=");
                                if (netflixSearch > 0)
                                {
                                    formatted_html += '<li><a href="http://' + addNetflixLink + '" target=\'_blank\'">Search Netflix</a></li>';
                                }
                                else
                                {
                                    var aPosition = addNetflixLink.indexOf("/InQ");
                                    if (aPosition > 0)
                                    {
                                        addNetflixLink = addNetflixLink.replace("/InQ", "")
                                        formatted_html += '<li><a href="http://' + addNetflixLink + '">In Netflix Q</a></li>';
                                    }
                                    else
                                    {
                                        formatted_html += '<li><a href="http://' + addNetflixLink + '">Netflix - add</a></li>';
                                    }
                                }
                                if (watchNowLink != "")
                                {
                                    formatted_html += '<li><a href="http://' + watchNowLink + '">Watch Now!</a></li>';
                                }
                                formatted_html += '<li><a href="' + amazonlink + '" target="_blank">Buy it at Amazon</a></li>' 
                                    + '<li><a href="http://' + hoverlink + '">Tell me more</a></li></ul>';

                                document.getElementById(hoverdiv).innerHTML = formatted_html;

                                $$('.add2myMoviesHoverButton').addEvent('click', function(event) {
                                    event.stop();
                                    parsedMovieID = this.id.replace("add2myMoviesHover", "");

                                //Check the value of the class, depending on value, make server request or follow link.
                                    buttonclass=this.get('class');
                                    if (buttonclass == 'add2myMoviesHoverButton')
                                    {
                                        //make the ajax call
                                        var req = new Request({
                                            method: 'get',
                                            url: '/mymovies/add/userID/' + userIDforHover + '/movieID/' + parsedMovieID,
                                            onRequest: function() { /* alert('Request made. Please wait...'); */ },
                                            onComplete: function(response) {
                                                hoverID = response + 'add2myMoviesHover';
                                                $(hoverID).set('class', 'inmyMoviesHoverButton');
                                                $(hoverID).set('value', 'In myMovies');

                                                rightmain = response + 'add2myMovies';
                                                if ($(rightmain))
                                                {
                                                    $(rightmain).set('class', 'inmyMoviesButton');
                                                    $(rightmain).set('value', 'In myMovies');
                                                }

                                                //undoRemove=$(response).dispose();
                                                //alert('Response: ' + response);
                                            }
                                        }).send();
                                    }
                                });
                                isWorking="1";
                            }
                        }).send();
                    }  // end of check to see if a new request has started.
                }
            }
    }
}


/*************************************************************
*  Primary function which creates the initial Request object
*************************************************************/

function createRequestObject() {
	var ro;
	var browser = navigator.appName;
	if (browser == "Microsoft Internet Explorer") {
		ro = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		ro = new XMLHttpRequest();
	}
	return ro;
}

var http = createRequestObject();


