/*
Purpose:
	Contains javascript functions to do AJAX communication with
	backend ASP.NET web application

Author: Himanshu Patel 
Created: 10/19/06
Modification History:
*/

// ------------------------------------------------------------------------
// globals
// ------------------------------------------------------------------------
var debugVerbose = false;
// ajax object for xmlhttprequest
var ratingsAjax = null;
// add an additional parameter to create unique request to prevent caching
var ratingsAjaxGenerateUniqueUrl = true;
// use asynchronous mode
var ratingsAjaxAsync             = true;
// timeout in ms for the xmlhttprequest
var ratingsAjaxTimeout           = 20000; //20 sec
// url for the ajax request
var ratingsAjaxUrl = "";

if (document.domain == "localhost") 
{   //DEV
    ratingsAjaxUrl = "RateArticle.aspx";
}
else 
{   //PRODUCTION
    ratingsAjaxUrl = "/GeneralContent/Active/ContentRating/RateArticle.aspx";
}

var ratingCookie = "BriefingArticleRating";

// ------------------------------------------------------------------------
// intitialization ???
// ------------------------------------------------------------------------
// create the ajax object
ratingsAjax = new BriefingAjax();
var myid =0;
var ratingDone = 0;

var starImages =  new Array("/Common/Images/investor/RateThisArticle/0star.gif",
                            "/Common/Images/investor/RateThisArticle/1star.gif",
                            "/Common/Images/investor/RateThisArticle/2star.gif",
                            "/Common/Images/investor/RateThisArticle/3star.gif",
                            "/Common/Images/investor/RateThisArticle/4star.gif",
                            "/Common/Images/investor/RateThisArticle/5star.gif");

var starMap = new Array('0,0,0,0',
                        '0,0,30,22',
                        '30,0,60,22',
                        '60,0,87,22',
                        '88,0,117,23',
                        '117,0,150,23');

var savedRatings = new Array();
var changedRatings = new Array();
var starTwinkler = new Array();
var msgTwinkler = new Array();
var isRatingsBarChanged = false;
var delayTime = 500;
var allImages = new Array();
var id = 0;
var rating = 0;
savedRatings[id] = rating;

function preloadRatingImages()
{
	for (i=0; i < preloadRatingImages.length ;i++)
	{
		allImages[i] = new Image();
		allImages[i].src = preloadRatingImages.arguments[i];
	}
}

preloadRatingImages(starImages);

// ------------------------------------------------------------------------
// make the request
// ------------------------------------------------------------------------
function CallRateArticlePage(id, storyId, pageId, productId, ratingValue, actionName, rootPath)
{    
    try
    {
        ratingsAjax.MakeRequest(
            rootPath+ratingsAjaxUrl,      // url
            {StoryId:storyId,PageId:pageId,ProductId:productId,Rating:ratingValue,ActionName:actionName},   // parameters
            ratingsAjaxGenerateUniqueUrl, // generateUniqueUrl
            ratingsAjaxAsync,             // async
            ratingsAjaxTimeout,           // timeout
            HandleAjaxResponse);          // callback for response
    }
    catch (exception)
    {
        window.status = "Exception in MakeAjaxRequest: " + exception.message;
    }
}
// ------------------------------------------------------------------------
// handle the response
// ------------------------------------------------------------------------
function HandleAjaxResponse(xmlDocument)
{
    try
    {
      // make sure there is something to process
      if(xmlDocument != null && xmlDocument.xml != "")
      {
        var averageArticleRatingElement = xmlDocument.getElementsByTagName("AverageArticleRating")[0];
		var averageArticleRating = averageArticleRatingElement.firstChild.nodeValue.toString();
        
        var userRatingElement = xmlDocument.getElementsByTagName("UserRating")[0];        
        var userRating = userRatingElement.firstChild.nodeValue.toString();
        
        document.getElementById("ArticleRatingStars").innerHTML  = '<IMG src=/Common/Images/investor/RateThisArticle/' + userRating + 'star.gif>';                 
        document.getElementById("AverageArticleRating").innerHTML = '&nbsp;&nbsp;Average rating: '+ averageArticleRating;
        ratingDone = 1;
        
        var storyId = document.getElementById("ContentArticleId").value;
        //check for cookie and write it if not present
        var cookieName = ratingCookie + storyId;   
        //check for a ratings cookie
    
        var cookie = ReadCookie(cookieName);
        if (cookie == null) 
        {
            //creating cookie after rating done
            CreateCookie(cookieName, storyId, 16);
            //reload the page
            window.location = window.location + "#RateThisArticle";
            window.location.reload();
        }
      }
      else
      {
        alert("noting in the xml document");
      }
    }
    catch (exception)
    {
        window.status = "Exception in HandleAjaxResponse: " + exception.message;
    }
}

function SwapStars(id, rating)
{
	if (rating == undefined)
	{
		rating = 0;
	}	
	if (ratingDone == 0) {
	    document.images["stars." + id].src = starImages[rating];
	}
}

function SaveStarsAjax(id, pageId, productId, rating, rootPath)
{  	
    //get storyId from element tag
    var storyId = document.getElementById("ContentArticleId").value;
    
	if ((rating==1)||(rating==2)||(rating==3)||(rating==4)||(rating==5))
	{
		savedRatings[id] = rating;
		changedRatings[id] = 1;
		CallRateArticlePage(id, storyId, pageId, productId, rating, "RateArticle", rootPath);
	}
	else
	{
		alert("Rating Value out of the bound, Values can only be 1/2/3/4/5. Current rating value: " + rating);
	}
}

function StarMouseOver(id, rating)
{
	//alert("StarMouseOver:" + id + ":" + rating);
	if (starTwinkler[id] != 0)
	{
		window.clearTimeout(starTwinkler[id]);
		starTwinkler[id] = 0;
	}
	if (msgTwinkler[id] != 0)
	{
		window.clearTimeout(msgTwinkler[id]);
		msgTwinkler[id] = 0;
	}
	SwapStars(id, rating);	
}

function StarMouseOut(id)
{
	//alert("StarMouseOut:" + id);
	starTwinkler[id] = window.setTimeout("SwapStars('"+id+"')", delayTime);	
}

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 = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function ReadCookie(name) {
	var nameEQ = name + "=";
	var ca = document.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 DisplayStarsAjax (id, pageId, productId, rating, rootPath)
{     
    //alert("DisplayStarsAjax:" + id);	        
	var starID = "stars." + id;
	starTwinkler[id] = 0;
	msgTwinkler[id] = 0;
	document.write("<map name='starmap" + id +"'>");
	var i = 0;
	for (i = 1; i < 6; i++) 
	{
	    document.write("<area shape=rect " + 
	    "coords='" + starMap[i] + "' " +
	    "onMouseOver=\"StarMouseOver('" + id + "'," + i + ");\" " +
	    "onMouseOut=\"StarMouseOut('" + id + "');\" " +
	    "onClick=\"SaveStarsAjax('" + id + "', '" + pageId + "', '" + productId + "', " + i + ", '" + rootPath + "');" +
	    "\" >");
	}	
	document.write("</map>");
	document.write("<img vspace=2 src='" + starImages[rating] + "'");
	document.write(" border=0 usemap='#starmap" + id);
	document.write("' id='" + starID + "'>");
	
	var storyId = document.getElementById("ContentArticleId").value;
    //look for ratingCookie + storyId cookie name
    var cookieName = ratingCookie + storyId;
   
    //check for a ratings cookie
    var cookie = ReadCookie(cookieName);
    if (cookie != null) 
    {   
        //getting average only
        CallRateArticlePage(id, storyId, pageId, productId, 5, "GetAverageArticleRating", rootPath);
    }
}

function FeedbackOnThisArticle(rootPath)
{
    var articleId = document.getElementById("ContentArticleId").value;
    var feedbackUrl = rootPath+'/GeneralContent/Active/Feedback/FeedbackPlainInvestor.aspx?SiteName=Investor&ArticleId=' + articleId;    
    window.open(feedbackUrl,'Feedback','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=657,height=480,left=10,top=10');
}

/* END OF SCRIPT */
