﻿if (typeof(enableConsoleLog) == "undefined")
    var enableConsoleLog = false;

var PLUCKHotOrNot = PLUCKHotOrNot ? PLUCKHotOrNot : function() {
  var private = {
    title: "PLUCK HotOrNot Implementation",         // only used by debug to show the object title
	//serverUrl: "http://sitelifestage.en.batanga.com/ver1.0/Direct/Process?sid=sitelifestage.en.batanga.com",
	serverUrl: serverUrlEN,                            // serverUrl, this could be defined in the head, or 
													// defined here.
	section: "HotOrNot",  // section set for HotOrNot Photos
													// section defaults to HotOrNot, or can be overridden
													// by passing in the TextIdentifier to GetItStarted
													// along with the gallery identifier.
	personahome: "http://www.batanga.com/community/persona.aspx",
													// the personahome is used to build the links of the author
													// of comments and photos.
    //sitelifeServer : "sitelifestage.en.batanga.com",// sitelifeserver to use to send emails													
    sitelifeServer : sitelifeServer,                // sitelifeserver to use to send emails. Get that value from the global variable.													
	UID: "userid",									// the "userid" that us used on the query string
	currentPage: 1,									// current page we have retrieved from pluck
	currentImageInBatch: 1,							// image counter in the array of images (photo)
	AbuseThreshhold:3,								// Abuse Threshold where photos and comments above this are not shown
	myPhotoArray: new Array(),						// Array of images retuned from pluck built 10 at a time
	articleFound: false,							// used to Flag the UpdateArticleAction that needs to happen only once per image when creating the rating
	galleryKey: "",                                 // current Gallery Key that we are getting information from
	galleryTitle: "",								// Gallery Tile
	currentCommentPage: 1,                          // current page of comments (page counter - used for getting next pages of comments)
	redirectUrl : null,                             //will contain the url to redirec to if called from voting widget
	debug: function(str) {							// debugging
	        if(enableConsoleLog)
			    console.log(str);
	        //alert(str);
	},
	debugobj: function(obj) {						// debugginig
	        if(enableConsoleLog)
			    console.dir(obj);
	},
	// get Gallery based on Key and the photo batch that are
	// associated with that key, pass the reponses to renderGallery
	// this might not be used at all.
	getGallery: function(key) {
		private.debug("getting stuff from pluck");
        var requestBatch = new RequestBatch();
        var galleryKey = new GalleryKey(key);
        requestBatch.AddToRequest(galleryKey);
		var photoPage = new PhotoPage(galleryKey,1,private.currentPage,"TimeStampDescending");
		requestBatch.AddToRequest(photoPage);
        requestBatch.BeginRequest(private.serverUrl, private.renderGallery);

	},
	// override the hard-coded Section Tag so that HOTorNot can be HitMiss and we
	// can discover the hotest based on section and the articleIds are created 
	// accordingly
	setSection: function(sectionTag) {
		private.section = sectionTag;
	},
	// get the first image
	// this is used when the page is loaded for the first time
	// that gets the first page of the gallery photo page 
	// and displays the most recent photo passing the results to 
	// renderGallery
	getFirstImage: function(key) {
		private.galleryKey = key;
		private.debug("getting First Image");		
        var requestBatch = new RequestBatch();
        var galleryKey = new GalleryKey(key);
        requestBatch.AddToRequest(galleryKey);
		var photoPage = new PhotoPage(galleryKey,10,private.currentPage,"TimeStampDescending");
		requestBatch.AddToRequest(photoPage);
        requestBatch.BeginRequest(private.serverUrl, private.renderGallery);
	},	
	// build a unique idnetifier for the article
	// that we are associating the comments on, based on the
	// photoKey and the 'section' value.
	HotOrNotArticleKey: function(key){
		return private.section+key;
	},
	// get a specific image, based on the
	// index into the array myPhotoArray.
	// this is called from the next/previous in the public
	// display section of the code
	getImage: function(imageIndex) {
		// this gets one batch of image data,
		// article that contains the rating
		// comments that go with the image
		// and incrients the counter and sets the max number of images.
		if (imageIndex==private.myPhotoArray.length)
		    imageIndex = 0;
		private.debug("getting Image Data :"+imageIndex);
        var requestBatch = new RequestBatch();
		// get image data summary articleId
        var articleKey = new ArticleKey(private.HotOrNotArticleKey(private.myPhotoArray[imageIndex].PhotoKey.Key));
        requestBatch.AddToRequest(articleKey);
		requestBatch.AddToRequest(new PhotoKey (private.myPhotoArray[imageIndex].PhotoKey.Key));
		requestBatch.AddToRequest(new CommentPage (articleKey,10,private.currentCommentPage,"TimeStampDescending"));
        requestBatch.BeginRequest(private.serverUrl, private.renderImageData);
		// math IS WRONG
		// need to check against array length if are near the
		// end of the array and 10* page is less than total images
		// get next page.
		// this will probably need to take into account
		// images that are blocked, and it currently looks like it might not work
		// when images are 'blocked' as the count might not get the next page as desired.
		//if (((imageIndex+1) / 10) == private.currentPage) {
		//Anand: use the length myPhotoArray since that might have one 'added' via voting widget into it...
		//if (((imageIndex+1) / private.myPhotoArray.length) == private.currentPage) {
		if (((imageIndex+1) / private.myPhotoArray.length) == 1) {
		    private.debug ("need new batch");
			private.currentPage = private.currentPage + 1;
			var requestBatch2 = new RequestBatch();
			var photoPage = new PhotoPage(new GalleryKey(private.galleryKey),10,private.currentPage,"TimeStampDescending");
			requestBatch2.AddToRequest(photoPage);
	        requestBatch2.BeginRequest(private.serverUrl, private.renderImageData);
			private.debugobj(requestBatch2);
			}

		private.currentImageInBatch = imageIndex;
		private.debugobj(requestBatch);
		public.showCommentCounts("0");
	},
	// process the results from pluck.
	// loop through to find our object types and pass the data
	// to private handlers to decide what to do/how to to display
	// normally passing the data to the public functions for presentation
	renderGallery: function(responseBatch) {
		private.debug("renderGallery");
		private.debugobj(responseBatch);
		if (responseBatch.Messages[0].Message = 'ok') {
			// success from pluck, lets process the data
	        for (var i = 0; i < responseBatch.Responses.length; i++) {
				var response = responseBatch.Responses[i];

				if (response.Gallery != null) {
					if (private.galleryHandler != null) {
						private.galleryHandler(response.Gallery);
					}
					else {
						private.debug("No galleryHandler defined and response " + i + " is a DiscoverArticlesAction");
					}
				}
				else {
					if (response.PhotoPage != null) {
						if (private.photoPageHandler != null) {
							private.photoPageHandler(response.PhotoPage);
						}
						else {
							private.debug("No galleryHandler defined and response " + i + " is an Article");
						}
					}
				}
			}
		}
		// done getting the basics
		// now lets get the details.
		//private.getImage(0);
		
		private.debug("plckPhotoId = " + plckPhotoId);
		private.debug("myPhotoArray = ");
		private.debugobj(private.myPhotoArray);
		
		if(plckPhotoId != null && plckPhotoId.length > 0)
		{
		    if(private.myPhotoArray[0].PhotoKey.Key == plckPhotoId && plckPhotoVoted == "1")
		        private.getImage(1);    
		    else
		        private.getImage(0);    
		        
		        /*
		    //skip the first images where its the the voted one...
		    for(i = 0; i < private.myPhotoArray.length; i++)
		        if(myPhotoArray[i].PhotoKey.Key != plckPhotoId) break;
		        
		    private.getImage(i);    
		    //plckPhotoId = null;     //set it back to null
		    */
		}
		else
		{
		    private.getImage(0);
		}
		
	},
	// could probably be combined with the above renderGallery as they
	// pretty much do the exact same thing, but renderImageData takes
	// a couple other data types into account.
	renderImageData: function(responseBatch) {
		private.debug("renderImageData");
		private.debugobj(responseBatch);
		private.articleFound = false;
		//public.showCommentCounts("0");
		if (responseBatch.Messages[0].Message = 'ok') {
			// success from pluck, lets process the data
	        for (var i = 0; i < responseBatch.Responses.length; i++) {
	            var response = responseBatch.Responses[i];

		        if (response.Gallery != null) {
	                if (private.galleryHandler != null) {
	                    private.galleryHandler(response.Gallery);
	                } else {
	                    private.debug("No galleryHandler defined and response " + i + " is a DiscoverArticlesAction");
	                }
	            } else if (response.Photo != null) {
	                if (public.photoHandler != null) {
	                    public.photoHandler (response.Photo);
	                } else {
	                    private.debug("No photoHandler defined and response " + i + " is an Photo");
	                }
	            } else if (response.Article != null) {
					private.articleFound = true; // set this so we only run updateArticleAction once
	                if (private.articleHandler != null) {
	                    private.articleHandler(response.Article);
	                } else {
	                    private.debug("No articleHandler defined and response " + i + " is an Article");
	                }
	            } else if (response.CommentPage != null) {
	                if (private.commentsPageHandler != null) {
	                    private.commentsPageHandler(response.CommentPage);
	                } else {
	                    private.debug("No commentsPageHandler defined and response " + i + " is a CommentPage");
	                }
	            } else if (response.PhotoPage != null) {
	                if (private.photoPageHandler != null) {
	                    private.photoPageHandler(response.PhotoPage);
	                } else {
	                    private.debug("No photoPageHandler defined and response " + i + " is a PhotoPage");
	                }
	            }
	        }
		}
	},
	// pass the gallery information to the public function to convert to HTML
	galleryHandler:function(gallery){
		private.debug('galleryHandler');
		private.debugobj(gallery);
		private.galleryTitle=gallery.Title;
	},
	// pass the article information to the public function to convert to HTML
	articleHandler:function(article){
		private.debug('articleHandler');
		private.debugobj(article);
		// show the comment count at the top of the comment area.
		public.showCommentCounts(article.Comments.NumberOfComments);
	},
	// pass the comments information to the public function to convert to HTML
	commentsPageHandler:function(commentPage){
		private.debug('commentsPageHandler');
		private.debugobj(commentPage);
		public.showComments(commentPage.Comments,commentPage.NumberOfComments,commentPage.OnPage);
	},
	insertPhotoAsFirst:function(responseBatch)
	{
	    private.debug('insertPhotoAsFirst');
		private.debugobj(responseBatch);
		if (responseBatch.Messages[0].Message == 'ok') {
		    private.myPhotoArray[private.myPhotoArray.length] = responseBatch.Responses[0].Photo;
		}
		private.debug('myPhotoArray');
		private.debugobj(private.myPhotoArray);
		
		private.getFirstImage(private.galleryKey);
		
	},
	widgetPhotoHandler:function(key)
	{
	    private.galleryKey = key;
	    private.debug('widgetPhotoHandler');
	    private.debug('plckPhotoVoted = ' + plckPhotoVoted + ", plckPhotoId = " + plckPhotoId);
	    if(plckPhotoVoted == "0")
	    {
	        var requestBatch2 = new RequestBatch();
		    requestBatch2.AddToRequest(new PhotoKey(plckPhotoId));
            requestBatch2.BeginRequest(private.serverUrl, private.insertPhotoAsFirst);
	    }
	    else
	    {		    
		    var key = plckPhotoId;
		    var requestBatch = new RequestBatch();
    		
		    requestBatch.AddToRequest(new ArticleKey(private.HotOrNotArticleKey(key)));
		    requestBatch.AddToRequest(new PhotoKey(key));
            requestBatch.BeginRequest(private.serverUrl, private.renderRating);
            
            private.getFirstImage(private.galleryKey);
        }
	},
	// build up our photo array of images that we'll keep around to go quickly 
	// between next/prev and hot/not
	photoPageHandler:function(photoPage){
		private.debug('photoPageHandler');
		private.debugobj(photoPage);
		private.debug('private.myPhotoArray.length = ' + private.myPhotoArray.length);
		
		// build a photo array
		for (var c = 0; c < photoPage.Photos.length; c++) {
			//private.debug("building : "+c);
			// check the photos and make sure they pass the abuse checks
			// before building our photo array out of the
			// the first batch of images.
			if ((photoPage.Photos[c].Author.IsBlocked == "False") && plckPhotoId != photoPage.Photos[c].PhotoKey.Key &&
			(parseInt(photoPage.Photos[c].AbuseReportCount) < private.AbuseThreshhold) /*&&
			(private.myPhotoArray.length < 10)*/) {
				private.myPhotoArray[private.myPhotoArray.length] = photoPage.Photos[c];
			}
			else
				if ((photoPage.Photos[c].Author.IsBlocked == "True") && plckPhotoId != photoPage.Photos[c].PhotoKey.Key &&
				// if this is a bozo'd user, show his comments
				(parseInt(photoPage.Photos[c].AbuseReportCount) < private.AbuseThreshhold) &&
				(photoPage.Photos[c].Author.UserKey.Key == this.User.UserKey.Key) /*&&
				(private.myPhotoArray.length < 10)*/) {
					private.myPhotoArray[private.myPhotoArray.length] = photoPage.Photos[c];
				}
		}
		
		private.debug('end of loop, private.myPhotoArray.length = ' + private.myPhotoArray.length);		
		private.debugobj(private.myPhotoArray);
		// we have processed a page of photos, and built our array of approved photos.
		// need to add the 'isPending' check above too and verify the
		// bozo feature will work.
	},
	// vote functionality:
	// since we are using a Rating here, vote 1 = NOT vote 5 = HOT, basically
	// send a rating to pluck, assigned to the article that identifies the image
	// and the same article that the comments about the image are attached.
	vote:function(key,rating,redirectUrl){
	    private.redirectUrl = redirectUrl;
		private.debug("vote. key = " + key + ", rating = " + rating + ", redirectUrl = " + redirectUrl);
		
        var requestBatch = new RequestBatch();
		// get image data summary articleId
		// if we didn't find the article information,
		// we need to set the meta data here
		var articleKey = new ArticleKey(private.HotOrNotArticleKey(key));
		if(!private.articleFound){
			private.debug("Running Update Article Action");
			//requestBatch.AddToRequest(new UpdateArticleAction(articleKey,document.location.href,document.title,private.section,null));
			 requestBatch.AddToRequest(new UpdateArticleAction(articleKey,document.location.href,document.title, new Section(private.section),null));
		}
		// rate the photo /article
        requestBatch.AddToRequest(new RateAction(articleKey,rating));
		// ask for the article back, so we can draw the screen
        requestBatch.AddToRequest(articleKey);
		// ask for the image back, even tho we have it to make
		// drawing the image & data easier.
        requestBatch.AddToRequest(new PhotoKey(key));
        
        //if there is redirecturl passed then after voting redirect user to that url. otherwise use default pluck implementation...
        if(redirectUrl != null)    
            requestBatch.BeginRequest(private.serverUrl, private.handleVotingWidget);
        else
            requestBatch.BeginRequest(private.serverUrl, private.renderRating);
	    private.debugobj(requestBatch);
	},
	// return the persona link, since this is used many places the function
	// returns the string based on the private.personahome class member
	personaLink:function(userId){
		var link = private.personahome+"?"+private.UID+"="+userId+"&plckPersonaPage=PersonaHome";
		return link;
	},
	handleVotingWidget:function(responseBatch){		
		private.debug('handleVotingWidget: should redirect to: ' + private.redirectUrl);
		private.debugobj(responseBatch);		
		
		if (responseBatch.Messages[0].Message = 'ok') {		  
		    window.location.href = private.redirectUrl;
		    
		}
	},
	// calculate the values for the HOT or NOT from the rating
	// and pass the calculated values to the public functions for display
	renderRating:function(responseBatch){
		// not sure we need to handle this
		private.debug("renderRating");
		private.debugobj(responseBatch);
		var prevImageHref="";
		var prevAverageRating=0.0;
		var prevNumberOfRatings=0;
		if (responseBatch.Messages[0].Message = 'ok') {		    
			// success from pluck, lets process the data
	        for (var i = 0; i < responseBatch.Responses.length; i++) {
	            var response = responseBatch.Responses[i];

		        if (response.Photo != null) {
					// pull small image from response
					prevImageHref = response.Photo.Image.Small;
	                }
	            else if (response.Article != null) {
					prevAverageRating = parseFloat(response.Article.Ratings.AverageRating);
					prevNumberOfRatings = parseInt(response.Article.Ratings.NumberOfRatings);
	            }
	        }
		}
		var pctHot=0;
		var pctNot=0;
		if(prevNumberOfRatings > 0) {
		   pctHot = Math.round(((Math.round((prevAverageRating/5)*prevNumberOfRatings))/prevNumberOfRatings)*100);
		   pctNot = Math.round(((Math.round(prevNumberOfRatings-((prevAverageRating/5)*prevNumberOfRatings))/prevNumberOfRatings))*100);
		}
		public.previousRated(prevImageHref,pctHot,pctNot);
	},
	// post a comment about the image
	// pretty straight forward DAAPI comment submission 
	// notice that the articleKey is geneated based on the currentPhoto and section
	postComment:function(commentText) {
		// daapi comment on key
       	var articleKey = new ArticleKey(private.HotOrNotArticleKey(private.myPhotoArray[private.currentImageInBatch].PhotoKey.Key));
        var pageUrl = document.location.href;
        var pageTitle = document.title;

        // create and send request
        var requestBatch = new RequestBatch();
        var commentAction = new CommentAction(articleKey, pageUrl, pageTitle, commentText);
        requestBatch.AddToRequest(commentAction);
        requestBatch.BeginRequest(private.serverUrl, private.renderCommentPost);
		private.debug("here :" + private.currentImageInBatch);
		private.debug(private.HotOrNotArticleKey(private.myPhotoArray[private.currentImageInBatch].PhotoKey.Key));
	},
	// show the results of the comment posting
	// here we'll normally see 'ok' but sometimes you'll see the 
	// rapid posting warning, or the 'word filter' message when
	// bad words are used.  The results are passed to the presentation
	// to either display or hide the yahoo popup for comment entry.
	renderCommentPost:function(responseBatch){
		// need to handle this
		// check repsonse for success or dirty words.
		private.debug("renderCommentPost");
		private.debugobj(responseBatch);
		private.debug(responseBatch.Messages[0].Message);
		//postEditor.submit();
		public.postCommentResult(responseBatch.Messages[0].Message);
	},
	// reloads the comments for the given image, this is called if the
	// results of the renderCommentPost are sucessful so that the instant
	// gratification of seeing you comment on the page is done.
	reloadComments:function() {
		private.getImage(private.currentImageInBatch);
	},
	// go back to pluck and get the next or previous page of comments
	// get the next page of comments, this is called from the comment pageination
	// links when there are more than 10 comments per image
	commentsPagination:function(page) {
		private.debug("commentsPagination");
	    var requestBatch = new RequestBatch();
	    var articleKey = new ArticleKey(private.HotOrNotArticleKey(private.myPhotoArray[private.currentImageInBatch].PhotoKey.Key));
		requestBatch.AddToRequest(articleKey);
		requestBatch.AddToRequest(new CommentPage (articleKey,10,page,"TimeStampDescending"));
		private.currentCommentPage = page;
		private.debug(requestBatch);
		requestBatch.BeginRequest(private.serverUrl, private.renderImageData);
	},
	// since I used DAAPI to upload the photo, in one example and javascript in the other
	// the dappi version needed to have the facilities to update the photo information
	// this uses the modalbox to capture the data, then send to pluck
	// the photoKey is returned from the form post and used to assign
	// the metadata on the image.
	updatePhotoAction:function(photoKey,title,description,tags,section) {
	    private.debug("updatePhotoAction");
	    var update = new UpdatePhotoAction(
            new PhotoKey(photoKey), 
            title, 
            description, 
            tags,
			new Section(section));
        var requestBatch = new RequestBatch();
        requestBatch.AddToRequest(update);
        requestBatch.BeginRequest(private.serverUrl, private.updatePhotoCallBack);
    },
    // the results are normally  'ok' but just incase the image is too large, 
    // too fast of posting etc, the response is sent to the public methods to 
    // close the modalbox.
    // we probably should refresh the image list here and get the first
    // image in the gallery so that the user gets instant gratification
    updatePhotoCallBack:function(responseBatch) {
    	private.debug("updatePhotoCallBack");
    	private.debugobj(responseBatch);
    	public.updatePhotoActionSuccess(responseBatch.Messages[0]);
    },
    reloadHotOrNot:function() {
		private.currentPage=1;						// current page we have retrieved from pluck
	    private.currentImageInBatch=1;				// image counter in the array of images (photo)
	    private.myPhotoArray=[];					// Array of images retuned from pluck built 10 at a time
		private.currentCommentPage;1;               // current page of comments (page counter - used for getting next pages of comments)
		private.getFirstImage(private.galleryKey);  // reload the gallery
    }	
  };

  // public methods on PLUCKHotOrNot are mainly used for
  // manipluating the data and creating the HTML that will be added on the screen.
  // sort of a small seperation between data and presentation, but the two are
  // very closely connected.
  var public = {
    // nothing really just used for debuging when the object is created.
    getTitle: function() {
      return private.title;
    },
    // gets the specified gallery of information from pluck
    // might be left over from inital coding
	getGallery: function(key) {
		private.getGallery(key);
	},
	// main function to get things going.
	// takes the galleryKey and optionally the textIdentifier
	// the textIdentifier becomes the section and is used
	// to tag the images and articles about those sections
	getItStarted: function(key,textIdentifier) {
		if (textIdentifier)
		   private.setSection(textIdentifier);
		
		if(plckPhotoId != null && plckPhotoId.length > 0)
		{
		    private.widgetPhotoHandler(key);
		}
		else
		{
		    private.getFirstImage(key);
		}
		
		//anand: uploadPhotoForm is not used to upload photos; hence the following two lines are commented.
		//uploadPhotoForm.galleryKey.value = key;
		//uploadPhotoForm.plckGalleryID.value = key;
	},
	// get the next image without voting
	next: function(imageIndex) {
	    private.getImage(imageIndex+1);
	},
	// get the previous image without voting
	previous: function(imageIndex) {
	    private.getImage(imageIndex);
	},
	// vote HOT or in favor of this particular image
	// the current imageIndex is the index into the
	// array of photos which will be incrimented to
	// get the next image in the array
	voteHot: function(imageKey,imageIndex){
	    //check to see if the user has logged in.     
        if(false) //(!IsUserLoggedIn())
        {
            showLoginDialog();            
            return false;
        }
		private.debug("voteHot : "+imageKey);				
		// send rating to pluck & load next image and comments
		// load next image into page.		
		private.vote(imageKey,5);
		//private.debug("voteHot : getImage call is disabled for test");
		private.getImage(imageIndex+1);
		try { batangaReloadAds(); } catch(eRAds) {}
	},
	// vote NOT or in favor of this particular image
	// the current imageIndex is the index into the
	// array of photos which will be incrimented to
	// get the next image in the array
	voteNot: function(imageKey,imageIndex){
	    //check to see if the user has logged in.     
        if(false) //(!IsUserLoggedIn())
        {
            showLoginDialog();            
            return false;
        }
		private.debug("voteNot : "+imageKey);
		// send rating to pluck & load next image and comments
		// load next image into page.
		private.vote(imageKey,1);
		private.getImage(imageIndex+1);
        try { batangaReloadAds(); } catch(eRAds) {}
	},
	voteHotFromWidget: function(imageKey, redirectUrl){
	    private.debug("voteHotFromWidget : "+imageKey + ", redirectUrl = " + redirectUrl);						
	    public.voteFromWidget(imageKey, 5, redirectUrl);
	},
	voteNotFromWidget: function(imageKey, redirectUrl){
	    private.debug("voteNotFromWidget : "+imageKey + ", redirectUrl = " + redirectUrl);						
	    public.voteFromWidget(imageKey, 1, redirectUrl);
	},
	voteFromWidget: function(imageKey, rating, redirectUrl){
	    //check to see if the user has logged in.     
        if(false) //(!IsUserLoggedIn())
        {
            showLoginDialog();            
            return false;
        }
		private.debug("voteFromWidget : "+imageKey + ", rating = " + rating + ", redirectUrl = " + redirectUrl);						
		private.vote(imageKey, rating, redirectUrl);		
	},
	// this function formats an email request and uses the pluck sitelife widgets to make it work
	// these are what the links look like
	// 	<a onclick="window.open('http://sitelifeapi.pluck.com/ver1.0/Email/SendLinkDialog?plckObjectType=Gallery&amp;plckObjectKey=0&amp;plckLink=' + gSiteLife.EscapeValue(window.location.href) + '&amp;plckSubject=Reader\'s+Excellent+Travel+Photos&amp;sid=', 'Email', 'width=500,height=500,scrollbars=yes'); return false;" class="SiteLife_EmailThis" href="#">Email this gallery</a>
	//  <a onclick="window.open('http://sitelifeapi.pluck.com/ver1.0/Email/SendLinkDialog?plckObjectType=  Photo&amp;plckObjectKey=110b63c5-d2be-47c0-9d04-7b012e841582&amp;plckLink=' + gSiteLife.EscapeValue(window.location.href) + '&amp;plckSubject=car&amp;sid=', 'Email', 'width=500,height=500,scrollbars=yes'); return false;" class="SiteLife_EmailThis" href="#none">Email this photo</a>
	// type = "Photo or Gallery"
	// caption = What the link says
	// key = item being emailed
	// subject = subject of the email		
	emailThis:function(type,caption,key, subject) {
		var html = "<a onclick=window.open('http://";
		    html += private.sitelifeServer;
		    html += "/ver1.0/Email/SendLinkDialog?plckObjectType=";
		    html += type;
		    html += "&amp;plckObjectKey=";
		    html += key;
		    html += "&amp;plckLink=";
		    html += gSiteLife.EscapeValue(window.location.href);
		    html += "&amp;plckSubject=";
		    html += subject;
		    html += "&amp;sid=','Email','width=500,height=500,scrollbars=yes'); return false;\" class=\"SiteLife_EmailThis\" href=\"#none\">";
		    html += caption;
		    html += "</a>";	
		return html;
	},
	// draw a specific photo to the page, and update the navigation
	// elements for the next and previous
	// craet the divs and display all the pertinent data about the photo 
	photoHandler:function(photo){
		// we have a photo, update the page controls
		// for this photo.
		private.debug('photoHandler');
		private.debugobj(photo);
		var elCurrPhoto = document.getElementById("currentPhoto");
		elCurrPhoto.src = photo.Image.Full;
		
		// set vote options
		//anand: changed the hot or not control id's to ctl00_theContent_HyperLinkXXX since the page used master page
		//var elHot = document.getElementById("HotClick");
		var elHot = document.getElementById("ctl00_theContent_HyperLinkHot");
		elHot.onclick = function() { PLUCKHotOrNot.voteHot(photo.PhotoKey.Key,private.currentImageInBatch); };
		//var elNot = document.getElementById("NotClick");
		var elNot = document.getElementById("ctl00_theContent_HyperLinkNot");
		elNot.onclick = function() { PLUCKHotOrNot.voteNot(photo.PhotoKey.Key,private.currentImageInBatch);	};
		
		/*
		//anand: commented these code as there is no need for prev/next button
		// set prev/next buttons		
		var elPrev = document.getElementById("prevButton");
		elPrev.onclick = function() { PLUCKHotOrNot.previous(private.currentImageInBatch-1); };
		var elNext = document.getElementById("nextButton");
		elNext.onclick = function() { PLUCKHotOrNot.next(private.currentImageInBatch);	 };
		*/
		
		// set image details
		var elCurrentInfoDiv = document.getElementById("currentImageInfo");
		var infoHtml="";
		infoHtml += "<div id='honCurrentImageText'>";
		infoHtml += " <span id='honCurrentImageCaption'>"+photo.Title+"</span>";
		        
		var reportText = "Report Abuse";
		if(getLanguage() == "ES")
			reportText = "Reportar un Abuso";
		else
			reportText = "Report Abuse";
			    
		var reportedClass = "honCurrentReportAbuse";		
		var reportClick = " onclick=\"Batanga_ShowReportAbuse(event, document.URL, gSiteLife.__baseUrl + '/Photo/ReportAbuse?plckElementId=rpt_"+photo.PhotoKey.Key+"&plckPhotoId="+photo.PhotoKey.Key+"&plckTargetKeyType=Photo'); return false;";
		if (photo.CurrentUserHasReportedAbuse === "True") {
			reportClick ="";
			reportedClass = "honCurrentReportAbuseReported";
			if(getLanguage() == "ES")
			    reportText = "Abuso Reportado";
			else
			    reportText = "Abuse Reported";
		}
		//infoHtml += " <span id='rpt_"+photo.PhotoKey.Key+"' class='"+reportedClass+"' "+reportClick+"\";><div style=\"display:inline\">"+reportText+"</div></span>";
		infoHtml += " <div style='display:inline;' id='rpt_"+photo.PhotoKey.Key+"'> <span class='"+reportedClass+"' "+reportClick+"\";><div style=\"display:inline\">"+reportText+"</div></span></div>";
		infoHtml += "</div>";
		infoHtml += "<div id='honCurrentLeft'><a class='honLink' href='"+private.personaLink(photo.Author.UserKey.Key)+"'><img class='honPreviousPhoto' src='"+photo.Author.AvatarPhotoUrl+"' /></a></div>";
		infoHtml += "<div id='honCurrentRight'>";
		infoHtml += "  <div id='honCurrentSubmitted'>Submitted by: <span id='honSubmittedBy'><a class='honLink' href='"+private.personaLink(photo.Author.UserKey.Key)+"'>"+photo.Author.DisplayName+"</a></span> </div>";
		infoHtml += "  <div id='honSubmittedDate'>"+public.formatDate(photo.CreatedOn)+"</div>";
		infoHtml += "  <div id='honCurrentEmail'>";
		//infoHtml += "    <span id='honCurrentEmailGallery'>"+public.emailThis("Gallery","Email Gallery",private.galleryKey,gSiteLife.EscapeValue(private.galleryTitle)) + "</span>";
		if(getLanguage() == "EN")
		    infoHtml += "    <span id='honCurrentEmailGallery'>"+public.emailThis("Gallery","Email this Gallery",private.galleryKey,gSiteLife.EscapeValue(private.galleryTitle)) + "</span>";
		else
		    infoHtml += "    <span id='honCurrentEmailGallery'>"+public.emailThis("Gallery","Enviar esta Galería",private.galleryKey,gSiteLife.EscapeValue(private.galleryTitle)) + "</span>";
		infoHtml += "     | ";
		
		//infoHtml += "    <span id='honCurrentEmailPhoto'>"+public.emailThis("Photo","Email Photo",photo.PhotoKey.Key,gSiteLife.EscapeValue(photo.Title))+"</span>";
		if(getLanguage() == "EN")
		    infoHtml += "    <span id='honCurrentEmailPhoto'>"+public.emailThis("Photo","Email this Photo",photo.PhotoKey.Key,gSiteLife.EscapeValue(photo.Title))+"</span>";
		else
		    infoHtml += "    <span id='honCurrentEmailPhoto'>"+public.emailThis("Photo","Enviar esta Foto",photo.PhotoKey.Key,gSiteLife.EscapeValue(photo.Title))+"</span>";
		    
		infoHtml += "  </div>";
		infoHtml += "</div>";
		elCurrentInfoDiv.innerHTML = infoHtml;
	},
	// function that draws the HOT and NOT gradient bars based on the 
	// rating that came back with the article that was assigned to the image
	previousRated:function(href,hotpct,notpct){
		private.debug("previousRated: hotpct = " + hotpct + ", notpct = " + notpct + ", href = " + href);
		var elPreviousDiv = document.getElementById("previousImage");
		var prevHtml="";
		prevHtml += "<div id='honPrevText'>" + plckPrevPhotoText + "</div>";
		prevHtml += "<div id='honPrevLeft'><img class='honPreviousPhoto' src='"+href+"' /></div>";
		prevHtml += "<div id='honPrevRight'>";
		prevHtml += "  <div id='honPrevHot'>" + plckHotText + ": <span id='honPrevPercent'>"+hotpct+"%</span> </div> <div id='honHotSlider'></div>";
		prevHtml += "  <div id='honPrevNot'>" + plckNotText +": <span id='honPrevPercent'>"+notpct+"%</span> </div> <div id='honNotSlider'></div>";
		prevHtml += "</div>";
		elPreviousDiv.innerHTML = prevHtml;
		var elHotSlider = document.getElementById("honHotSlider");
		elHotSlider.style.width = hotpct+'%';
		var elNotSlider = document.getElementById("honNotSlider");
		elNotSlider.style.width = notpct+'%';
	},
	// format the display date to the batanga mocks
	formatDate:function(dateStr){  // June 02, 2008 | 1:43 AM EST
		//var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
     	var fullmonths = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

	    dateObj = new Date(dateStr);
	    var dateElements = dateObj.toString().split(" ");
	    var rawTime = "";
		var dateSplit = dateStr.split(" ");
	    var convertedTime = fullmonths[dateObj.getMonth()] + " " + dateObj.getDate()+ ", "+ dateObj.getFullYear() + " | " + dateSplit[1] + " " + dateSplit[2] + " EST" ;

		return convertedTime;
	},
	// show the comments associated with the image
	// if there are more than 10 comments include a pagination
	// links down at the bottom.
	showComments: function(commentArray,totalComments,onPage) {
		// draw comments
		var commentHtml = "";
		//commentHtml = "<div id=\"uploadPhoto\"><a href=\"GetPhoto.html?plckGalleryID="+private.galleryKey+"\">UploadToGallery</a></div>";
		var commentHtml;
		for (var i = 0; i < commentArray.length; i++) {
			var comment=commentArray[i];
			commentHtml += "<div id='commentRow'>";
			commentHtml += " <div id='commentAvatarLeft'><img class='honPreviousPhoto' src='"+comment.Author.AvatarPhotoUrl+"' /></a></div>";
			commentHtml += " <div id='commentRight'>";
			commentHtml += "   <div id='honCurrentSubmitted'>";
			commentHtml += "      <span id='honSubmittedBy'><a class='honLink' href='"+private.personaLink(comment.Author.UserKey.Key)+"'>"+comment.Author.DisplayName+"</a></span>";
			commentHtml += "      <span id='honSubmittedDate'> ("+public.formatDate(comment.PostedAtTime)+")</span>";
			
			var reportText = "Report Abuse";
		    if(getLanguage() == "ES")
			    reportText = "Reportar un Abuso";
		    else
			    reportText = "Report Abuse";
			var reportedClass = "honCurrentReportAbuse";			
			//var reportClick = " onclick=\"ShowReportAbuse(event, document.URL, gSiteLife.__baseUrl + '/AbuseReport/ReportAbuse?plckElementId=rpt_"+comment.CommentKey.Key+"&plckTargetKey="+comment.CommentKey.Key+"&plckTargetKeyType=Comment'); return false;";
			var reportClick = " onclick=\"Batanga_ShowReportAbuse(event, document.URL, gSiteLife.__baseUrl + '/AbuseReport/ReportAbuse?plckElementId=rpt_"+comment.CommentKey.Key+"&plckTargetKey="+comment.CommentKey.Key+"&plckTargetKeyType=Comment'); return false;";
			if (comment.CurrentUserHasReportedAbuse === "True") {
				reportClick ="";
				reportedClass = "honCurrentReportAbuseReported";
			    if(getLanguage() == "ES")
			        reportText = "Abuso Reportado";
			    else
			        reportText = "Abuse Reported";
			}
			//commentHtml += " <span id='rpt_"+comment.CommentKey.Key+"' class='"+reportedClass+"' "+reportClick+"\";><div style=\"display:inline\">"+reportText+"</div></span>";
			commentHtml += " <div style='display:inline;' id='rpt_"+comment.CommentKey.Key+"'><span class='"+reportedClass+"' "+reportClick+"\";><div style=\"display:inline\">"+reportText+"</div></span></div>";
//			commentHtml += "      <span id='honReportAbuse'> report abuse</span>";
			commentHtml += "   </div>";
			commentHtml += "   <div id='commentText'>"+comment.CommentBody+"</div>";
			commentHtml += " </div>";
			commentHtml += "</div>";
			commentHtml += "<hr />";
		}
		if (commentArray.length == undefined) {
			commentHtml += "Be the first to leave a comment<br />";
		}
		var elCmtDetails = document.getElementById("currentComments");
		elCmtDetails.innerHTML = commentHtml;
		// we have more than 10 comments
		// we need some pagination.
		if (totalComments > 10) {
			var elPage = document.getElementById("commentsPagination"); 
			elPage.innerHTML = public.paginationLinks(totalComments,onPage);
		}
		else {  // clear the pagination
			var elPage = document.getElementById("commentsPagination"); 
			elPage.innerHTML ="";
		}
	},
	// routine to create the pagination links based on
	// the current page and the total number of comments.
	paginationLinks: function(totalComments,onPage) {
	    var html =  "<div id=\"clearbof\"></div><div id=\"Paginator\" class=\"Comments\">";
	    for( var i=1;i<=(totalComments/10)+1;i++) {  // pages need to start at 1, so add 10
	    	if (onPage == i) // don't draw the link.
	    		html += " " +i+ " " ;		
	    	else
	    		html += " <a href=\"#none\" onclick=\"PLUCKHotOrNot.getCommentPage("+i+");return false;\">"+i+"</a> ";	
	    }
	    	html += "</div>";
	    	html += "<div id=\"clearbof\"></div>";
	    return html;
	},
	// display the comment counts above the comments
	showCommentCounts:function(cnt) {
		private.debug("showCommentCounts");
		private.debug("comment count : " + cnt);
		if (cnt == undefined)
		   cnt = 0;
		var elCmtHeader = document.getElementById("commentCount");
		//elCmtHeader.innerHTML = cnt +" Comments";
		
        language = getLanguage();
        if(cnt == 1)
        {
            if(language == "EN")
                elCmtHeader.innerHTML = cnt +" Comment";
            else
                elCmtHeader.innerHTML = cnt +" Comentario";                
        }
        else
        {
           if(language == "EN")
                elCmtHeader.innerHTML = cnt +" Comments";
            else
                elCmtHeader.innerHTML = cnt +" Comentarios";                
        }
	},
	// get a specific page of comments, AJAX from the comment links
	getCommentPage: function(pageNumber){
		private.debug("getCommentPage");
		private.debug("need page# " + pageNumber);
		private.commentsPagination(pageNumber);
	},
	commentPopup: null,
	postComment:function(obj,comment) {
		private.debug("postComment-public");
		// post a comment
		// quick hack to create a comment
		private.postComment(comment);
		commentPopup=obj;
	},
	// after the comment was posted
	// show the user some feed back, if there was
	// an error, or clean up the comment dialog
	// for the next comment
	postCommentResult:function(result) {
		private.debug("postCommentResult");
		if (result === "ok") {		    
		    //anand: commentPopup could be null when called from votinggallery page to post comment coded by batanga.
		    if(commentPopup != null)
			    commentPopup.submit();
			
			// success, we must reload the comments
			private.reloadComments();
			
			// clear previous comment entry
			document.getElementById("commentEntry").value = "";
			document.getElementById("commentErrorMessage").innerHTML = "";
		}
		else {
			var elErr = document.getElementById("commentErrorMessage");
			elErr.innerHTML = result;
		}

	},
	// get the details from the modalbox to update the photo and send off to 
	// pluck.
	setPhotoDetails: function() {
		private.debug("setPhotoDetails");
	    var photoKey = document.getElementById("updatePhotoKey").value;
	    var title = document.getElementById("updateTitle").value;
	    var description = document.getElementById("updateDescription").value;
	    var tags = document.getElementById("updateTags").value;
		private.updatePhotoAction(photoKey,title,description,tags,private.section);
		//Modalbox.hide();
	},
	// after the photo meta data was updated, 
	// hide the modalbox.
	// 
	updatePhotoActionSuccess: function(results) {
		private.debug("updatePhotoActionSuccess");
		if (results==="ok")
		    Modalbox.hide();
		else
			Modalbox.hide();
		// REVIST this, we need to add error message to the Modalbox
		private.reloadHotOrNot();
	},
	reportAbuse: function(index){
		// report abuse
	}
  }
  // just log our object getting created
  private.debug("Doing Something : "+ public.getTitle() );
  return public;
}();

