var feedbackForm = function(){
	this.currentDomain = window.location.hostname.split('.').slice(-2).join('.');
	var feedbackContainer = $('#feedback-popup-window'),
	feedbackContentHtml = '<div id="feedback-popup-window-inner-1"><div id="feedback-popup-window-inner-2"><div id="feedback-popup-window-inner-3"><div id="feedback-popup-window-inner-4"><div id="feedback-popup-header">Contact OpticsPlanet<span id="feedback-popup-close-button"></span></div><div id="feedback-popup-content"><div id="feedback-popup-content-main"><div id="feedback-popup-left-menu"><ul></ul></div><div id="feedback-popup-form-container"><div class="active"><p>Thanks for reaching out to OpticsPlanet. Our trained, professional customer service representatives are happy to help you in any way they can. <p><strong>Please select the option on the left which best describes your question so that we can help.</strong></p></div></div></div><span id="feedback-popup-contact-bg"></span><div id="feedback-popup-right-content"><div><span class="feedback-right-headers">Call Us</span></p><p><span>Toll-Free:</span> 800-504-5897</p><p><span>Intl.:</span> 847-513-6201</p><p><span>Fax</span> 847-919-3003</p></div><div><span class="feedback-right-headers">Hours of Operation</span><p>8AM-9PM CST Mon-Fri</p><p>9AM-5PM CST Sat-Sun</p></div><div><span class="feedback-right-headers">Address</span><p>OpticsPlanet, Inc.</p><p>3150 Commercial Avenue</p><p>Northbrook, Illinois 60062</p></div><div><span class="feedback-right-headers">Common Questions</span><p>How do I get <a href="http://www.opticsplanet.net/free-shipping.html" class="enable-contact-popup feedback-shipping-policy">free shipping</a>?</p><p>How do I make a <a href="http://www.opticsplanet.net/return-policy.html" class="enable-contact-popup feedback-rma-policies">return</a>?</p><p>Can you export this <a href="http://www.opticsplanet.net/export.html" target="_blank">product</a>?</p><p>How do I <a href="http://www.opticsplanet.net/orderstatus.html" class="enable-contact-popup feedback-check-status">track my order</a>?</p></div></div><div class="info-clear"></div></div></div></div></div></div><div id="feedback-popup-top-left" class="feedback-popup-corners"></div><div id="feedback-popup-top-right" class="feedback-popup-corners"></div><div id="feedback-popup-bottom-left" class="feedback-popup-corners"></div><div id="feedback-popup-bottom-right" class="feedback-popup-corners"></div>',
	feedbackContent = $(feedbackContentHtml),
	bigFadedBox = $('<div id="big-faded-box"></div>'),
	feedbackFadeOut = function(){
		// fade out the popup
		$(feedbackContainer).fadeOut(300, function(){
			if($('#feedback-popup-content-main-submit').hasClass('feedback-popup-form-success')){
				//removes and repopulates content after form submission
				feedbackContainer.removeClass('feedback-form-repopulated');
				feedbackContent.remove();
				feedbackContent = $(feedbackContentHtml);
			
				feedbackContainer.append(feedbackContent).addClass('feedback-form-repopulated');
				form.loadTopics(formTopics);
			}
		}).unbind();
	
		// Removes selected and hides selected content
		$('#feedback-popup-left-menu > ul > li.feedback-menu-link-selected > ul').stop(true).slideUp(300).find('li.feedback-menu-sublink-selected').removeClass('feedback-menu-sublink-selected');
		$('#feedback-popup-left-menu > ul > li.feedback-menu-link-selected').removeClass('feedback-menu-link-selected');
		$('#feedback-popup-form-container div.active').removeClass('active').fadeOut(300,function(){
			// Shows the generic caption after previous caption fades out
			$('#feedback-popup-form-container > div:first-child').children().show().parent().addClass('active').show();
		});
		$(bigFadedBox).fadeOut(300).remove();
		$(window).unbind();

		$('#page-container iframe').css('visibility', 'visible');
	},
	showPopup = function(){
		// show the popup
		var feedbackPosition = function (){
				var calcWidth = $(window).width() - feedbackContainer.width(),
				calcHeight = $(window).scrollTop() + 60;
			
				feedbackContainer.css({
					left: (calcWidth / 2) + 'px',
					top: calcHeight + 'px'
				});
				if (calcWidth < 0){
					feedbackContainer.css('left', '0px');
				}
				if (calcHeight < 0){
					feedbackContainer.css('top', '0px');
				}
			};

		// creates the faded box
		$('#feedback-popup-window').prependTo('body');
		$('body').prepend(bigFadedBox);
		//$('#big-faded-box').prependTo('body');
		$(bigFadedBox).css('opacity','0.8').fadeIn(300);
		
		$(window).resize(function (){
			feedbackPosition();
		});
		
		$('#page-container iframe').css('visibility', 'hidden');
		
		// fade in
		$('#big-faded-box').fadeIn(300);
		$(feedbackContainer).fadeIn(300);
		
		// init the centering
		feedbackPosition();
		
		// fade out and unbind
		$('span#feedback-popup-close-button').click(function(){feedbackFadeOut();});
		
	},
	checkFeedbackLink = function (popupTrigger) {
		// checks feedback link class & open to correct form
		var sectionToDisplay, sectionParent,
		linkClassString = ($(popupTrigger).attr('class')).match(/feedback(-[a-z]+)+/);
		
		if (linkClassString) {
			if ($('#feedback-popup-window').css('display') == 'none'){
				showPopup();
			}
			sectionToDisplay = $('#feedback-popup-left-menu li.'+linkClassString[0]);
			sectionParent = $(sectionToDisplay).parent();
			// checks to see if there are subitems
			if($(sectionParent).parent().hasClass('feedback-menu-link-subitems')){
			//checks to see if there are any selected items
				if (!$(sectionParent).parent().hasClass('feedback-menu-link-selected')){
					//closes any previously selected items
					$('#feedback-popup-left-menu > ul > li.feedback-menu-link-selected.feedback-menu-link-subitems').not(sectionParent.parent()).find('ul').slideUp(450, function(){
						$('#feedback-popup-left-menu > ul > li.feedback-menu-link-selected.feedback-menu-link-subitems').not(sectionParent.parent()).removeClass('feedback-menu-link-selected');
					});
					$('#feedback-popup-left-menu > ul > li.feedback-menu-link-selected').not('.feedback-menu-link-subitems').removeClass('feedback-menu-link-selected');
					$(sectionParent).hide().parent().addClass('feedback-menu-link-selected');
					
					//displays correct item
					$(sectionParent).find('li').show();
					$(sectionParent).slideDown(function(){$(sectionToDisplay).click();});
					
				} else {
					$(sectionToDisplay).click();
				}
			} else {
			$('#feedback-popup-left-menu > ul > li.feedback-menu-link-selected').removeClass('feedback-menu-link-selected');
				$(sectionToDisplay).click();
			}
		} else {
			showPopup();
		}
		return false;
	},
	feedbackLinkHandler = function(){
		// handles the feedback link click
		if(!($.browser.msie && $.browser.version == '6.0')){
			checkFeedbackLink(this);
			return false;
		}
	},
	checkSubmitButton = function(){
		// disables/enables submit button
		var feedbackButton = $('div#feedback-popup-content div.active .feedback-submit-button'),
		feedbackFieldGood = $('div#feedback-popup-content div.active span.feedback-input-good'),
		feedbackFieldRequired = $('div#feedback-popup-content div.active span.feedback-input-required');
		
		feedbackButton.addClass('feedback-button-disabled').attr('disabled', 'disabled');
		
		if(feedbackFieldRequired.size() != feedbackFieldGood.size()){
			feedbackButton.addClass('feedback-button-disabled').attr('disabled', 'disabled');
		} else if(feedbackFieldRequired.size() == feedbackFieldGood.size()){
			feedbackButton.removeClass('feedback-button-disabled').removeAttr('disabled');
		}
	};
	
	this.init = function(){
		var iframe,
		queue = [];
		
		// This has to be set both here and in iframe.html
		var currentDomain = this.currentDomain;
		document.domain = currentDomain;
		
		// We'll first replace $.ajax with a thin wrapper that both
		// loads our iframe tunnel and saves invocations until the
		// iframe is ready
		
		ajaxIframeTunnel = function(params) {
			if (!iframe) {
				// tunnel iframe page should be a bare bones html page that
				// includes a copy of jQuery, and sets document.domain
				// to 'example.com'
			
				iframe = $(document.createElement('iframe'))
				.load(function(){
					// Our prize: a version of $.ajax that can communicate safely
					// with our base domain
					// window.$.ajax = iframe.contentWindow.jQuery.ajax;
					var ajax = null;
			
					if (typeof this.contentWindow.jQuery !== 'undefined') {
						ajax = this.contentWindow.jQuery.ajax;
					}
			
					if (ajax !== null) {
						window.ajaxIframeTunnel = ajax;
					}
			
					// Flush queued $.ajax calls
					$.each(queue, function(_, params) {
						ajaxIframeTunnel(params);
					});
					
					queue = null;
				})
				.attr('src', 'http://feedback.' + currentDomain + '/ajax/tunnel-iframe')
				.attr('name', 'ajax-iframe')
				.addClass('feedback-file-attachment-iframe-hidden')
				.css('position', 'absolute')
				.appendTo('#feedback-popup-window');
			}
			
			// Save calls to $.ajax, execute when we're ready
			queue.push(params);
		};
	};

	// Create the feedback html
	$(feedbackContainer).append(feedbackContent);
	if($.browser.msie && parseFloat($.browser.version) < 8){
		$('#feedback-popup-content-main').before('<span id="feedback-popup-left-bg"></span>');
	}

	$(document).keydown(function(e) {
		// ESCAPE key pressed
		if (e.keyCode == 27) {
			feedbackFadeOut();
		}
	});
	
	$('.enable-contact-popup').click(feedbackLinkHandler);       

	// load topics
	this.loadTopics = function (topics){
		var currentDomain = this.currentDomain;
		var feedbackMenu = feedbackContainer.find('div#feedback-popup-left-menu > ul'),
		menuItem = '',
		subMenu = '',
		subMenuItem = '',
		i = 0,
		j = 0,
		contactCheckbox = function(){
			$('div#feedback-popup-content div.active span.feedback-popup-form-checkbox-span').die('click').live('click',function () {
				//$(this).toggleClass('feedback-checkbox-selected');
				if($(this).hasClass('feedback-checkbox-selected')){
					$(this).removeClass('feedback-checkbox-selected');
					$(this).find('input.feedback-form-input-checkbox').val(0);
				} else {
					$(this).addClass('feedback-checkbox-selected');
					$(this).find('input.feedback-form-input-checkbox').val(1);
				}
			});
		},
		showValidation = function () {
			var inputContainer = $(this).parent();
			if(inputContainer.hasClass('feedback-input-required')){
				if(validate(this)){
					inputContainer.removeClass('feedback-input-bad').addClass('feedback-input-good');
				} else {
					inputContainer.removeClass('feedback-input-good').addClass('feedback-input-bad');
				}
				checkSubmitButton();
			}
		},
		validate = function (input) {
			var inputContainer = $(input).parent(),
			validationMethods  = $(input).parent().attr('class').split(' '),
			value              = input.value,
			validators = {
				'validate-order-number' : function (){
					return value.match(/^\d{4,}$/);
				},
				'validate-zip-code-or-email' : function (){
					return value.match(/^(\d{5,}|[a-z0-9\d\.\-\_\ ]+@[a-z0-9\d\.\-_]{2,}\.[a-z]{2,10})$/i);
				},
				'validate-email-address' : function (){
					inputContainer.parent().parent().find('span.validate-email-confirm').filter('.feedback-input-good,.feedback-input-bad').find('input').change();
					return value.match(/^[a-z0-9\d\.\-\_\ ]+@[a-z0-9\d\.\-_]{2,}\.[a-z]{2,10}$/i);
				},
				'validate-name' : function (){
					return value.match(/^[a-z\,\-\. ]+$/i);
				},
				'validate-message-sku-or-url' : function (){
					return value.match(/(.|\n){8,}/);
				},
				'validate-email-confirm' : function (){
					var emailInput = inputContainer.parent().parent().find('span.validate-email-address input');
					return emailInput.parent().hasClass('feedback-input-good') && $.trim(emailInput.attr('value').toLowerCase()) === $.trim(input.value.toLowerCase());
				},
				'validate-price' : function(){
					return value.match(/[0-9]/);
				}
			};
			
			for(method in validationMethods){
				if(validators.hasOwnProperty(validationMethods[method])){
					if(!validators[validationMethods[method]]()){
						return false;
					}
				}
			}
			return true;
		},
		menuClick = function (data) {
			return function () {
				if(!$(this).hasClass('feedback-menu-link-selected')){
					$('div#feedback-popup-left-menu > ul > li.feedback-menu-link-selected').not(this).removeClass('feedback-menu-link-selected').find('ul').slideUp(350).find('li').fadeOut().removeClass('feedback-menu-sublink-selected');
					$(this).find('li').fadeIn().parent().slideDown(350);
					$(this).addClass('feedback-menu-link-selected');
					if ($(this).hasClass('feedback-menu-link-subitems')){
						$(this).find('ul > li:first-child').click();       
					}
					if (!$(this).hasClass('feedback-menu-link-subitems')){
					  redrawMainArea(data);
					}
				}
				return false;
			}
		},
		subMenuClick = function (data) {
			return function () {
				if(!$(this).hasClass('feedback-menu-sublink-selected')){
					$('div#feedback-popup-left-menu li.feedback-menu-link-subitems > ul > li').not(this).removeClass('feedback-menu-sublink-selected');
					$(this).addClass('feedback-menu-sublink-selected');
					redrawMainArea(data);
				}
				return false;
			}
		},
		redrawMainArea = function (data) {
			// shows selected topic caption
			$('#feedback-popup-form-container > div.active').slideUp(300,function () {
				if( !data.obj || feedbackContainer.hasClass('feedback-form-repopulated')){
					data.obj = $('<div>' + ((data.form) ? data.caption + data.form : data.caption) + '</div>');
					$('#feedback-popup-form-container').append(data.obj);
					data.obj.find('span.feedback-input-required :input').bind('keyup blur change', showValidation).focus(function () {
						var input = this;
						this.onTimerValidator = window.setInterval(function () {$(input).change()}, 200);
					}).blur( function () {
						window.clearInterval(this.onTimerValidator);
					});
				}
				// removes form border if caption is empty
				if (data.caption == ''){
					data.obj.find('form.feedback-popup-form').addClass('feedback-popup-form-no-caption');
				}
			
				$('#feedback-popup-form-container > div.active').removeClass('active').slideUp().children().fadeOut(600);
			
				$('#feedback-popup-form-container > div').not('.active').hide();
			
				data.obj.addClass('active').children().hide().fadeIn(600).parent().slideDown(350);
			
			
				// attaches item name + sku values to certain form fields
				if ($('div#main-panel').hasClass('hproduct')){
					if(data.obj.find('form').is('#feedback-price-match-form, #feedback-deal-alert-form')){
						$('#feedback-popup-form-container input.feedback-form-item-sku-name').val($('#product-code').html() + ' + ' + $('div#main-panel.hproduct h1.item').html().replace('w/ FREE UPS','')).change();
					}
				} else {
					if(data.obj.find('form').is('.feedback-price-match, .feedback-deal-alert')){
						data.obj.remove();
					}
				}
				
				// toggle optional checkboxes
				contactCheckbox();
				
				// enables/disables submit button
				checkSubmitButton();
			
				// adds loading and submits form
				$('div#feedback-popup-content div.active form.feedback-popup-form').each(function(){
					// add additional POST parameters
					var additionalParams = {
						product_code:  ($('#product-code').length) ? $('#product-code').html() : '',
						product_name: ($('div#main-panel.hproduct h1.item').length) ? $('div#main-panel.hproduct h1.item').html().replace('w/ FREE UPS','') : '',
						form_id: ($(this).attr('id')),
						page_link: document.location.href
					};
					if (typeof $(this).attr('action') !== 'undefined') {
						return false;
					}
					
					$('textarea', this).keydown(function (e) {
						if (e.ctrlKey && e.keyCode == 13) {
							if(!$('div#feedback-popup-form-container div.active input.feedback-submit-button').hasClass('feedback-button-disabled') && $('div#feedback-popup-form-container div.active input.feedback-submit-button').attr('disabled') !== 'disabled'){
								$('div#feedback-popup-form-container div.active input.feedback-submit-button').click();
							}
						}
					});

					$(this).unbind('submit').bind('submit', function() {
						$(':submit', this).click(function() {
							return false;
						});
						$('#feedback-popup-content').addClass('feedback-popup-content-no-bg');
						$('#feedback-popup-content-main').fadeOut(200, function(){
							$('#feedback-popup-contact-bg').before('<div id="feedback-popup-content-main-submit" class="feedback-popup-loading-screen" style="display:none"><img src="http://layout.opticsplanet.com/images/contact-form/contact-ajax-loader.gif" id="feedback-popup-ajax-loader" width="16" height="11"></div>');
							$('#feedback-popup-content-main-submit').fadeIn(400);
						});
						ajaxIframeTunnel({
							url: 'http://feedback.' + currentDomain + '/ajax/post/',
							type: "POST",
							data: $(this).serialize() + '&' + $.param(additionalParams),
							success: function(data){
									$('.feedback-popup-loading-screen').fadeOut(400, function(){
									$(this).remove();
									if($.browser.msie && parseFloat($.browser.version) < 8){
										$('span#feedback-popup-left-bg').remove();
									}
									$('#feedback-popup-contact-bg').before('<div id="feedback-popup-content-main-submit" class="feedback-popup-form-success" style="display:none"></div>');
									$('.feedback-popup-form-success').html('<p>Thank you for choosing OpticsPlanet! Your form has been submitted. One of our trained professionals will get back to you within the next 24 hours. <a href="http://www.opticsplanet.net" id="feedback-form-submitted-close">Close</a></p>').fadeIn(300);
									$('#feedback-form-submitted-close').click(function(){
										feedbackFadeOut();
										return false;
									});
								});
							},
							error: function(request, status, error) {
								$('.feedback-popup-loading-screen').fadeOut(400, function(){
									$(this).remove();
									if($.browser.msie && parseFloat($.browser.version) < 8){
										$('span#feedback-popup-left-bg').remove();
									}
									$('#feedback-popup-contact-bg').before('<div id="feedback-popup-content-main-submit" class="feedback-popup-form-success" style="display:none"></div>');
									$('.feedback-popup-form-success').html('<p>Unfortunately your form was not successfully submitted. Please try again, or email us directly at <a href="mailto:care@opticsplanet.com">care@opticsplanet.com</a>. <a href="http://www.opticsplanet.net" id="feedback-form-submitted-close">Close</a></p>').fadeIn(300);
									$('#feedback-form-submitted-close').click(function(){
										feedbackFadeOut();
										return false;
									});
								}); 
							}
						});
						return false;
					});
				});
					
				// opens correct form and tab when linked from feedback caption
				$('#feedback-popup-content a.enable-contact-popup').click(feedbackLinkHandler);
				
				// removes file attachment for FF2 and Opera browsers and Ipad
				if($.browser.mozilla && parseFloat($.browser.version) < 1.9 || $.browser.opera || (navigator.platform.indexOf("iPad") != -1)){
					$('#feedback-popup-content div.active .feedback-file-attachment-container').hide();
				}
				
				// removes hidden class from iframe for FF3.6
				if(!($.browser.mozilla && parseFloat($.browser.version) < 2)){
					$('div#feedback-popup-content div.active div.feedback-file-attachment > iframe').addClass('contact-file-attachment-iframe-hidden').css('left','-1000px');
				}
				
			}).children().fadeOut(600);
		};
		
		// creates contact topic list
		feedbackContainer.each(function () {
			for(i = 0; i < topics.length; i++){
				menuItem = $('<li class="'+ topics[i].id +'"><span class="feedback-menu-link">' + topics[i].name +'<span class="feedback-menu-arrow"></span></span></li>');
		
				if(topics[i].subTopics){
					menuItem.addClass('feedback-menu-link-subitems');
					subMenu = $('<ul></ul>');
					for(j = 0; j < topics[i].subTopics.length; j++){
						subMenuItem = $('<li class="'+ topics[i].subTopics[j].id +'"><span class="feedback-submenu-link">' + topics[i].subTopics[j].name +'<span class="feedback-menu-arrow"></span></span></li>');
						subMenuItem.click(subMenuClick(topics[i].subTopics[j]));
						subMenu.append(subMenuItem);
					}
					menuItem.append(subMenu);
				}
				
				menuItem.click(menuClick(topics[i]));
				
				$('#feedback-popup-left-menu > ul').append(menuItem);
				
				// remove price match and deal notification if not on product page
				if (!$('div#main-panel').hasClass('hproduct')){
					if($(menuItem).is('.feedback-price-match, .feedback-deal-alert')){
						$(menuItem).remove();
					}
				}
			}
		});
	};
},
addFileAttachment = function(json){
	var currentDomain = window.location.hostname.split('.').slice(-2).join('.'),
	attachedItems = $('<span class="feedback-file-attached-items' + ((!json.success) ? ' feedback-file-attached-error' + '">' + json.msg : '">' + json.filename ) + '<span class="feedback-file-attached-remove"></span></span>'),
	attachedContainer = $('#feedback-popup-content div.active .feedback-file-attachment-container'),
	attachedLoadingImg = $('#feedback-popup-content div.active .feedback-file-attachment-container > img'),
	attachmentHTML = $('<div class="feedback-file-attachment"><span class="feedback-file-attachment-link">attach another file</span><iframe class="feedback-file-attachment-iframe' + 
	((!($.browser.mozilla && parseFloat($.browser.version) < 2)) ? ' contact-file-attachment-iframe-hidden' : '') + '" src="http://feedback.'+ currentDomain + '/ajax/upload-iframe" frameBorder="0"></iframe></div>');


	attachedLoadingImg.remove();

	attachedContainer.append(attachedItems); 

	if (($('div#feedback-popup-content div.active .feedback-file-attached-items').size() == 1) && (json.success)){
		$('div#feedback-popup-content div.active .feedback-file-attachment').before('<span class="feedback-file-attached-text">Attachments</span>');
	}
	if ((json.success) && $('div#feedback-popup-content div.active .feedback-file-attached-error')){
		$('div#feedback-popup-content div.active span.feedback-file-attached-items.feedback-file-attached-error').remove();
	}
	// event handler to remove attachment
	attachedItems.each(function(){
		attachedItems.find('span.feedback-file-attached-remove').click(function(){
			$(this).unbind().parent().remove();
			$('img.file-attachment-loader').remove();
			if($('div#feedback-popup-content div.active .feedback-file-attached-items').not('.feedback-file-attached-error').length == 0) {
				$('div#feedback-popup-content div.active .feedback-file-attached-text').remove();
				$('div#feedback-popup-content div.active .feedback-file-attachment-link').html('attach a file');
			}
			return false;
		});
	});
	
	$('div#feedback-popup-content div.active .feedback-file-attachment').remove();
	attachedContainer.append(attachmentHTML);
	$('div#feedback-popup-content div.active iframe.contact-file-attachment-iframe-hidden').css('left','-1000px');
	
	// create hidden form element
	$('<input>').attr({
		type: 'hidden',
		name: 'file_id[]',
		value: json.file_id
	}).appendTo(attachedItems);

},
contactFileAttachment = function(fileForm,fileInput){
	$(fileInput).change(function () {
		$(fileForm).submit();
		$('div#feedback-popup-content div.active .feedback-file-attached-error:first-child').remove();
		$('div#feedback-popup-content div.active .feedback-file-attachment').before('<img src="http://layout.opticsplanet.com/images/contact-form/contact-file-attachment-loader.gif" class="file-attachment-loader" width="16" height="11">').hide();
	});

	$('#feedback-popup-content div.active span.feedback-file-attachment-link').click(function () {
		$(fileInput).click();
	});
};
