/*global $, cmsLoad, inArray, jQuery */
var cmsFiles = ['cms/popup/module.css'];

if(typeof(cmsLoad) === 'function'){
    cmsLoad(cmsFiles);
}

/**
 * CMS Popup Module
 * This is a generic jQuery plugin solution for adding Popup forms on every page.
 *
 * @version 1.0
 * @requires
 * 		jquery.js
 * 		core.js
 * 		common.js
 * 		simplemodal.js
 * 		timers.js
 * @author Ed Rodriguez Ed.Rodriguez@watermatters.org
 */
(function($){
	var module = 'Popup',
	cmsPopupModal = 'cms'+module+'Modal';
	
	$.fn.cmsPopup = function(options){
		
		// preload images
		var img = ['btn.png', 'form_bottom.gif', 'form_top.gif', 'loading.gif'];
		$(img).each(function(){
			var i = new Image();
			i.src = INCLUDE_ROOT+'cms/popup/images/'+this;
		});
		
		return $(this).each(function(){
			var message = '',
			elem = this,
			opts = $.extend({}, $.fn.cmsPopup.defaults, options);
			
			// OVERRIDES
			if(opts.type === 'friend'){
				opts.template_form = 'cms/popups/email.snip';
				opts.template_html = 'email/email_friend_html.html';
				opts.template_text = 'email/email_friend_text.html';
			}else if(opts.type === 'tag'){
				opts.template_form = 'cms/popups/tag.snip';
				opts.height = 120;
			}else if(opts.type === 'rate'){
				opts.template_form = 'cms/popups/rate.snip';
				opts.height = 350;
			}else if(opts.type === 'comment'){
				opts.template_form = 'cms/popups/comment.snip';
				opts.height = 350;
			}else{
				if(opts.template_form === ''){
					opts.template_form = 'email/email_form.html';
				}
				if(opts.template_text === ''){
					opts.template_text = 'email/email_text.html';
				}
			}
			
			/*------------------
				OBJECT FUNCTIONS
			------------------*/
			function merge(o1, o2){
				var i = 0;
				for(var z in o2){
					if(o2.hasOwnProperty(z)){
						o1[z] = o2[z];
					}
				}
				return o1;
			}
			
			function open(dialog){
				// REDIRECT (for login form etc.)
				if(typeof($('#'+cmsPopupModal+' .form').attr('data-redirect')) === 'string' && $('#'+cmsPopupModal+' .form').attr('data-redirect') !== ''){
					document.location.href = $('#'+cmsPopupModal+' .form').attr('data-redirect');
					return false;
				}
				
				// add padding to the buttons in firefox/mozilla
				if($.browser.mozilla){
					$('#'+cmsPopupModal+' .button').css({
						'padding-bottom': '2px'
					});
				}
				// input field font size
				if($.browser.safari){
					$('#'+cmsPopupModal+' .input').css({
						'font-size': '.9em'
					});
				}
				
				var title = $('#'+cmsPopupModal+' .title').html();
				$('#'+cmsPopupModal+' .title').html('Loading...');
				
				// POSITIONS TOP
				if(!opts.scrollTop){
					dialog.container.css({top: $(window).scrollTop()+30});
				}else{
					dialog.container.css({top: 30});
				}
				
				dialog.overlay.fadeIn(200, function(){
					dialog.container.fadeIn(200, function(){
						dialog.data.fadeIn(200, function(){		
							$('#'+cmsPopupModal+' .content').animate({
								height: opts.height
							}, function(){
								$('#'+cmsPopupModal+' .title').html(title);
								$('#'+cmsPopupModal+' form').fadeIn(200, function(){
									$('#'+cmsPopupModal+' #name').focus();
									
									// fix png's for IE 6
									if ($.browser.msie && $.browser.version < 7) {
										$('#'+cmsPopupModal+' .button').each(function(){
											if ($(this).css('backgroundImage').match(/^url[("']+(.*\.png)[)"']+$/i)) {
												var src = RegExp.$1;
												$(this).css({
													backgroundImage: 'none',
													filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' +  src + '", sizingMethod="crop")'
												});
											}
										});
									}
								});
							});
						});
					});
				});
				
				if(typeof(opts.onopen) === 'function'){
					opts.onopen.apply(elem);
				}
				return false;
			}
			
			function show(dialog){
				var msg;
				
				$('#'+cmsPopupModal+' .send').click(function(e){
					e.preventDefault();
					// validate form
					if(validate()){
						msg = $('#'+cmsPopupModal+' .message');
						msg.fadeOut(function(){
							msg.removeClass('error').empty();
						});
						$('#'+cmsPopupModal+' .title').html('Sending...');
						$('#'+cmsPopupModal+' form').fadeOut(200);
						$('#'+cmsPopupModal+' .content').animate({
							height: '80px'
						}, function(){
							$('#'+cmsPopupModal+' .loading').fadeIn(200, function(){
								var query = $('#'+cmsPopupModal+' form').serialize();
								
								// MODULE VALUES (if a form field of the same name doesn't exist)
								if(!opts.custom){
									var fields = ['event','to','subject','message','success','template_path','template_html','template_text','preface','sufface','tracking'];
									for(var i=0; i<fields.length; i++){
										var field = fields[i];
										if($("#"+cmsPopupModal+" input[name='"+field+"']").length === 0 &&
										   $("#"+cmsPopupModal+" textarea[name='"+field+"']").length === 0 &&
										   opts[field].length !== 0){
											query += '&'+field+'='+escape(opts[field]);
										}
									}
								
									// GETS DATA PARAMS FROM THE TRIGGER ELEMENT ATTRIBUTE (data-params)
									var params = $(elem).attr('data-params');
									if(typeof(params) === 'string'){
										query += '&params='+escape(params);
									}
								}
								
								$.ajax({
									data: query,
									type: 'post',
									cache: false,
									dataType: 'html',
									success: function(response){
										$.cms.log(response);
										$('#'+cmsPopupModal+' .loading').fadeOut(200, function(){
											var success = false;
											var message = 'Unable to submit your request at this time.';
											if(response === null || response === ''){
												message = 'Unable to submit your request at this time.';
											}else if(response.indexOf('errors=') >= 0){
												response = $.query(response);
												var errors = urldecode(response.errors);
												errors = errors.split('|');
												if(errors.length > 0){
													message = '';
													for(var i=0; i<errors.length; i++){
														message += errors[i]+"\n";
													}
												}
											}else if(response.indexOf('error=') >= 0){
												response = $.query(response);
												message = response.error;
											}else if(response.indexOf('success=1') >= 0){
												success = true;
												response = $.query(response);
												message = response.message;
											}
											message = urldecode(message);
											if(typeof(message) !== 'undefined'){
												//$.cms.log(message);
											}
											
											if(success){
												$('#'+cmsPopupModal+' .title').html('Thank You!');
												$('body').oneTime(2000, 'close', function(){
													// PAGE REFRESH
													if(opts.type === 'tag' ||
													   opts.type === 'rate' ||
													   opts.type === 'comment' ||
													   opts.refresh){
														document.location.href = document.location.href;
													}else{
														close(dialog);
													}
												});
											}else{
												//$.cms.log(response);
												$('#'+cmsPopupModal+' .title').html('Error');
											}
											msg.html(message).fadeIn(200);
										});
									},
									error: error
								});
							});
						});
					}else{
						alert(message);
					}
				});
				if(opts.scrollTop){
					scrollToTop();
				}
			}
			
			function close(dialog){
				$('#'+cmsPopupModal+' .message').fadeOut();
				$('#'+cmsPopupModal+' .title').html('Closing...');
				$('#'+cmsPopupModal+' form').fadeOut(200);
				$('#'+cmsPopupModal+' .content').animate({
					height: 40
				}, function(){
					dialog.data.fadeOut(200, function(){
						dialog.container.fadeOut(200, function(){
							dialog.overlay.fadeOut(200, function(){
								$.modal.close();
							});
						});
					});
				});
			}
			
			function error(xhr){
				alert(xhr.statusText);
			}
			
			function validate(){
				message = '';
				var errors = $.cms.validate($('#'+cmsPopupModal+' form:first'));
				if(errors.length > 0){
					message = errors.join('');
					return false;
				}
				return true;
			}
			
			function html(html){
				$(html).modal({
					closeHTML: "<a href='#' title='Close' class='close'>x</a>",
					position: '15%',
					overlayId: 'cms'+module+'Overlay',
					containerId: cmsPopupModal,
					onOpen: open,
					onShow: show,
					onClose: close,
					cssPosition: opts.cssPosition
				});
			}
			
			/*------------------
				SETUP
			------------------*/
			
			if(!$(this).hasClass('cursor')){
				$(this).addClass('cursor');
			}
			$(this).click(function(e){
				e.preventDefault();
				
				// CACHES SNIPPET (needed to prevent multiple requests on each click)
				var cache = $(this).data('cache');
				if(typeof(cache) === 'string'){
					html(cache);
				}else{
					var data = {
						template_path: opts.template_path
					};
					if($.evalJSON){
						var params = $(this).attr('data-params');
						if(typeof(params) === 'string'){
							params = $.evalJSON(params);
							if(typeof(params) === 'object'){
								data = merge(data, params);
							}
						}
					}
					$.ajax({
						type: 'post',
						url: SITE_ROOT+'snippet/'+opts.template_form,
						data: data,
						success: function(response){
							$(this).data('cache', response);
							html(response);
						}
					});
				}
				if(!e){
					e = window.event;
				}
				if(typeof(e) !== 'undefined'){
					e.cancelBubble = true;
					if(e.stopPropagation){
						e.stopPropagation();
					}
				}
			});
		});
		
	};
	/*------------------
		OBJECT DEFAULTS
	------------------*/
	$.fn.cmsPopup.defaults = {
		type: 'default', // (default, friend)
		tracking: 'Popup',
		event: 'Popup',
		template_form: '',
		template_html: '',
		template_text: '',
		refresh: 0,
		height: 300,
		to: '',
		subject: '',
		preface: '',
		message: '',
		sufface: '',
		cssPosition: 'absolute',
		template_path: window.location.href,
		success: 'Your email has been sent.',
		scrollTop: false,
		onopen: null,
		custom: false
	};
}(jQuery));
