/*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';
	var current = null;
	var cmsPopupModal = 'cms'+module+'Modal';
	
	$.fn.cmsPopup = function(options){
		var state = null;
		var opts = $.extend({}, $.fn.cmsPopup.defaults, options);
		var count = opts.count;
		var mode = null;
		
		// 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
		------------------*/
		this.get = function(name){
			var local = eval(name);
			if(typeof(local) !== 'undefined'){
				return(local);
			}else if(typeof(this[name]) !== 'undefined'){
				return(this[name]);
			}else if(typeof(this.name) === 'function'){
				return(this.name);
			}
			return('');
		};
		
		this.message = null;
		
		this.open = function(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();
			}
            return false;
		};
		
		this.show = function(dialog){
			var msg;
			var elem = window['cms'+module+count];
			
			$('#'+cmsPopupModal+' .send').click(function(e){
				e.preventDefault();
				// validate form
				if(elem.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)
							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)
							if(typeof(elem.btn) === 'object'){
								var params = $(elem.btn).attr('data-params');
								if(typeof(params) === 'string'){
									query += '&params='+escape(params);
								}
							}
							
							$.ajax({
								data: query,
								type: 'post',
								cache: false,
								dataType: 'html',
								success: function(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'){
                                                    document.location.href = document.location.href;
                                                }else{
                                                    elem.close(dialog);
                                                }
											});
										}else{
											//$.cms.log(response);
											$('#'+cmsPopupModal+' .title').html('Error');
										}
										msg.html(message).fadeIn(200);
									});
								},
								error: elem.error
							});
						});
					});
				}else{
					alert(elem.message);
				}
			});
			if(opts.scrollTop){
				scrollToTop();
			}
		};
		
		this.close = function(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();
						});
					});
				});
			});
		};
		
		this.error = function(xhr){
			alert(xhr.statusText);
		};
		
		this.validate = function(){
			var elem = window['cms'+module+count];
			elem.message = '';
			var errors = $.cms.validate($('#'+cmsPopupModal+' form:first'));
			if(errors.length > 0){
				elem.message = errors.join('');
				return false;
			}else{
				return true;
			}
		};
		
		this.html = function(html){
			var elem = window['cms'+module+count];
			$(html).modal({
				closeHTML: "<a href='#' title='Close' class='close'>x</a>",
				position: '15%',
				overlayId: 'cms'+module+'Overlay',
				containerId: cmsPopupModal,
				onOpen: elem.open,
				onShow: elem.show,
				onClose: elem.close,
				cssPosition: opts.cssPosition
			});
		};
		
		/*------------------
			SETUP
		------------------*/
		
		var elem = this;
		$(this).each(function(){
			if(!$(this).hasClass('cursor')){
				$(this).addClass('cursor');
			}
			$(this).click(function(e){
				elem.btn = this;
				e.preventDefault();
				
				// CACHES SNIPPET (needed to prevent multiple requests on each click)
				var cache = $.cms.getHtml(opts.template_form);
				if(typeof(cache) === 'string'){
					elem.html(cache);
				}else{
					$.get(SITE_ROOT+'snippet/'+opts.template_form, {template_path: opts.template_path}, function(response){
						$.cms.setHtml(opts.template_form, response);
						elem.html(response);
					});
				}
				if(!e){
					e = window.event;
				}
				if(typeof(e) !== 'undefined'){
					e.cancelBubble = true;
					if(e.stopPropagation){
						e.stopPropagation();
					}
				}
			});
		});
	
		// 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;
		});
		
		//$.cms.log('cms'+module+count);
		window['cms'+module+count] = this;
		$.fn.cmsPopup.defaults.count++;
		return(this);
	};
	/*------------------
		OBJECT DEFAULTS
	------------------*/
	$.fn.cmsPopup.defaults = {
		count: 1,
		type: 'default', // (default, friend)
		tracking: 'Popup',
		event: 'Popup',
		template_form: '',
		template_html: '',
		template_text: '',
		height: 300,
		to: '',
		subject: '',
		preface: '',
		message: '',
		sufface: '',
		cssPosition: 'absolute',
		template_path: window.location.href,
		success: 'Your email has been sent.',
		scrollTop: false,
		onopen: null
	};
}(jQuery));