/*
 * 	 ui.imFeedBack - A JQuery UI Feedback Widget 
 * 	 @author Les Green
 * 	 Copyright (C) 2010 Intriguing Minds, Inc.
 * 
 *  version 0.5.2 - 
 *  1. fixed bug so widget works in IE7 
 * 
 * 
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.

 *   Demo and Documentation can be found at:   
 *   http://www.grasshopperpebbles.com
 *   
 */

 (function($) {

$.widget("ui.imFeedBack", {

	_init: function() {
		o = this.options;
		//var self = this;
		feedBackOpen = false;
		brwsrIsIE7 = this.isIE7();
		this.buildSideFeedbackBtn();
	},
	
	isIE7: function() {
		var v = parseFloat(navigator.appVersion.split("MSIE")[1]);
		return ((v < 8) && (document.body.filters)); 
	},
	
	buildSideFeedbackBtn: function() {
		var self = this;
		//$('<div id='imFeedBack-container'></div>').appendTo(this.element);
		$('<div></div>').attr('id', 'imFeedBack-container').css(o.location, '0px').appendTo(this.element);
		//$('<div></div>').attr('id', 'imFeedBack-container').css('position', 'absolute').css('top', '0px').css(o.location, '0px').appendTo(this.element);
		var frm, tf;
		
/*		var sH = parseInt(screen.height);
		var cH = parseInt($('#imFeedBack-container').height());
		var mT = (sH - cH)/3;
		if (brwsrIsIE7) {
			$('#imFeedBack-container').css('top', mT + 'px');
		} 
		var sH = parseInt(screen.height);
		alert("sH : " + sH);		
		var cH = parseInt($('#imFeedBack-container').height());
		alert("cH : " + cH);
		var mT = (sH - cH)/2;	
		alert("mT: " + mT);
		if ($.browser.webkit || $.browser.safari) {
			mT = mT - 100;
		}
		if (brwsrIsIE7) {
			$('#imFeedBack-container').css('top', mT + 'px');
		}
		else {
			$('#imFeedBack-container').css('top', mT + 'px');
		}
*/		
		var btn = $('<button></button>').attr({'id': 'imFeedBack-Button', 'class': o.feedback_button_class}).html(o.feedback_button_text);		
		
		if (o.show == 'slide') {
			frm = self.getFeedBackForm();
		} else {
			tf = self.buildDialogFeedback();
		}
		if (o.location == 'right') {
			$(btn).addClass('imFeedBack-Button-right');
			if (o.show == 'slide') {
				$('#imFeedBack-container').append($(btn), $(frm));
			}	
		} else {
			if ($(btn).hasClass('ui-corner-top')) {
				//$(btn).removeClass('ui-corner-top').addClass('ui-corner-bottom');
			}
			$(btn).addClass('imFeedBack-Button-left');
			if (o.show == 'slide') {
				$('#imFeedBack-container').append($(frm), $(btn));
			}
		}
		if (o.form_capture_name) {
			tf = self.formCaptureName();
		}
		if (o.show == 'slide') {
			$('#imFeedBack-Form').prepend($('<h3></h3>').attr('class', o.header_class).html(o.header_caption));
			$('#imFeedBack-Message').after(
				$('<button id="imFeedBack-Button-Send" type="button" class="'+o.form_button_class+'">Submit</button>'),
				$('<button id="imFeedBack-Button-Cancel" type="button" class="'+o.form_button_class+'">Close</button>'));
		}
		if (o.show == 'dialog') {
			$('#imFeedBack-container').append($(btn));
		}
		var bH = $('#imFeedBack-Button').width();
		var mT = (parseInt(mT) - bH)/2 +'px';
    	$('#imFeedBack-Button').css('width', 30);
		
		$('#imFeedBack-Button').hover(
			function() {
				if (o.feedback_button_class_hover) {
					$(this).addClass(o.feedback_button_class_hover).css('cursor', 'pointer');
				} else {
					$(this).css('cursor', 'pointer');
				} 
			}, 
			function() { 
				if (o.feedback_button_class_hover) {
					$(this).removeClass(o.feedback_button_class_hover).css('cursor', 'default');
				} else {
					$(this).css('cursor', 'default');
				}	
			}
		);
		var feedBackBtns = (o.external_control) ? '#imFeedBack-Button, #' + o.external_control.id : '#imFeedBack-Button'; 
		$(feedBackBtns).click(function() {
			if ($(this).attr('id') == o.external_control.id) {
				if (o.external_control.top_text) {
					$('#imFeedBack-Top-Text').html(o.external_control.top_text);
				}
				if (o.external_control.feedback_subject) {
					$('#imFeedBack-Subject').val(o.external_control.feedback_subject);
				}
				if (o.external_control.disable_subject) {
					$('#imFeedBack-Subject').attr('disabled', true);
				}
			} else {
				if (o.disable_subject) {
					$('#imFeedBack-Subject').attr('disabled', true);
				}
			}	
			self.toggleText(); 
			if (o.show == 'slide') {
				$('#imFeedBack-FormContainer').toggle("slow", function() {
					if (brwsrIsIE7) {
						if (feedBackOpen) {
							var w = $('#imFeedBack-FormContainer').width();
							$('#imFeedBack-FormContainer #imFeedBack-Form h3').css('width', w);
						}
					}
				});
			} else {
				$('#' + o.dialog_container).dialog('open');
			}
		});
/*		$('#imFeedBack-Button-Send, #imFeedBack-Button-Cancel').hover(
			function() {
				if (o.form_button_class_hover) {
					$(this).addClass(o.form_button_class_hover).css('cursor', 'pointer');
				} else {
					$(this).css('cursor', 'pointer');
				} 
			}, 
			function() { 
				if (o.form_button_class_hover) {
					$(this).removeClass(o.form_button_class_hover).css('cursor', 'default');
				} else {
					$(this).css('cursor', 'default');
				}	
			}
		);*/
		$('#imFeedBack-Button-Send').click(function() {
			self.sendFeedBack();
		});
		$('#imFeedBack-Button-Cancel').click(function() {
			self.closeFeedBackCntnr();	
		});
	},
	
	buildDialogFeedback: function() {
		var self = this;
		if (o.dialog_widget_form) {
			$(document.body).append($('<div></div>').attr('id', o.dialog_container));
			var frm = this.getFeedBackForm();
			$('#'+ o.dialog_container).append($(frm));
			$('#imFeedBack-FormContainer').removeClass(o.form_container_class);
			$('#imFeedBack-FormContainer').show();
		}
		
		$('#'+o.dialog_container).dialog({ 
	    	buttons: { 
	    		"Send": function() {
					self.sendFeedBack();
	    		}, 
	    		"Close": function() { 
					self.closeFeedBackCntnr();
	       			//$(this).dialog("close");
	   			} 
	   		}, 
			width: o.dialog_width,
			modal: true, 
			autoOpen: false, 
			title: o.header_caption
		});
		return true;
	},
	
	getFeedBackForm: function() {
		var h = '';
		$.each(o.hidden_fields, function (i, itm) {
			h += '<input type="hidden" name="' + itm.name + '" value="' + itm.value + '" />';
		});
		var frm = $('<div></div>').attr({
			'id': 'imFeedBack-FormContainer',
			'class': o.form_container_class
		}).css('float', o.location).append($('<form></form>').attr({'id': 'imFeedBack-Form'}).html(h).append(
						$('<div></div>').attr({'id': 'imFeedBack-NameEmailInfo'}).append(
							$('<div></div>').attr({'id': 'imFeedBack-NameEmail'}).css('float', 'left').css('width', '185px').append(
							$('<div></div>').attr('id', 'imFeedBack-Top-Text').html(o.top_text),							$('<label></label>').html('Email:'),
							$('<input type="text" class="inputtext" name="imFeedBack-Email" id="imFeedBack-Email" />')
						),
						$('<div></div>').attr({'id': 'imFeedBack-Info'}).css('float', 'left').css('width', '365px').css('font-size', '8pt').html('<br/>This form allows you to help PSI improve the user\’s experience on the website. If you have a concern that requires a response, please contact a Customer Service Representative.'
						)						
						)).append(
						$('<label></label>').html('<span class="mandatory">*</span>Category:'),
						$('<select name="imFeedBack-Category" id="imFeedBack-Category"><option value="There are feature(s) I like">There are feature(s) I like</option><option value="There are feature(s) I dislike">There are feature(s) I dislike</option><option value="I have suggestion(s)">I have suggestion(s)</option><option value="I had a problem with the website">I had a problem with the website</option><option value="Other">Other</option></select>'),
						$('<label></label>').html('<span class="mandatory">*</span>Message:'),						
						$('<textarea></textarea>').attr({'name': 'imFeedBack-Message', 'id': 'imFeedBack-Message'}),
						$('<div></div>').attr('id', 'imFeedBack-Response')
					)
		);
		if (brwsrIsIE7) {
			//var f = (o.location == 'right') ? 'left' : 'right';
			$(frm).css('float', 'left');	
		}
		return frm;
	},
	
	formCaptureName: function() {
		if (o.form_capture_name == 'firstName') {
			$('#imFeedBack-Top-Text').after(
				$('<label></label>').text('First Name:'),
				$('<input type="text" name="imFeedBack-FirstName" id="imFeedBack-FirstName" />')
			);
		} else if (o.form_capture_name == 'fullName') {
			$('#imFeedBack-Top-Text').after(
				$('<label></label>').text('Name:'),
				$('<input type="text" class="inputtext" name="imFeedBack-Name" id="imFeedBack-Name" />')
			);
		} else if (o.form_capture_name == 'firstLast') {
			$('#imFeedBack-Top-Text').after(
				$('<label></label>').text('First Name:'),
				$('<input type="text" name="imFeedBack-FirstName" id="imFeedBack-LastName" />'),
				$('<label></label>').text('Last Name:'),
				$('<input type="text" name="imFeedBack-LastName" id="imFeedBack-LastName" />')
			);
		}
		return true;
	},
	
	sendFeedBack: function() {
		var validForm = this.validateForm();
		if (validForm == true) {
			this.doAjax('POST', o.submit_url, $('#imFeedBack-Form').serialize(), '', this.showSuccess);
		} else {
			$('#imFeedBack-Response').html(validForm);
		}	
	},
	
	closeFeedBackCntnr: function() {
		if (o.show == 'slide') {
			$('#imFeedBack-Response').html('');
			$('#imFeedBack-FormContainer').hide("slow");
		} else {
			$('#'+o.dialog_container).dialog("close");
		}
		this.toggleText();
	},
	
	toggleText: function() {
		feedBackOpen = (feedBackOpen == false);
		if (!feedBackOpen) {
			$('imFeedBack-Top-Text').html(o.top_text);
			$('#imFeedBack-Subject').val(o.feedback_subject);
			if (o.disable_subject) {
				$('#imFeedBack-Subject').attr('disabled', true);
			} else {
				$('#imFeedBack-Subject').removeAttr('disabled');
			}
			$('#imFeedBack-Response').html('');
		}
	},
	
	validateForm: function() {
		var rVal = true;
		/*if ((o.form_capture_name != false) && (o.validate_name == true)) {
			if (o.form_capture_name == 'firstName') {
				if ($.trim($('#imFeedBack-FirstName').val()) == '') {
					rVal = 'You must enter your first name';
				}
			} else if (o.form_capture_name == 'fullName') {
				if ($.trim($('#imFeedBack-Name').val()) == '') {
					rVal = 'You must enter your name';
				}
			} else if (o.form_capture_name == 'firstLast') {
				if (($.trim($('#imFeedBack-FirstName').val()) == '') || ($.trim($('#imFeedBack-LastName').val()) == '')) {
					rVal = 'You must enter your first and last name';
				}
			}
		} else*/ 
		if (!this.isValidEmail($('#imFeedBack-Email').val())) {
			rVal = 'Please enter a valid email address';
		} else if ($('#imFeedBack-Subject').val() == '') {
			rVal = 'You must enter a subject';
		} else if ($.trim($('#imFeedBack-Message').val()) == '') {
			rVal = 'Please enter a feedback message';
		} else if ($('#imFeedBack-Category').val() == '') {
			rVal = 'Please select a feedback category';
		}  
		return rVal; 
	},
	
	isValidEmail: function(val) {
		var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
		if(val != "") {
			if (filter.test(val)) {
				return true;
			} else {
				return false;
			}
		}
		return true;
	},
	
	doAjax: function (t, u, d, fnBefore, fnSuccess) {		
		$.ajax({
			type: t,
			url: u,
			data: d,
			dataType: 'html',
			beforeSend: fnBefore, 
			success: fnSuccess,
			error: self.showError
	 	}); //close $.ajax(
	},
	
	showError: function (XMLHttpRequest, textStatus, errorThrown) {		
		console.log(textStatus);
	},

	showSuccess: function (result) {
		//alert(result);
		var self = this;
		//$('#imFeedBack-Response').empty();
		if (result == 'Feedback Submitted') {
			var msg = (o.success_msg) ? o.success_msg : result;
			$('#imFeedBack-Response').html(msg);
		} else {			
			$('#imFeedBack-Response').html(o.failure_msg);
		}
		
		$('#imFeedBack-Name').val('');
		$('#imFeedBack-Email').val('');
		$('#imFeedBack-Message').val('');
		$('#imFeedBack-Category').val('There are feature(s) I like');
		
	},

	destroy: function() {
		$.widget.prototype.destroy.apply(this, arguments);
		return this;
	}

});

$.extend($.ui.imFeedBack, {
	version: "@VERSION",
	defaults: {
		location: 'right', //left
		show: 'slide', //dialog
		dialog_container: 'imFeedBack-dialog',// used only if show = dialog
		dialog_widget_form: true, //if true, email form will be built
		dialog_width: '550px',
		form_container_class: 'ui-widget ui-widget-content ui-corner-all',
		form_button_class: 'btn',
//		form_button_class_hover: 'btn',
		form_capture_name: 'fullName', // firstName, fullName, firstLast
		validate_name: true,
		feedback_subject: '',
		disable_subject: '',
		header_class: 'greyrow',
		header_caption: 'Please Give Us Feedback',
		top_text: '',
		feedback_button_class: 'fg-button ui-state-default ui-corner-top', 
//		feedback_button_class_hover: 'ui-state-hover',
		feedback_button_text: '',
		hidden_fields: '', //[ {name: "img_type", value: "P"}, {name: "action", value: "doAdd"}, {name: "page", value: "member_images"} ]
		submit_url: '',
		success_msg: 'Your feedback is submitted, thank you.',
		failure_msg: 'There was a problem in submitting your feedback at the moment. Please try later.',
		external_control: '' //{ id: 'webDesignBtn', top_text: '', feedback_subject: '', disable_subject: true}
	}
});

})(jQuery);
