﻿// Dean Edwards' IE6 detect
var IE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;

// Set everything up  when the window is done loading
Event.observe( window, 'load', function() {
	setTimeout( function(){
		$$('div.gallery div.pager span').each(function(element) {
			element.observe('click', onPagerButtonClick.bind(this, element));
		}.bind(this));
		
		$$('.calendar').each(function(calendar) {
			$(calendar.id + '_goButton').observe('click', onCalendarGoButtonClick.bind(this, calendar));
		}.bind(this));
		
		$$('.moreLink').each(function(element) {
			element.observe('click', onShowMoreLinkClick.bind(this, element));
		}.bind(this));
			
		$$('.feedbackButton').each(function(button) {
			button.observe('click', onFeedbackButtonClick.bind(this, button));
		}.bind(this));
		
		$$('.contentFeedback').each( function(f) {
			new AvenetPublic.GrowBox(f);
		});
		
		$$('a.intermediate').each( function(link){
			Event.observe( link, 'click', function(ev){
				//var targetHost = this.href;
				var targetHost = this.href.match(/(^|\/\/)(([a-zA-Z0-9]+\.?)+)($|\/)/)[2];
				var message = lpack.IntermediateWarning.replace("{0}", window.location.host).replace("{1}", targetHost);
				if( !confirm(message) )
					ev.stop();
			});
		});
		
	}, 1);
});

function onPagerButtonClick(element) {
	function togglePages(pages, className, selectedpager) {
		pages.each(function(page) {
			if(page.hasClassName(className)) {
				page.removeClassName('hidden');
			} else {
				page.addClassName('hidden');
			}
		});
		
		element.up('div.pager').select('span.pagerPage').each(function(page) {
			if(page.hasClassName('selected'))
				page.removeClassName('selected');
		});
		
		selectedpager.addClassName('selected');
	}
	
	var pages = element.up('div.gallery').select('div.page');
	var curPage = pages.find(function(page) {
		return !page.hasClassName('hidden');
	}.bind(this));
	var pageNum = curPage.className.split('_')[1];
		
	if(element.hasClassName('pagerPrevious')) {
		if(pageNum > 1) {
			pageNum--;
			togglePages(pages, 'page_' + pageNum, element.up('div.pager').select('span.page_' + pageNum)[0]);
		}
	} else if(element.hasClassName('pagerNext')) {
		if(pageNum < element.up('div.pager').select('span.pagerPage').length) {
			pageNum++;
			togglePages(pages, 'page_' + pageNum, element.up('div.pager').select('span.page_' + pageNum)[0]);
		}
	} else {
		togglePages(pages, element.className.split(' ')[1], element);
	}
}

function onCalendarGoButtonClick(calendar) {
	location.href = '?CollectorId=' + calendar.id + '&year=' + $(calendar.id + '_year').value + '&month=' + $(calendar.id + '_month').value;
}

function onShowMoreLinkClick(element) {
	// whis is this supposed to do?
	//element.up('.content').down('.moreContent').toggle();
}

function onFeedbackButtonClick(button) {
	var contentId = null;
	var pageContentId = null;
	var collectorId = null;
	var formId = null;
	
	var parent = $(button).up('.content');
	parent.className.split(' ').each(function(cn) {
		if (cn.indexOf('contentId') == 0)
			contentId = cn.substr('contentId'.length  + 1);
		else if (cn.indexOf('pageContentId') == 0)
			pageContentId = cn.substr('pageContentId'.length + 1);
		else if (cn.indexOf('collectorId') >= 0)
			collectorId = cn.substr('collectorId'.length + 1);
		else if (cn.indexOf('formId') == 0)
			formId = cn.substr('formId'.length + 1);
	});
	new AvenetPublic.Popup({ 
		formName: 'feedbackEntry', 
		formTitle: 'Feedback',
		
		onLoaded: function(form) {
			var showContentSuggestions = true;
			var feedbackConfig = parent.feedbackConfig;
			var formDiv = $(form).down('#step2').down('.padder');
			
			if (feedbackConfig.allowSuggestions == "true" && pageInfo.authUser && formId != "UploadImage" && formId != "UploadFile" && formId != 'IMSLodeStar') {
				Avenet.Forms.fetchForm(formId, formDiv, { 
					ignoreDefaultShell: true,
					contentId: contentId,
					isContentForm: true,
					callbackScope: this, 
					isPopupForm: true,
					
					beforePrepareForm: function(formHtml) {
						// Remove any linkbuilders. feedback users can't alter them.
						$(formHtml).select('.linkBuilderFrame').each(function(frame) {
							frame.up('.row').remove();
						});
					},
					onSuccess: function() {
						var reportConfig = parent.reportConfig;
						
						// Hide fields for editing that the user can't currently see.
						for (a in reportConfig) {
							var fieldName = formId + "_" + a;
							var field = $(form).down('#' + fieldName);
							
							if (field && reportConfig[a] == "off")
								field.up('.row').style.display = "none";
						}
					}
				});
			}
			else {
				$(form).down('#step2').remove();
			}
		},
		
		onRetrieved: function(popupForm) {
			var feedbackConfig = parent.feedbackConfig;
			
			popupForm.form.down('.minRatingLabel').innerHTML = feedbackConfig.minRatingLabel;
			popupForm.form.down('.maxRatingLabel').innerHTML = feedbackConfig.maxRatingLabel;
			popupForm.form.down('#feedbackEntry_ScaleLabel').innerHTML = feedbackConfig.scaleLabel;
			
			if (feedbackConfig.showScale == "false") {
				popupForm.form.down('#feedbackEntry_ScaleGroup').style.display = 'none';
			}
			
			popupForm.form.down('#feedbackEntry_ContentTitle').innerHTML = feedbackConfig.title;
			popupForm.form.down('#feedbackEntry_YesNoLabel').innerHTML = feedbackConfig.yesNoQuestion;
			popupForm.form.down('#feedbackEntry_YesNoYesAnswerLabel').innerHTML = feedbackConfig.yesNoYesAnswer;
			popupForm.form.down('#feedbackEntry_YesNoNoAnswerLabel').innerHTML = feedbackConfig.yesNoNoAnswer;
			popupForm.form.down('#feedbackEntry_UserIdGroup').style.display = pageInfo.authUser ? 'none' : 'block';
			
			if (feedbackConfig.showYesNo == "false") {
				popupForm.form.down('#feedbackEntry_YesNoGroup').style.display = 'none';
			}
			
			if (feedbackConfig.showNotes == "false") {
				popupForm.form.down('#feedbackEntry_NotesGroup').style.display = 'none';
			}
			
			if (!pageInfo.authUser) {
				var recaptchaDiv = document.createElement("div");
				recaptchaDiv.style.className = 'recaptchaDiv';
				popupForm.form.appendChild(recaptchaDiv);
				
				// TODO: Make sure to use Avenet public key here.
				Recaptcha.create(recaptchaPK, recaptchaDiv, {
					tabindex: 50000,
					callback: Recaptcha.focus_response_field,
					theme: "clean",
					callback: function() {
						var errorDiv = new Element("div");
						errorDiv.update('<span class="formError" id="feedbackEntry_recaptcha_response_fieldErrors"><ul class="errorDisplay"></ul></span>');
						$('recaptcha_area').insert(errorDiv);
					}
				});
				
				if( IE6 ) {
					setTimeout( function() {
						Recaptcha.reload();
					}, 3000 );
				}
			}
		},
		
		onOk: function(popupForm) {
			var feedback = Form.serialize(document.body.down('#step1'));
			
			if (document.body.down('#recaptcha_area')) {
				$A(Form.serialize(document.body.down('#recaptcha_area'))).each(function(field) {
					feedback.push(field);
				});
			}
			
			var contentSuggestion = null;
			
			if (document.body.down('#step2')) {
				contentSuggestion = Form.serialize(document.body.down('#step2'));
			}
			
			new Ajax.Request(Avenet.ServiceUrls.feedbackService + "/CreateFeedback", {
				postBody: $JSON({ 
					hash: feedback, 
					contentSuggestion: contentSuggestion,
					siteId: pageInfo.siteId, 
					pageContentId: pageContentId,
					contentId: contentId,
					collectorId: collectorId
				}),
				onSuccess: function ( transport ) {
				    var response = transport.responseText.evalJSON(true);
				    if( response.Status == true ) {
					    alert("Feedback message sent.");
            			popupForm.close();
				    }
				    else {
					    var errors = unpackDictionary(response.ErrorMessages);
    					
					    if ($H(errors).keys().length) {
						    var message = "";
						    $H(errors).each(function (err) {
							    if (err[0] == 'reCAPTCHA') message = (err[1]);
						    });
						    if (message.length > 0) {
						        alert(message);
						    }
						}
						Recaptcha.reload();
				    }
			    }
			});
		}
	}).show();
}

if (!AvenetPublic) var AvenetPublic = {};

AvenetPublic.Popup = Class.create({
	mask: null,
	
	initialize: function(config) {
		this.config = config;
	},
	show: function() {
		this.maskBody();
		Avenet.Forms.fetchForm(this.config.formName, $('popupBody'), { 
			onSuccess: function() {
			
				$('formPopupTitle').innerHTML = this.config.formTitle;
				$('doItButton').onclick = this.okClicked.bind(this);
				$('cancelButton').onclick = this.cancelClicked.bind(this);
				
				this.form = $('popupBody').select('form')[0];
				
				if (this.config.onRetrieved) 
					this.config.onRetrieved(this);
			},
			 
			callbackScope: this, 
			elToShow: $('popupFrame'),
			isPopupForm: true,
			disabledByDefault: false,
			
			beforePrepareForm: function(form) {
				if (this.config.onLoaded)
					this.config.onLoaded(form);
			}
		});
	},
	close: function() {
		Avenet.Forms.unloadMagicBoxes(this.form, $('popupBody'));
		$('popupFrame').style.display = 'none';
		$('popupBody').innerHTML = '';
		this.unmaskBody();
	},
	okClicked: function() {
		this.config.onOk ? this.config.onOk(this) : this.close();
	},
	cancelClicked: function() {
		this.close();
	},
	
	// utility stuff
	maskBody: function() {
		this.mask = new Element('div', { 'class':'bodyMask' }).setStyle({
			height: document.body.getHeight() + 'px',
			opacity: 0.75
		});
		document.body.appendChild(this.mask);
	},
	unmaskBody: function() {
		this.mask.remove();
		this.mask = null;
	}
});

AvenetPublic.GrowBox = Class.create({
	element: null,
	toggle: null,
	showText: null,
	hideText: null,
	body: null,
	duration: 0.15,
	initialize: function(element) {
		this.element = element;
		this.toggle = element.down('.toggle');
		this.body = element.down('.body');
		if( !this.toggle || !this.body ) return null;
		this.showText = this.toggle.down('.show');
		this.hideText = this.toggle.down('.hide');
		Event.observe( this.toggle, 'click', this.toggleClicked.bind(this) );
		element.growBox = this;
	},
	toggleClicked: function(e) {
		if( this.isOpen() ) this.close();
		else this.open();
		e.stop();
	},
	isOpen: function() {
		return ( this.body.getHeight() > 0 );
	},
	close: function() {
		if( this.showText ) this.showText.setStyle({ display:'inline' });
		if( this.hideText ) this.hideText.setStyle({ display:'none' });
		this.element.removeClassName('open');
		new Effect.Morph( this.body, {
			style: { height: '0px'},
			duration: this.duration
		});
	},
	open: function() {
		this.element.addClassName('open');
		if( this.showText ) this.showText.setStyle({ display:'none' });
		if( this.hideText ) this.hideText.setStyle({ display:'inline' });
		new Effect.Morph( this.body, {
			style: { height: this.body.scrollHeight + "px" },
			duration: this.duration
		});
	}
});
