/**
 * @author ernestoj
 */

/**
 * Add event handlers for flag, download, add/cancel clicks
 */
adobe.marketplace.addClickListeners = function(offeringID, publisherID){
	// --- offering-related ---
	// track download of non-AIR offering
	if ($('linkOfferDownload')) {
		Event.observe($('linkOfferDownload'), 'click', function(){
			adobe.marketplace.track('offeringDownload', offeringID, publisherID);
		});
	}
	// flag offering
	Event.observe($('linkOfferingFlag'), 'click', function(){
		adobe.marketplace.popupManager.launchPopup('flagOffering', this, function(){
			adobe.marketplace.PopupContent_Flag.flagInit('flagOffering', offeringID, 'offering');
		});
	});
	// --- review-related ---
	// add review
	if ($('reviewLinkAdd')) {
		Event.observe($('reviewLinkAdd'), 'click', function(){
			adobe.marketplace.reviewController('','review','add', offeringID);
		});
	}
	// cancel review
	if ($('linkReviewCancel')) {
		Event.observe($('linkReviewCancel'), 'click', function(){
			adobe.marketplace.reviewController('', 'review', 'canceladd', offeringID);
		});
	}
	// submit review
	if ($('linkReviewSubmit')) {
		Event.observe($('linkReviewSubmit'), 'click', function(){
			adobe.marketplace.reviewController('', 'review', 'submitadd', offeringID);
		});
	}
	// review/comment-specific links: review helpfulness, comments toggles, comment add
	$('allReviews').select('.reviewBlock').each(function(reviewBlock) {
		var reviewID = reviewBlock.id.sub('reviewBlock','');
		// --- review-related ---
		// rank review
		if ((reviewBlock.select('.linkReviewHelpfulY')[0]) && (reviewBlock.select('.linkReviewHelpfulN')[0])) {
			Event.observe(reviewBlock.select('.linkReviewHelpfulY')[0], 'click', function(){
				adobe.marketplace.reviewController(reviewID,'review','rankYes', '');
			});
			Event.observe(reviewBlock.select('.linkReviewHelpfulN')[0], 'click', function(){
				adobe.marketplace.reviewController(reviewID,'review','rankNo', '');
			});
		}
		// flag review
		if (reviewBlock.select('.linkReviewFlag').length > 0) {
			Event.observe(reviewBlock.select('.linkReviewFlag')[0], 'click', function(){
				adobe.marketplace.popupManager.launchPopup('flagReview',this, function(){
				 	adobe.marketplace.PopupContent_Flag.flagInit('flagReview', reviewID, 'review')
				});
			});
		}
		// remove review
		if (reviewBlock.select('#linkReviewRemove').length > 0) {
			Event.observe($('linkReviewRemove'), 'click', function(){
				adobe.marketplace.popupManager.launchPopup('confirm',this, function(){
				 	adobe.marketplace.PopupContent_ConfirmDelete.init('confirm', reviewID,'review','')
				});
			});
		}
		// edit review
		if (reviewBlock.select('#linkReviewEdit').length > 0) {
			Event.observe($('linkReviewEdit'), 'click', function(){
				 adobe.marketplace.reviewController(reviewID,'review','edit', '');
			});
		}
		if($('reviewEditCancel'+reviewID)){
			Event.observe($('reviewEditCancel'+reviewID), 'click', function(){
				adobe.marketplace.reviewController(reviewID, 'review', 'canceledit', '');
			});
		}
		if($('reviewEditSubmit'+reviewID)){
			Event.observe($('reviewEditSubmit'+reviewID), 'click', function(){
				adobe.marketplace.reviewController(reviewID, 'review', 'submitedit', '');
			});
		}
		// --- comment-related ---
		// toggle comments
		if (reviewBlock.select('.linkCommentCtrl').length > 0) {
			reviewBlock.select('.linkCommentCtrl').each(function(linkCtrl) {
				Event.observe(linkCtrl, 'click', function(){
					adobe.marketplace.reviewController(reviewID, 'review', 'toggleComments', '');
				});
			});
		}
		// add comment
		if (reviewBlock.select('.linkCommentAdd').length > 0) {
			var linkAdd = reviewBlock.select('.linkCommentAdd')[0];
			linkAdd.onclick = function(){
				 adobe.marketplace.reviewController(reviewID,'comment','add', offeringID);
			}
		}
		if ($('linkCommentCancel' + reviewID)) {
	  	Event.observe($('linkCommentCancel' + reviewID), 'click', function(){
	  		adobe.marketplace.reviewController(reviewID, 'comment', 'canceladd', offeringID);
	  	});
	  }
		if ($('linkCommentSubmit' + reviewID)) {
	  	Event.observe($('linkCommentSubmit' + reviewID), 'click', function(){
	  		adobe.marketplace.reviewController(reviewID, 'comment', 'submitadd', offeringID);
	  	});
	  }
	});

	$('allReviews').select('.commentsSet').each(function(commentSet){
		var reviewID = commentSet.id.sub('commentsSet','');
			commentSet.select('.comment').each(function(commentBlock){
				var commentID = commentBlock.id.sub('comment', '');
				if ($('commentEditCancel' + reviewID + "_" + commentID)) {
					Event.observe($('commentEditCancel' + reviewID + "_" + commentID), 'click', function(){
						adobe.marketplace.reviewController(reviewID + "_" + commentID, 'comment', 'canceledit', '');
					});
				}
				if ($('commentEditSubmit' + reviewID + "_" + commentID)) {
					Event.observe($('commentEditSubmit' + reviewID + "_" + commentID), 'click', function(){
						adobe.marketplace.reviewController(reviewID + "_" + commentID, 'comment', 'submitedit', '');
					});
				}
			});
	});
}

/**
 * Controller to handle all review/comment actions: add, edit, remove, and rank
 * @see adobe.marketplace.toggleDisplay
 * @see adobe.marketplace.toggleLink
 * @param {Int} itemid Review/Comment Id, blank if new
 * @param {String} type
 * @param {Function} action
 */
adobe.marketplace.reviewController = function(itemid, type ,action, offeringId){
	switch(action){
		case "add": //Initialize form for adding an item
			adobe.marketplace.track(type+'Add', offeringId, '');
			switch(type){
				case "review":
					adobe.marketplace.toggleDisplay($(type+"LinkAdd"));
				break;
				case "comment":
					adobe.marketplace.toggleLink($(type+"LinkAdd"+itemid));
				break;
			}
			if (adobe.marketplace.reviewController.hasScreenName == false) {
	  	// Bug 92611 : Added logic for checking nick name of the logged in user
				itemForm = "arButtonForm";
				//Display loading message
				//adobe.marketplace.popupManager.showCenterPopup("generic");
				//adobe.marketplace.popupManager.showPopupCustom("generic", "Checking your credentials...");
				//adobe.marketplace.popupManager.hidePopupButtons("generic");
				new Ajax.Request(adobe.marketplace.AJAXURL, {
					parameters: $(itemForm).serialize(true),
					method: 'post',
					onSuccess: function(response){
						//Hide loading message
						adobe.marketplace.popupManager.hidePopup("generic");
						var responseObj = response.responseText.stripTags().evalJSON();
						if (typeof(responseObj.RETURNDATA.MESSAGE) != "undefined" && responseObj.RETURNDATA.MESSAGE == "Successful") {
							//adobe.marketplace.toggleDisplay($(type+"LinkAdd"));
							adobe.marketplace.reviewController.hasScreenName = true;
						}
						else {
							window.location.replace('http://' + responseObj.RETURNDATA.SERVER + '&' + responseObj.RETURNDATA.RETURNURL);
						}
					}.bind(this)
				});
			}
			$(type+"AddBlock"+itemid).style.display = 'block';
			//adobe.marketplace.toggleDisplay($(type+"AddBlock"+itemid));
			$(type+"TextArea"+itemid).focus();
		break;
		case "edit": //Initialize form for editing an item
			//adobe.marketplace.toggleDisplay($(type+"EditBlock"+itemid));
			$(type+"EditBlock"+itemid).style.display = 'block';
			adobe.marketplace.toggleDisplay($(type+"Block"+itemid));
		break;
		case "canceladd": //Reset after cancelled add.
			switch(type){
				case "review":
				 	//adobe.marketplace.toggleDisplay($(type+"LinkAdd"));
					$(type+"LinkAdd").style.display = 'block';
				break;
				case "comment":
					adobe.marketplace.toggleLink($(type+"LinkAdd"+itemid));
				break;
			}
			$(type+"AddForm"+itemid).reset();
			adobe.marketplace.toggleDisplay($(type+"AddBlock"+itemid));
		break;
		case "canceledit": // Reset after cancelled edit
			$(type+"EditForm"+itemid).reset();
			adobe.marketplace.toggleDisplay($(type+"EditBlock"+itemid));
			adobe.marketplace.toggleDisplay($(type+"Block"+itemid));
		break;
		case "submitadd": //Submit the added data to the server
			var itemForm;
			switch (type) {
			  	case "review":
			  		itemForm = "reviewAddForm";
			  	break;
			  	case "comment":
			  		itemForm = "commentAddForm"+itemid;
			  	break;
			}
			adobe.marketplace.toggleDisplay($(type+"AddBlock"+itemid));
			//Display loading message
			//adobe.marketplace.popupManager.showCenterPopup("generic");
			//adobe.marketplace.popupManager.showPopupCustom("generic","Your submission is being processed...");
			new Ajax.Request(adobe.marketplace.AJAXURL,{
				parameters: $(itemForm).serialize(true),
				method: 'post',
				onSuccess: function(response){
					//Hide loading message
					adobe.marketplace.popupManager.hidePopup("generic");
					var responseObj = response.responseText.stripTags().evalJSON();
					var requiresLogin = false;
					if((responseObj.ERRORS.MISSING_ARGUMENTS.length > 0)||(responseObj.ERRORS.INVALID_ARGUMENTS.length > 0)||(typeof(responseObj.ERRORS.RESULT) != "undefined")){
						var errorStr = "";
						if (responseObj.ERRORS.MISSING_ARGUMENTS.length > 0) {
							errorStr += "You have not filled out all the required fields:<ul>";
							responseObj.ERRORS.MISSING_ARGUMENTS.each(function(errorMsg){
								switch (errorMsg.toUpperCase()) {
									case "USERID":
										requiresLogin = true;
									break;
									case "REVIEW_TEXT":
									case "COMMENT_TEXT":
									case "OFFERINGID": //Error - shouldn't happen
										errorStr += "<!-- error: " + errorMsg + "-->";
									break;
									case "RATING":
										errorStr += "<li>Please select rating.</li>";
									break;
								}
							});
							errorStr += "</ul>";
						}
						if (responseObj.ERRORS.INVALID_ARGUMENTS.length > 0) {
							errorStr += "There was a problem with your submission:<ul>";
							responseObj.ERRORS.INVALID_ARGUMENTS.each(function(errorMsg){
								switch (errorMsg.toUpperCase()) {
									case "OFFERINGID"://Error - shouldn't happen
										errorStr += "<!-- error: " + errorMsg + "-->";
									break;
									case "RATING": //Error - shouldn't happen
										errorStr += "<li>Please select rating.</li>";
									break;
									case "USERID":
										requiresLogin = true;
									break;
									break;
									case "REVIEW_TEXT":
										errorStr += "<li>Your review must be between 1 and 4,000 characters.</li>";
									break;
									case "COMMENT_TEXT":
										errorStr += "<li>Your comment must be between 1 and 250 characters.</li>";
									break;
								}
							});
							errorStr += "</ul>";
			 	 		}
						if(typeof(responseObj.ERRORS.RESULT) != "undefined"){
							switch(responseObj.ERRORS.RESULT.ERRORTYPE){
								case "ALREADYREVIEWED":
									errorStr += "<br/>You have already reviewed this Offering."
								break;
								default:
									errorStr += "<br/>There was an error in submitting your "+type+".  Please try again."
								break;
							}
						}
						if(requiresLogin){
							adobe.marketplace.login();
							return false;
						}
						if(errorStr != ""){
							adobe.marketplace.popupManager.showCenterPopup("generic");
							adobe.marketplace.popupManager.showPopupCustom("generic",errorStr);
							adobe.marketplace.toggleDisplay($(type+"AddBlock"+itemid));
						}
					} else { //Successful submission
						adobe.marketplace.track(type+'Submit', offeringId, '');
						var reviewsLink = "http://"+window.location.hostname+"/cfusion/marketplace/index.cfm?event=marketplace.offering.reviews&marketplaceid="+adobe.marketplace.getUrlParam("marketplaceid")+"&offeringid="+adobe.marketplace.getUrlParam("offeringid");
						triggerSubmit(reviewsLink);
					//	adobe.marketplace.toggleDisplay($(type+"AddBlock"+itemid));
					}
				}.bind(this),
				onFailure: function(){ //Server error
					adobe.marketplace.popupManager.showCenterPopup("generic");
					adobe.marketplace.popupManager.showPopupCustom("generic","There was an error in your submission, please try again.");
					adobe.marketplace.toggleDisplay($(type+"AddBlock"+itemid));
				}.bind(this)
			});
		break;
		case "submitedit": //Submit the submitted data to the server
			var formObj = $(type+"EditForm"+itemid).serialize(true);
			adobe.marketplace.toggleDisplay($(type+"EditBlock"+itemid)); //Hide Form on submit
			//Display loading message
			//adobe.marketplace.popupManager.showCenterPopup("generic");
			//adobe.marketplace.popupManager.showPopupCustom("generic","Your submission is being processed...");
			new Ajax.Request(adobe.marketplace.AJAXURL,{
				parameters: formObj,
				method: 'post',
				onSuccess: function(response){
					//Hide loading message
					adobe.marketplace.popupManager.hidePopup("generic");
					try{
						var responseObj = response.responseText.stripTags().evalJSON();
						var requiresLogin = false;
						if((responseObj.ERRORS.MISSING_ARGUMENTS.length > 0)||(responseObj.ERRORS.INVALID_ARGUMENTS.length > 0)||(typeof(responseObj.ERRORS.RESULT) != "undefined")){
							var errorStr = "";
							if (responseObj.ERRORS.MISSING_ARGUMENTS.length > 0) {
								errorStr += "You have not filled out all the required fields.<ul>";
								responseObj.ERRORS.MISSING_ARGUMENTS.each(function(errorMsg){
									switch (errorMsg.toUpperCase()) {
										case "USERID":
											requiresLogin = true;
										break;
										case "REVIEW_TEXT":
										case "COMMENT_TEXT":
										case "OFFERINGID": //Error - shouldn't happen
											errorStr += "<!-- error: " + errorMsg + "-->";
										break;
										case "RATING": //Error - shouldn't happen due to previous submission
											errorStr += "<li>Please select rating.</li>";
										break;
									}
								});
								errorStr += "</ul>";
							}
							if (responseObj.ERRORS.INVALID_ARGUMENTS.length > 0) {
								errorStr += "You have not filled out all the required fields.<ul>";
								responseObj.ERRORS.INVALID_ARGUMENTS.each(function(errorMsg){
									switch (errorMsg.toUpperCase()) {
										case "OFFERINGID"://Error - shouldn't happen
											errorStr += "<!-- error: " + errorMsg + "-->";
										break;
										case "RATING": //Error - shouldn't happen
											errorStr += "<li>Your rating was invalid.  Please select a rating.</li>";
										break;
										case "USERID":
											requiresLogin = true;
										break;
										case "REVIEW_TEXT":
											errorStr += "<li>Your " + type + " must be between 1 and 4,000 characters.</li>";
										break;
										case "COMMENT_TEXT":
											errorStr += "<li>Your " + type + " must be between 1 and 4,000 characters.</li>";
										break;
									}
								});
				  		}
							if(requiresLogin){
								adobe.marketplace.login();
								return false;
							}
							if(errorStr != ""){
								adobe.marketplace.popupManager.showCenterPopup("generic");
								adobe.marketplace.popupManager.showPopupCustom("generic",errorStr);
								adobe.marketplace.toggleDisplay($(type+"EditBlock"+itemid)); //redisplay form for correction
							}
						} else { //Successful submission
						var reviewsLink = "http://"+window.location.hostname+"/cfusion/marketplace/index.cfm?event=marketplace.offering.reviews&marketplaceid="+adobe.marketplace.getUrlParam("marketplaceid")+"&offeringid="+adobe.marketplace.getUrlParam("offeringid");
						triggerSubmit(reviewsLink);
						}
					}catch(err){
						adobe.marketplace.popupManager.showCenterPopup("generic");
						adobe.marketplace.popupManager.showPopupCustom("generic","There was an error in your submission, please try again.");
						adobe.marketplace.toggleDisplay($(type+"EditBlock"+itemid)); //redisplay form for correction
					}
				}.bind(this),
				onFailure: function(){ //Server error
					adobe.marketplace.popupManager.showCenterPopup("generic");
					adobe.marketplace.popupManager.showPopupCustom("generic","There was an error in your submission, please try again.");
					adobe.marketplace.toggleDisplay($(type+"EditBlock"+itemid)); //redisplay form for correction
				}
			});
		break;
		case "rankYes": //Submit the a vote for the review/comment to the server
			//Display loading message
			//adobe.marketplace.popupManager.showCenterPopup("generic");
			//adobe.marketplace.popupManager.showPopupCustom("generic","Your submission is being processed...");
			new Ajax.Request(adobe.marketplace.AJAXURL,{
				parameters: {
					METHOD:'simpleRateItem',
					TYPE: type,
					ITEMID: itemid,
					VOTE: 1
				},
				method: 'post',
				onSuccess: function(response){
					//Hide loading message
					adobe.marketplace.popupManager.hidePopup("generic");
					var responseObj = response.responseText.stripTags().evalJSON();
					if((responseObj.ERRORS.MISSING_ARGUMENTS.length > 0)||(responseObj.ERRORS.INVALID_ARGUMENTS.length > 0)||(typeof(responseObj.ERRORS.RESULT) != "undefined")){
						var hasRanked = 0;
						responseObj.ERRORS.INVALID_ARGUMENTS.each(function(errorMsg){
							switch(errorMsg.toUpperCase()){
								case "ITEMID":
									adobe.marketplace.popupManager.showCenterPopup("generic");
									adobe.marketplace.popupManager.showPopupCustom("generic","You have already ranked that item.<br /><br />Thank you for your vote.");
									$("helpfulMessage"+itemid).innerHTML = "Thank you for your vote.";
									hasRanked = 1;
								break;
							}
						});
						if (hasRanked == 0) {
							adobe.marketplace.popupManager.showCenterPopup("generic");
							adobe.marketplace.popupManager.showPopupCustom("generic", "There was a problem with your vote.  Please try again.");
						}
					} else {
						if (responseObj.VOTES != "") {
							var peopleStr = "people"
							if (responseObj.VOTES == 1) peopleStr = "person";
							$("helpfulMessage" + itemid).innerHTML = responseObj.VOTES + " " + peopleStr + " found this review helpful.";
						} else {
							$("helpfulMessage"+itemid).innerHTML = "Thank you for your vote.";
						}
					}
				}.bind(this),
				onFailure: function(){
					adobe.marketplace.popupManager.showCenterPopup("generic");
					adobe.marketplace.popupManager.showPopupCustom("generic","There was a problem with your vote.  Please try again.");
				}
			});
		break;
		case "rankNo":
			new Ajax.Request(adobe.marketplace.AJAXURL,{
				parameters: {
					METHOD:'simpleRateItem',
					TYPE: type,
					ITEMID: itemid,
					VOTE: 0
				},
				method: 'post'
			});
			$("helpfulMessage"+itemid).innerHTML = "Thank you for your vote.";
		break
		case "toggleComments": //toggle visibility of comments
			//adobe.marketplace.toggleDisplay($("commentCtrlHide"+itemid));
			//adobe.marketplace.toggleDisplay($("commentCtrlShow"+itemid));
			adobe.marketplace.toggleDisplay($("commentsSet"+itemid));
			if($("commentsSet"+itemid).style.display == 'none')
			{
				$("commentCtrlHide"+itemid).style.display = 'none';
				$("commentCtrlShow"+itemid).style.display = 'inline';
			}
			else
			{
				$("commentCtrlHide"+itemid).style.display = 'inline';
				$("commentCtrlShow"+itemid).style.display = 'none';
			}
		break;
		default:
			//Error - shouldn't happen
		break;

	}
}
adobe.marketplace.reviewController.hasScreenName = false;

adobe.marketplace.reviewController.reviewCount = 0;
adobe.marketplace.tempStr = "<div id=\"comment#{commentid}\" class=\"comment\">";
adobe.marketplace.tempStr+= "	<div class=\"commentBlockLabel\">Comment:</div>";
adobe.marketplace.tempStr+= "	<div id=\"commentBlock#{reviewid}_#{commentid}\" class=\"commentBlock\">";
adobe.marketplace.tempStr+= "		<span class=\"screen_name\">#{username}</span>		<br/>";
adobe.marketplace.tempStr+= "		Posted: #{postdate}<br/><br />";
adobe.marketplace.tempStr+= "		<p>";
adobe.marketplace.tempStr+= "			#{commenttext}";
adobe.marketplace.tempStr+= "		</p>";
adobe.marketplace.tempStr+= "		<div class=\"helpfulBlock\">";
adobe.marketplace.tempStr+= "			<div class=\"insideBlock\">";
adobe.marketplace.tempStr+= "				<span id=\"helpfulMessage#{commentid}\">";
adobe.marketplace.tempStr+= "					Was this review helpful?";
adobe.marketplace.tempStr+= "					<a href=\"javascript:void(0);\" onclick=\"adobe.marketplace.reviewController('#{commentid}','comment','rankYes');\"><img class=\"helpfulButton\" src=\"/images/marketplace/buttons/yes_btn.jpg\"></a>";
adobe.marketplace.tempStr+= "					<a href=\"adobe.marketplace.reviewController('#{commentid}','comment','rankNo');\"><img class=\"helpfulButton\" src=\"/images/marketplace/buttons/no_btn.jpg\"></a> <br />";
adobe.marketplace.tempStr+= "				</span>";
adobe.marketplace.tempStr+= "			</div>";
adobe.marketplace.tempStr+= "		</div><br />";
adobe.marketplace.tempStr+= "		<a href=\"javascript:void(0);\" onclick=\"adobe.marketplace.popupManager.launchPopup('confirm',this, function(){adobe.marketplace.PopupContent_ConfirmDelete.init('confirm','#{commentid}','comment')});\">Remove My Comment</a> |";
adobe.marketplace.tempStr+= "		<a href=\"javascript:void(0);\" onclick=\"adobe.marketplace.reviewController('#{reviewid}_#{commentid}','comment','edit')\">Edit My Comment</a><br /><br />";
adobe.marketplace.tempStr+= "	</div>";
adobe.marketplace.tempStr+= "	<div id=\"commentEditBlock#{reviewid}_#{commentid}\" class=\"initialHide\">";
adobe.marketplace.tempStr+= "		<form name=\"commentEditForm#{reviewid}_#{commentid}\" id=\"commentEditForm#{reviewid}_#{commentid}\">";
adobe.marketplace.tempStr+= "			<input type=\"hidden\" name=\"id\" value=\"#{commentid}\" />";
adobe.marketplace.tempStr+= "			<textarea  name=\"commentEditTextArea#{reviewid}_#{commentid}\" id=\"ccommentEditTextArea#{reviewid}_#{commentid}\" class=\"addTextArea\" maxlength=\"250\">#{commenttext}</textarea><br/>";
adobe.marketplace.tempStr+= "			<a href=\"javascript:void(0);\" onclick=\"adobe.marketplace.reviewController('#{reviewid}_#{commentid}','comment','canceledit')\">[cancel button]</a>";
adobe.marketplace.tempStr+= "			<a href=\"javascript:void(0);\" onclick=\"adobe.marketplace.reviewController('#{reviewid}_#{commentid}','comment','submitedit')\">[submit button]</a>";
adobe.marketplace.tempStr+= "		</form>";
adobe.marketplace.tempStr+= "	</div>";
adobe.marketplace.tempStr+= "</div>";
adobe.marketplace.commenthtmlTemplate = new Template(adobe.marketplace.tempStr);
/**
 * Tracks: 1. clickthroughs/downloads of offerings;
 * 2. adds and submits of reviews and comments;
 * 3. flags of offerings, reviews, and comments
 * @param {String} action
 * @param {Int} offeringId
 * @param {Int} publisherId
 */

adobe.marketplace.track = function(action, offeringId, publisherId){
	// Get and format marketplace name
	var marketplaceName = $('ratingWidgetTop').className;
	marketplaceName = (marketplaceName == 'air') ? 'AIR' : marketplaceName.capitalize();
	s_eVar23=""; // Reset values so that non-offering download actions are not populated with these values
	s_events=""; // Reset values so that non-offering download actions are not populated with these values
	switch(action) {
		case "offeringDownload":
			new Ajax.Request(adobe.marketplace.AJAXURL,{
				parameters: {OFFERINGID:offeringId, PUBLISHERID:publisherId, method:"trackClickThrough"},
				method: 'post',
				onSuccess: function(response){
					//Do nothing.  Click successfully tracked.
				},
				onFailure: function(){
					//Do nothing.  Reattempted submission could infinite loop.
				}
			});
			s_pageNameSuffix = 'Download';
			s_prop41Middle = 'Download';
			s_eVar23="Marketplace: "+marketplaceName+": "+offeringId;
			s_events="event46";
		break;
		// tracking for review and comment add and submit
		// called from adobe.marketplace.reviewController in this JS file
		case "reviewAdd":
			s_pageNameSuffix = 'Review';
			s_prop41Middle = 'Offer Add Review';
		break;
		case "reviewSubmit":
			s_pageNameSuffix = 'Review Added';
			s_prop41Middle = 'Offer Review Added';
		break;
		case "commentAdd":
			s_pageNameSuffix = 'Comment';
			s_prop41Middle = 'Offer Page Add Comment';
		break;
		case "commentSubmit":
			s_pageNameSuffix = 'Comment Added';
			s_prop41Middle = 'Offer Page Comment Added';
		break;
		// tracking for review, comment, and offering flag called from
		// adobe.marketplace.PopupContent_Flag.flagInit in onclick in CFM file
		case "reviewFlag":
			s_pageNameSuffix = 'Review Flagged';
			s_prop41Middle = 'Offer Review Flagged';
		break;
		case "commentFlag":
			s_pageNameSuffix = 'Comment Flagged';
			s_prop41Middle = 'Offer Comment Flagged';
		break;
		case "offeringFlag":
			s_pageNameSuffix = 'Offering Flagged';
			s_prop41Middle = 'Offer Offering Flagged';
		break;
	}
	s_pageName = 'Marketplace: ' + marketplaceName + ': Offer: ' + s_pageNameSuffix;
	s_prop41 = 'Marketplace: ' + marketplaceName + ': ' + s_prop41Middle + ': Offering=' + offeringId;
	try
	{
		sendAnalyticsEvent();
	}
	catch(e)
	{
	}
}
/**
 * Simple data object storage of button values for use in Popups
 * @extends adobe.marketplace.DataObject
 * @constructor
 * @param {String} label Text value for button label
 * @param {Function} action Function to be called on click
 */
adobe.marketplace.PopupButton = Class.create(adobe.marketplace.DataObject, {
	initialize: function(label, action){
		this.label = label;
		this.action = action;
	}
});
/**
 * Textstring prototype template for PopupButton initialization.
 */
adobe.marketplace.tempStr = "<a id=\"popupButton#{id}\" class=\"greyButtonLink popupButton\" href=\"javascript:void(0)\">";
adobe.marketplace.tempStr+= "		<div class=\"greyButtonBorder\"><div class=\"greyButton greyButton21\">";
adobe.marketplace.tempStr+= "			<div class=\"buttonText\">#{label}</div>";
adobe.marketplace.tempStr+= "		</div></div>";
adobe.marketplace.tempStr+= "	</a>";
adobe.marketplace.PopupButton.htmlTemplate = new Template(adobe.marketplace.tempStr);
/**
 * Popup layer for use in form submissions, confirmations, and other alerts.
 * Not manipulated directly but called through adobe.marketplace.PopupManager
 * @see adobe.marketplace.PopupButton
 * @see adobe.marketplace.PopupButton.htmlTemplate
 * @see adobe.marketplace.toggleLink
 * @constructor
 */
adobe.marketplace.Popup = Class.create({
	/**
	 * Initializes values and sets up Popup
	 * @see #setup
	 * @param {String} id Unique label/identifier for Popup
	 * @param {String} title Label displayed in Popup title bar
	 * @param {String} classNameStr CSS class(es) to be assigned to Popup
	 * @param {String} content HTML to be inserted into 'content' div of popup
	 * @param {Array} buttons Array of adobe.marketplace.PopupButton for insertion into 'popupButtons' div
	 * @param {String} confirmation Message to be displayed upon successful submission
	 */
	initialize: function(id, title, classNameStr, content, buttons, confirmation){
		this.id = id;
		this.title = title;
		this.classNameStr = classNameStr;
		this.content = content;
		this.buttons = buttons;
		confirmation ? this.confirmation = confirmation : this.confirmation = 'Your item has been submitted.';
		this.buttonCount = 0;
		this.setup();
		this.callingItem;
	},
	/**
	 * Preps Popup for use on page.
	 */
	setup: function(){
		var data = {id:this.id, title: this.title, classNameStr: this.classNameStr, content: this.content, confirmation: this.confirmation};
		var popup = adobe.marketplace.Popup.htmlTemplate.evaluate(data);
		$(document.body).insert(popup,{position: 'bottom'});
		this.buttons.each(function(button){
			this.buttonCount++;
			var data = {id: this.id+""+this.buttonCount, label: button.label}
			var buttonNode = adobe.marketplace.PopupButton.htmlTemplate.evaluate(data);
			$('popup'+this.id).getElementsByClassName('popupButtons')[0].insert(buttonNode,{position: 'bottom'});
			Event.observe($('popupButton'+this.id+""+this.buttonCount),"click",button.action);
		}.bind(this));
		//Add ok button - closes window
		this.buttonCount++;
		var buttonObj =	new adobe.marketplace.PopupButton("OK", function(){
			adobe.marketplace.popupManager.hidePopup(this.id);
		}.bind(this));
		var data = {id: this.id+""+this.buttonCount, label: buttonObj.label}
		var buttonNode = adobe.marketplace.PopupButton.htmlTemplate.evaluate(data);
		$('popup'+this.id).getElementsByClassName('popupOkButton')[0].insert(buttonNode,{position: 'bottom'});
		Event.observe($('popupButton'+this.id+""+this.buttonCount),"click",buttonObj.action);
		//Add okReturn button - returns to base state without a form reset
		this.buttonCount++;
		var buttonObj =	new adobe.marketplace.PopupButton("OK", function(){
			adobe.marketplace.popupManager.returnPopupLayout(this.id);
		}.bind(this));
		var data = {id: this.id+""+this.buttonCount, label: buttonObj.label}
		var buttonNode = adobe.marketplace.PopupButton.htmlTemplate.evaluate(data);
		$('popup'+this.id).getElementsByClassName('popupOkReturnButton')[0].insert(buttonNode,{position: 'bottom'});
		Event.observe($('popupButton'+this.id+""+this.buttonCount),"click",buttonObj.action);
		adobe.marketplace.CountdownTextareaManager.getInstance().findNew($('popup'+this.id)); //add textarea counters as needed.
	},
	/**
	 * Positions and displays popup
	 * @param {Object} callingItem Link used to call show.  Used to disable while visible.
	 * @param {Function} action Function called after initialization. Primarily used to set form values.
	 */
	show: function(callingItem,action){
		this.callingItem = callingItem; //store callingItem for toggle later
		// If calling item is link to flag offering, remove event handler before turning off
		if (this.callingItem.id == 'linkOfferingFlag') {
			Event.stopObserving(this.callingItem, 'click');
		}
		adobe.marketplace.toggleLink(callingItem);
		var topOffset=($('popup'+this.id).getHeight() * -1) - callingItem.getHeight();
		$('popup'+this.id).clonePosition(callingItem,{offsetTop:topOffset, offsetLeft: 0, setHeight: false, setWidth: false});
		$('popup'+this.id).style.display = "block";
		adobe.marketplace.sifrOnDemand('popup'+this.id);
		adobe.marketplace.CountdownTextareaManager.getInstance().findNew($('popup'+this.id)); //add textarea counters as needed.
		document.location.href="#popupAnchor"+this.id; //Ensure top of popup visible.
		action();
	},
	showCenter: function(){
		// most browsers
		if (typeof window.innerHeight != 'undefined') {
			$('popup' + this.id).style.top = Math.round(document.viewport.getScrollOffsets().top + ((window.innerHeight - $('popup' + this.id).getHeight())) / 2) + 'px';
			$('popup' + this.id).style.left = Math.round(document.viewport.getScrollOffsets().left + ((window.innerWidth - $('popup' + this.id).getWidth())) / 2) + 'px';
		// IE
		} else {
			if (BrowserDetect.version == 7) {
		  	$('popup' + this.id).style.top = Math.round(document.viewport.getScrollOffsets().top + (($$('body')[0].clientHeight - $('popup' + this.id).getHeight())) / 2) + 'px';
		  	$('popup' + this.id).style.left = Math.round(document.viewport.getScrollOffsets().left + (($$('body')[0].clientWidth - $('popup' + this.id).getWidth())) / 2) + 'px';
		  }
		  else {
		  	$('popup' + this.id).style.top = Math.round(document.body.scrollTop + (($$('body')[0].clientHeight - $('popup' + this.id).getHeight())) / 2) + 'px';
		  	$('popup' + this.id).style.left = Math.round(document.body.scrollLeft + (($$('body')[0].clientWidth - $('popup' + this.id).getWidth())) / 2) + 'px';
		  }
		}
		$('popup'+this.id).setStyle({display: "block"});
	},
	/**
	 * Hides Popup and re-enables callingItem
	 * @see #resetLayout
	 */
	hide: function(){
		this.resetLayout();
		$('popup'+this.id).style.display = "none";
		adobe.marketplace.toggleLink(this.callingItem);
		// If calling item is link to flag offering, restore event handler after hiding popup
		if ((this.callingItem) && (this.callingItem.id)) {
			if (this.callingItem.id == 'linkOfferingFlag') {
				var offeringID = this.callingItem.className;
				Event.observe($('linkOfferingFlag'), 'click', function(){
					adobe.marketplace.popupManager.launchPopup('flagOffering', this, function(){
						adobe.marketplace.PopupContent_Flag.flagInit('flagOffering', offeringID, 'offering');
					});
				});
			}
		}
	},
	/**
	 * Hides all Popup divs.  Used to establish baseline before displaying specific divs
	 * @see #hideAllButtons
	 */
	hideAll: function(){
		$('popup'+this.id).getElementsByClassName('content')[0].style.display="none";
		$('popup'+this.id).getElementsByClassName('loading')[0].style.display="none";
		$('popup'+this.id).getElementsByClassName('complete')[0].style.display="none";
		$('popup'+this.id).getElementsByClassName('dynamic')[0].style.display="none";
		this.hideAllButtons();
	},
	/**
	 * Hides all Popup Button divs.  Used to establish baseline before displaying specific button divs
	 */
	hideAllButtons: function(){
		$('popup'+this.id).getElementsByClassName('popupButtons')[0].style.display="none";
		$('popup'+this.id).getElementsByClassName('popupOkButton')[0].style.display="none";
		$('popup'+this.id).getElementsByClassName('popupOkReturnButton')[0].style.display="none";
	},
	/**
	 * Returns the Popup to it's base/original state
	 * @see #hideAll
	 * @see #showPopupButtons
	 */
	resetLayout: function(){
		this.hideAll();
		$('popup'+this.id).getElementsByTagName('form')[0].reset();
		$('popup'+this.id).getElementsByClassName('dynamic')[0].innerHTML="";
		$('popup'+this.id).getElementsByClassName('content')[0].style.display="block";
		this.showPopupButtons();
	},
	/**
	 * Returns the Popup to it's base layout without reseting it's form state
	 * @see #hideAll
	 * @see showPopupButtons
	 */
	returnLayout: function(){
		this.hideAll();
		$('popup'+this.id).getElementsByClassName('dynamic')[0].innerHTML="";
		$('popup'+this.id).getElementsByClassName('content')[0].style.display="block";
		this.showPopupButtons();
	},
	/**
	 * Displays Popup 'loading' div
	 * @see #hideAll
	 */
	showLoading: function(){
		this.hideAll();
		$('popup'+this.id).getElementsByClassName('loading')[0].style.display="block";
	},
	/**
	 * Displays Popup 'dynamic' div with Error string, and OK button enabled to
	 * return to form for further attempts at submission
	 * @see #hideAll
	 * @see #showOkReturnButton
	 * @param {String} errorStr HTML formatted string for insertion into 'dynamic' div
	 */
	showErrors: function(errorStr){
		this.hideAll();
		var errorsdiv = $('popup'+this.id).getElementsByClassName('dynamic')[0];
		errorsdiv.innerHTML = errorStr;
		errorsdiv.style.display="block";
		this.showOkReturnButton();
	},
	/**
	 * Displays Popup 'dynamic' div with Custom string and OK button to close Popup
	 * @see #hideAll
	 * @see #showOkButton
	 * @param {Object} customStr
	 */
	showCustom: function(customStr){
		this.hideAll();
		var customdiv = $('popup'+this.id).getElementsByClassName('dynamic')[0];
		customdiv.innerHTML = customStr;
		customdiv.style.display="block";
		this.showOkButton();
	},
	/**
	 * Displays Popup 'complete' div and Ok button to close Popup
	 * @see #hideAll
	 * @see #showOkButton
	 */
	showComplete: function(){
		this.hideAll();
		$('popup'+this.id).getElementsByClassName('complete')[0].style.display="block";
		this.showOkButton();
	},
	/**
	 * Display Ok Button div (closes Popup on click)
	 */
	showOkButton: function(){
		$('popup'+this.id).getElementsByClassName('popupOkButton')[0].style.display="block";
	},
	/**
	 * Display Ok Return Button div (calls returnLayout on click - returns to form without reseting)
	 */
	showOkReturnButton: function(){
		$('popup'+this.id).getElementsByClassName('popupOkReturnButton')[0].style.display="block";
	},
	/**
	 * Display Popup Buttons div (Custom buttons added on creation)
	 */
	showPopupButtons: function(){
		$('popup'+this.id).getElementsByClassName('popupButtons')[0].style.display="block";
	}
});
/**
 * Textstring prototype template for Popup initialization.
 */
adobe.marketplace.tempStr = "<div id=\"popup#{id}\" class=\"popupStandard #{classNameStr}\"><a name=\"popupAnchor#{id}\" class=\"popupAnchor\"></a>";
adobe.marketplace.tempStr+= "  <div class=\"blackBottomBorder\"><div class=\"blockHeader blockHeader21\">";
adobe.marketplace.tempStr+= "    <h3 class=\"headerText sifrTextOnDemand\">#{title}</h3>";
adobe.marketplace.tempStr+= "    <div class=\"headerLink\"><a href=\"javascript:void(0);\" onclick=\"adobe.marketplace.popupManager.hidePopup('#{id}')\"><img src=\"/images/marketplace/popup_close.gif\" alt=\"x\" width=\"7\" height=\"8\" border=\"0\" class=\"popupClose\"></a></div>";
adobe.marketplace.tempStr+= "  </div></div>";
adobe.marketplace.tempStr+= "  <div class=\"content\">";
adobe.marketplace.tempStr+= "    <form name=\"popupForm#{id}\" id=\"popupForm#{id}\">#{content}</form>";
adobe.marketplace.tempStr+= "  </div>";
adobe.marketplace.tempStr+= "  <div class=\"initialHide loading\">Loading ...</div>";
adobe.marketplace.tempStr+= "  <div class=\"initialHide complete\"><p>#{confirmation}</p></div>";
adobe.marketplace.tempStr+= "  <div class=\"initialHide dynamic\"></div>";
adobe.marketplace.tempStr+= "  <div class=\"popupButtons\"></div>";
adobe.marketplace.tempStr+= "  <div class=\"initialHide popupOkButton\"></div>";
adobe.marketplace.tempStr+= "  <div class=\"initialHide popupOkReturnButton\"></div>";
adobe.marketplace.tempStr+= "</div>";
adobe.marketplace.Popup.htmlTemplate = new Template(adobe.marketplace.tempStr)

/**
 * Manages creation/retrieval/method-calls for adobe.marketplace.Popup objects.
 * @see adobe.marketplace.Popup
	* @constructor
 */
adobe.marketplace.PopupManager = Class.create({
	/**
	 * Initialize storage list
	 */
	initialize: function(){
		this.popupList = new Array();
	},
	/**
	 * Locate and Return popup in popupList or alert with error
	 * @param {String} id Unique string for identifying Popup
	 */
	findPopup: function(id){
		var currentPopup = this.popupList.find(function(popup){return popup.id == id});
		if(!currentPopup){ //Error - shouldn't happen - Will only fire if code attempts to call a popup that has not been initialized.
			adobe.marketplace.popupManager.showCenterPopup("generic");
			adobe.marketplace.popupManager.showPopupCustom("generic","There has been a system problem. Please try again later.");
		} else {
			return currentPopup;
		}
	},
	/**
	 * Create Popup and add to storage list - alert error if name conflict
	 * @see adobe.marketplace.Popup
	 * @param {String} id Unique label/identifier for Popup
	 * @param {String} title Label displayed in Popup title bar
	 * @param {String} classNameStr CSS class(es) to be assigned to Popup
	 * @param {String} content HTML to be inserted into 'content' div of popup
	 * @param {Array} buttons Array of adobe.marketplace.PopupButton for insertion into 'popupButtons' div
	 * @param {String} confirmation Message to be displayed upon successful submission
	 */
	addPopup: function(id, title, classNameStr, content, buttons, confirmation){
		if (!this.popupList.find(function(popup){return popup.id == id})) {
			this.popupList.push(new adobe.marketplace.Popup(id, title, classNameStr, content, buttons, confirmation));
		} else { //Error - shouldn't happen - Will only fire if code attempts to initialize a popup already created.
			adobe.marketplace.popupManager.showCenterPopup("generic");
			adobe.marketplace.popupManager.showPopupCustom("generic","There has been a system problem. Please try again later.");
		}
	},
	/**
	 * Confirm popup exists and show
	 * @see #findPopup
	 * @param {String} id Unique label/identifier for Popup
	 * @param {Object} callingItem Calling link - passed for disabling while popup displayed
	 * @param {Object} action Function to be called upon successful creation of popup (used for form initialization)
	 */
	launchPopup: function(id,callingItem,action){
		if(this.findPopup(id))this.findPopup(id).show(callingItem,action);
	},
	showCenterPopup: function(id){
		if(this.findPopup(id))this.findPopup(id).showCenter();
	},
	/**
	 * Confirm popup exists and hide
	 * @see #findPopup
	 * @param {String} id Unique label/identifier for Popup
	 */
	hidePopup: function(id){
		if(this.findPopup(id))this.findPopup(id).hide();
	},
	/**
	 * Confirm popup exists and return layout to base state with all data reset
	 * @see #findPopup
	 * @param {String} id Unique label/identifier for Popup
	 */
	resetPopupLayout: function(id){
		if(this.findPopup(id))this.findPopup(id).resetLayout();
	},
	/**
	 * Confirm popup exists and return layout to base state without reseting data
	 * @see #findPopup
	 * @param {String} id Unique label/identifier for Popup
	 */
	returnPopupLayout: function(id){
		if(this.findPopup(id))this.findPopup(id).returnLayout();
	},
	/**
	 * Confirm popup exists and show Loading dialog
	 * @see #findPopup
	 * @param {String} id Unique label/identifier for Popup
	 */
	showPopupLoading: function(id){
		if(this.findPopup(id))this.findPopup(id).showLoading();
	},
	/**
	 * Confirm popup exists and show Error messages
	 * @param {String} id Unique label/identifier for Popup
	 * @param {String} errorStr HTML formatted string for display in Popup
	 */
	showPopupErrors: function(id, errorStr){
		if(this.findPopup(id))this.findPopup(id).showErrors(errorStr);
	},
	/**
	 * Confirm popup exists and show custom message
	 * @param {String} id Unique label/identifier for Popup
	 * @param {String} customStr HTML formatted string for display in Popup
	 */
	showPopupCustom: function(id, customStr){
		if(this.findPopup(id))this.findPopup(id).showCustom(customStr);
	},
	/**
	 * Confirm popup exists and show complete dialog
	 * @param {String} id Unique label/identifier for Popup
	 */
	showPopupComplete: function(id){
		if(this.findPopup(id))this.findPopup(id).showComplete();
	},
	/**
	 * Hide popup buttons
	 */
	hidePopupButtons: function(id){
		if(this.findPopup(id))this.findPopup(id).hideAllButtons();
	}
});
/**
 * Create instance of PopupManager for use.
 */
adobe.marketplace.popupManager = new adobe.marketplace.PopupManager();

adobe.marketplace.PopupContent_Generic = Class.create({
	initialize: function(id){
		this.id = id;
		adobe.marketplace.popupManager.addPopup(this.id,"","","popup_generic",[], 'Your item has been submitted.');
	}
})
/**
 * Creation of Popup for flagging offerings, reviews, and comments
 * @constructor
 * @see adobe.marketplace.PopupButton
 * @see adobe.marketplace.popupManager
 */
adobe.marketplace.PopupContent_Flag = Class.create({
	/**
	 * Initialize Object
	 * @param {String} id Unique label/identifier for Popup
	 * @param {String} type Type of item to be flagged: offering, review, or comment
	 * @param {String} type Type of item to be flagged: offering, review, or comment
	 */
	initialize: function(id, type, offeringId){
		this.id = id;
		this.type = type;
		this.offeringId = offeringId;
		this.confirmation = 'Thank you. Your flag will be reviewed by a Marketplace administrator.';
  		this.data = {
			type: this.type,
			reasonsSelect: adobe.marketplace.flagReasonsSelectOptions
		}
		adobe.marketplace.tempStr = "<p>Please let us know why this #{type} needs administrator attention.</p>";
		adobe.marketplace.tempStr+= "<select name=\"REASON_CODE\" class=\"flagSelect adobeSelectOnGrey\">";
		adobe.marketplace.tempStr+= "  <option value=\"\">Select reason for flagging</option>";
		adobe.marketplace.tempStr+= "  #{reasonsSelect}";
		adobe.marketplace.tempStr+= "</select><br />";
		adobe.marketplace.tempStr+= "<textarea name=\"REASON_TEXT\" class=\"flagText\" maxlength=\"250\"></textarea>";
		adobe.marketplace.tempStr+= "<input type=\"hidden\" name=\"ITEMID\" class=\"flagID\" />";
		adobe.marketplace.tempStr+= "<input type=\"hidden\" name=\"type\" value=\"#{type}\" />";
		adobe.marketplace.tempStr+= "<input type=\"hidden\" name=\"method\" value=\"flagItem\" />";
		this.htmlTemplate = new Template(adobe.marketplace.tempStr);
  		this.flagContent = this.htmlTemplate.evaluate(this.data);
  		this.buttons = [
			new adobe.marketplace.PopupButton("Cancel", function(){ //Cancel button to close Popup
				$('popup'+this.id).getElementsByTagName('form')[0].reset();
				adobe.marketplace.popupManager.hidePopup(this.id);
			}.bind(this)),
			new adobe.marketplace.PopupButton("Flag", function(){ //Flag button to submit form
				adobe.marketplace.popupManager.showPopupLoading(this.id);
				if(!($('popup'+this.id).select('TEXTAREA[name="REASON_TEXT"]').first().value.length > 250)){ // Tmp Fix for #99058
					new Ajax.Request(adobe.marketplace.AJAXURL,{
						parameters: $('popupForm'+this.id).serialize(true),
						method: 'post',
						onSuccess: function(response){
							var responseObj = response.responseText.stripTags().evalJSON();
							if((responseObj.ERRORS.MISSING_ARGUMENTS.length > 0)||(typeof(responseObj.ERRORS.RESULT) != "undefined")){
								var errorStr = "";
								if (responseObj.ERRORS.MISSING_ARGUMENTS.length > 0) {
									errorStr += "You have not filled out all the required fields.<ul>";
									responseObj.ERRORS.MISSING_ARGUMENTS.each(function(errorMsg){
										switch (errorMsg.toUpperCase()) {
											case "USERID":
											case "TYPE":
											case "ITEMID": //Error - shouldn't happen
												errorStr += "<!-- error: " + errorMsg + "-->";
											break;
											case "REASON_CODE":
												errorStr += "<li>Please select a reason for flagging this item.</li>";
											break;
											case "REASON_TEXT":
												errorStr += "<li>Please enter a description of why this needs administrator attention.</li>";
											break;
										}
									});
									errorStr += "</ul>";
								}
								if(typeof(responseObj.ERRORS.RESULT) != "undefined"){
									errorStr += "There was an error in submitting your flag.  Please try again."
								}
								adobe.marketplace.popupManager.showPopupErrors(this.id, errorStr);
							} else { //Successful submission
								adobe.marketplace.track(type+'Flag',this.offeringId,'');
								adobe.marketplace.popupManager.showPopupComplete(this.id);
							}
						}.bind(this),
						onFailure: function(){ //Server error
							adobe.marketplace.popupManager.showPopupErrors(this.id, "There was an error in your submission, please try again.");
						}.bind(this)
					});
				} else {
					adobe.marketplace.popupManager.showPopupErrors(this.id, "You have exceeded the maximum flag length.");
				}
	  	}.bind(this))
		];
		this.title;
		switch(this.type){
			case "offering":
				this.title = "FLAG THIS OFFERING"
			break;
			case "review":
				this.title = "FLAG THIS REVIEW"
			break;
			case "comment":
				this.title = "FLAG THIS COMMENT"
			break;
		}
		adobe.marketplace.popupManager.addPopup(this.id,this.title,"",this.flagContent,this.buttons, this.confirmation);
  }
});
/**
 * Called on launch of popup to set item id
 * @param {String} popupId Unique label/identifier for Popup
 * @param {Int} itemId Offering/Review/Comment Id to be flagged
 * @param {String} type Offering/review/comment being flagged
 * @param {Int} offeringId Associated offering
 */
adobe.marketplace.PopupContent_Flag.flagInit = function(popupId, itemId, type){
	$('popup'+popupId).getElementsByClassName('flagID')[0].value=itemId;
}
/**
 * Creation of Popup for confirmation of removal of a review or comment, and submit to server when confirmed.
 * @param {String} popupId Unique label/identifier for Popup
 * @param {String} type Review or Comment
 */
adobe.marketplace.PopupContent_ConfirmDelete = Class.create({
	initialize: function(id, type){
  	this.offeringID = $('linkOfferingFlag').readAttribute('class');
	this.marketplaceID = $('marketplaceId').innerHTML;
	this.id = id;
  	this.type = type;
  	this.data = {
  		type: this.type
  	}
		adobe.marketplace.tempStr = "<p>Are you sure you wish to remove this item?</p>";
		adobe.marketplace.tempStr+= "<input type=\"hidden\" name=\"REVIEWID\" class=\"removeID\" />";
		adobe.marketplace.tempStr+= "<input type=\"hidden\" name=\"type\" class=\"removeType\" />";
		adobe.marketplace.tempStr+= "<input type=\"hidden\" name=\"method\" class=\"removeItem\" value=\"removeItem\" />";
		adobe.marketplace.tempStr+= "<input type=\"hidden\" name=\"parentId\" class=\"removeParentId\" />";
  	this.htmlTemplate = new Template(adobe.marketplace.tempStr);
  	this.flagContent = this.htmlTemplate.evaluate(this.data);
  	this.buttons = [
			new adobe.marketplace.PopupButton("Yes", function(){
				adobe.marketplace.popupManager.showPopupLoading(this.id);
				this.formObj = $('popupForm'+this.id).serialize(true);
				new Ajax.Request(adobe.marketplace.AJAXURL,{
					parameters: this.formObj,
					method: 'post',
					onSuccess: function(response){
						var responseObj = response.responseText.stripTags().evalJSON();
						var requiresLogin = false;
						if((responseObj.ERRORS.MISSING_ARGUMENTS.length > 0)||(typeof(responseObj.ERRORS.RESULT)!="undefined")){
							if (responseObj.ERRORS.MISSING_ARGUMENTS.length > 0) {
								responseObj.ERRORS.MISSING_ARGUMENTS.each(function(errorMsg){
									switch (errorMsg.toUpperCase()) {
										case "USERID":
											requiresLogin = true;
											break;
										default:
											//Do Nothing
											break;
									}
								});
							}	
							if(requiresLogin){
								adobe.marketplace.login();
								return false;
							}
							errorStr = "There has been an error.";//Error - shouldn't happen
							adobe.marketplace.popupManager.showPopupErrors(this.id, errorStr);
						} else { //Successful submission
							try{
								switch(this.formObj.type){
									case "review":
										this.itemDiv = $(this.formObj.type + 'Block'+this.formObj.REVIEWID);
										if (adobe.marketplace.reviewController.reviewCount == 1) {
											adobe.marketplace.toggleDisplay($$('.paginateBar')[0]);
											$("reviewAddBlock").select(".addTextArea")[0].value="";
											adobe.marketplace.toggleDisplay($("reviewAddBlock"));
											Event.stopObserving($('linkReviewCancel'),'click');
											adobe.marketplace.toggleDisplay($("reviewAddBlock").select(".cancelButton")[0]);
										} else {
											adobe.marketplace.toggleDisplay($("reviewLinkAdd"));
										}
										$(this.itemDiv.parentNode).remove();
										adobe.marketplace.reviewController.reviewCount--;
									break;
									case "comment":
										this.itemDiv = $(this.formObj.type + this.formObj.REVIEWID);
										adobe.marketplace.toggleDisplay($("commentLinkAdd"+this.formObj.REVIEWID));
										this.itemDiv.remove();
										// update number of comments or hide comments hide or show link if none
										// Bug 96308 : Set comments count in innerhtml for show comments element.
										var commentsHideSpan = $('commentCtrlHide' + this.formObj.parentId);
										var commentsShowSpan = $('commentCtrlShow' + this.formObj.parentId);
										var newNumComments = adobe.marketplace.reviewController.commentsSetCounts.get('commentSet' + this.formObj.parentId) - 1;
										adobe.marketplace.reviewController.commentsSetCounts.set('commentSet' + this.formObj.parentId, newNumComments);
										if (newNumComments == 0) {
											adobe.marketplace.toggleDisplay(commentsHideSpan);
										} else {
											commentsHideSpan.select('span')[0].innerHTML = newNumComments;
											commentsShowSpan.select('span')[0].innerHTML = newNumComments;
										}
									break;
								}
								adobe.marketplace.popupManager.hidePopup(this.id);
								var reviewsLink = "http://"+window.location.hostname+"/cfusion/marketplace/index.cfm?event=marketplace.offering.reviews&marketplaceid="+this.marketplaceID+"&offeringid="+this.offeringID;
								triggerSubmit(reviewsLink);
							}catch(err){
								adobe.marketplace.popupManager.showPopupErrors(this.id, "There was an error in your submission, please try again.");
							}
						}
					}.bind(this),
					onFailure: function(){ //Server error
						adobe.marketplace.popupManager.showPopupErrors(this.id, "There was an error in your submission, please try again.");
					}.bind(this)
				});
	  	}.bind(this)),
			new adobe.marketplace.PopupButton("No", function(){
				adobe.marketplace.popupManager.hidePopup(this.id);
	  	}.bind(this))
		];
  	this.title = "ARE YOU SURE?"
	adobe.marketplace.popupManager.addPopup(this.id, this.title, "", this.flagContent, this.buttons);
  }
});
/**
 * Called on launch of popup to set item id
 * @param {String} popupId Unique label/identifier for Popup
 * @param {Int} removeId Review/Comment Id to be deleted
 * @param {String} type Review or Comment
 */
adobe.marketplace.PopupContent_ConfirmDelete.init = function(popupId, removeId, type, parentId){
	$('popup'+popupId).getElementsByClassName('removeID')[0].value=removeId;
	$('popup'+popupId).getElementsByClassName('removeType')[0].value=type;
	$('popup'+popupId).getElementsByClassName('removeParentId')[0].value=parentId;
}

triggerSubmit = function (url){
   Spry.Utils.loadURL('POST', url, true, ReturnWithEffect, {postData: '', headers: {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"}});
} 
 
ReturnWithEffect = function (req){
   //We use xhRequest to received notification from server side, usually the process file will return with an echo/write.
   var result = req.xhRequest.responseText; 
   var offeringId = document.getElementById("offeringId").innerHTML;
   var publisherId = document.getElementById("publisherId").innerHTML;
   
   document.getElementById("offeringReviews").innerHTML = '';
   document.getElementById("offeringReviews").innerHTML = result;
   FadeEfx.start();

	adobe.marketplace.addClickListeners(offeringId, publisherId);
	
	var userRating = document.getElementById("userRating").innerHTML;
	var ratingCount = document.getElementById("ratingCount").innerHTML;
	var avgRating = document.getElementById("avgRating").innerHTML;
	var currentUserId = document.getElementById("currentUserId").innerHTML;
	
	if(document.getElementById('currentUserReviewId').innerHTML != '')
	{
		var currentUserReviewId = document.getElementById('currentUserReviewId').innerHTML;

		var ratingWidgetOfferingEditFormRating = new adobe.marketplace.RatingWidget("offeringEditFormRating"+offeringId+'_'+currentUserReviewId, {
		ratingValue: userRating,
		rateHandler:function(){
			$("offeringEditFormRating"+offeringId+'_'+currentUserReviewId+"wrapper").select(".ratingValueInput")[0].value = ratingWidgetOfferingEditFormRating.spryWidget.getValue();
		}
		},{
			itemid:offeringId,
			uniqueId:"offeringEditFormRating"+offeringId+'_'+currentUserReviewId,
			userId:currentUserId,
			layout:"userLoggedInForm"
		});

		var ratingWidgetOfferingRating = new adobe.marketplace.RatingWidget("offeringRating"+offeringId+'_'+currentUserReviewId, {
		ratingValue: userRating,
		rateHandler:function(){
			ratingWidgetOfferingRating.submitRating();
			if(typeof(ratingWidgetOfferingEditFormRating) != 'undefined')
				ratingWidgetOfferingEditFormRating.spryWidget.setValue(ratingWidgetOfferingRating.spryWidget.getValue());
		}
		},{
			itemid:offeringId,
			uniqueId:"offeringRating"+offeringId+'_'+currentUserReviewId,
			userId:currentUserId,
			layout:"userLoggedInForm"
		});
	}

	var ratingWidgetOfferingRating2 = new adobe.marketplace.RatingWidget("offeringRating"+offeringId, {
	ratingValue: userRating,
	rateHandler:function(){
		if(typeof(ratingWidgetOfferingRating) != 'undefined')
			ratingWidgetOfferingRating.spryWidget.setValue(ratingWidgetOfferingRating2.spryWidget.getValue());
		if(typeof(ratingWidgetOfferingEditFormRating) != 'undefined')
			ratingWidgetOfferingEditFormRating.spryWidget.setValue(ratingWidgetOfferingRating2.spryWidget.getValue());
	}
	},{
		itemid:offeringId,
		uniqueId:"offeringRating"+offeringId,
		userId:currentUserId,
		layout:"userLoggedInForm"
	});
	if(ratingCount != '' && ratingCount > 0)
	{
		$("offeringRating"+offeringId+"wrapper").select(".userRatingRankValue")[0].innerHTML = adobe.marketplace.RatingWidgetManager.formatRate(userRating);
		$("offeringRating"+offeringId+"wrapper").select(".userRatingVotesValue")[0].innerHTML = ratingCount;
		$("offeringRating"+offeringId+"wrapper").select(".userRatingAverageValue")[0].innerHTML = adobe.marketplace.RatingWidgetManager.formatRate(avgRating);
	}
	else
	{
		$("offeringRating"+offeringId+"wrapper").select(".userRatingRankValue")[0].innerHTML = adobe.marketplace.RatingWidgetManager.formatRate(0);
		$("offeringRating"+offeringId+"wrapper").select(".userRatingVotesValue")[0].innerHTML = 0;
		$("offeringRating"+offeringId+"wrapper").select(".userRatingAverageValue")[0].innerHTML = adobe.marketplace.RatingWidgetManager.formatRate(0);
	}
	
	var ratingWidgetOfferingFormRating = new adobe.marketplace.RatingWidget("offeringFormRating"+offeringId, {
	ratingValue: userRating,
	rateHandler:function(){
		$("offeringFormRating"+offeringId+"wrapper").select(".ratingValueInput")[0].value = ratingWidgetOfferingFormRating.spryWidget.getValue();
	}
	},{
		itemid:offeringId,
		uniqueId:"offeringFormRating"+offeringId,
		userId:currentUserId,
		layout:"userLoggedInForm"
	});

} 