if (typeof console == 'undefined') {
	console = {
		log: function(){}
	}
}

//looking at other peoples code is silly!
$(document).ready(function() {

	function filterPath(string) {
		return string
			.replace(/^\//,'')
			.replace(/(index|default).[a-zA-Z]{3,4}$/,'')
			.replace(/\/$/,'');
	}
	var locationPath = filterPath(location.pathname);
	var scrollElem = scrollableElement('html', 'body');

	$('a[href*=#]').each(function() {
		var thisPath = filterPath(this.pathname) || locationPath;
		if (locationPath == thisPath
		&& (location.hostname == this.hostname || !this.hostname)
		&& this.hash.replace(/#/,'') ) {
			var $target = $(this.hash), target = this.hash;
			if (target) {
				var targetOffset = $(target).offset().top;
				$(this).click(function(event) {
					event.preventDefault();
					$(scrollElem).animate({scrollTop: targetOffset}, 350, function() {
						location.hash = target;
					});
				});
			}
		}
	});

	// use the first element that is "scrollable"
	function scrollableElement(els) {
		for (var i = 0, argLength = arguments.length; i <argLength; i++) {
			var el = arguments[i],
			$scrollElement = $(el);
			if ($scrollElement.scrollTop()> 0) {
				return el;
			} else {
				$scrollElement.scrollTop(1);
				var isScrollable = $scrollElement.scrollTop()> 0;
				$scrollElement.scrollTop(0);
				if (isScrollable) {
					return el;
				}
			}
		}
		return [];
	}
});


var app = {

	init: function () {
		$('input.DatePicker').datepicker();
	},
	
	query: {
		param: function(param) {
			if (!$.app.query[param]) {
				$.app.query[param] = new $.app.query.obj(param);
			}
			return $.app.query[param];
		},
		obj: function(param) {
			this.url = null;
			this.pop = false;
			this.param = param + '-';

			this.auto = function(key, value) {
				this.current();
				if (arguments.length >= 3 && arguments[2]) {
					alt = arguments[2].altKey;
					shift = arguments[2].shiftKey;
					ctrl = navigator.userAgent.indexOf('Macintosh') ? arguments[2].metaKey : ctrlKey;
				} else {
					alt = false;
					shift = false;
					ctrl = false;
				}
				
				this.pop = ctrl;
	
				if (shift && alt) {
					this.add(key, value);
				} else if (shift) {
					this.set(key, value);
				} else if (alt) {
					this.clear(key);
					this.add(key, value);
				} else {
					this.clear(key);
					this.set(key, value);
				}
			}
			
			this.clear = function() {
				if (arguments.length && this.url != null) {
					url = this.url[arguments[0]];
					order = this.url['o'] ? this.url['o'] : null
					this.url = {};
					this.url[arguments[0]] = url;
					if (order != null) {
						this.url['o'] = order;
					}
				} else {
					this.url = {};
				}
			}
			
			this.set = function (key, value) {
				this.current();
				this.url[key] = value;
				this.go();
			}
			
			this.add = function(key, value) {
				this.current();
				if (this.url[key]) {
					v = this.url[key].split(',');
					if ($.inArray(value,v) == -1) {
						v[v.length] = value;
					} else {
						v.splice(v.indexOf(value),1);
					}
					this.url[key] = v.join(',');
				} else {
					this.url[key] = value;
				}
				this.go();
			}
			
			this.go = function () {
				if (this.skipGo == true) {
					return;
				}
				q = this.encode(this.url);
				params = {};
				params[this.param + 'q'] = q;
				url = $.param.querystring(this.goUrl ? this.goUrl : location.href, params);
				if (this.pop) {
					window.open(url);
				} else {
					location.href = url;
				}
			}
			
			this.goto = function(gourl, key, value) {
				event = (arguments.length >= 4 && arguments[3]) ? arguments[3] : null;
				this.goUrl = gourl;
				this.auto(key, value, event);
			}
			
			this.decode = function(url) {
				q = $.deparam($.param.querystring());
				if (q[this.param + 'q']) {
					q = q[this.param + 'q'];
					q = q.split(';');
					url = {};
					for (i=0; i<q.length; i++) {
						q[i] = q[i].split(':');
						url[q[i][0]] = q[i][1];
					}
				} else {
					url = {}
				}
				return url;
			}
			
			this.encode = function(url) {
				encoded = '';
				$.each(this.url,function(key, value) {
					if (key && value) {
						encoded += key + ':' + value + ';';
					}
				});
				return encoded.substr(0,encoded.length-1);
			}
			
			this.current = function() {
				if (this.url == null) {
					this.url = this.decode(location.href);
				}
				return this.url;
			}
		}
	},
	
	loginDialogue: function() {
		$('#dialog-login').dialog({
			resizable: false,
			height: 230,
			width: 400,
			modal: true,
			show: {effect: 'fade', duration: 200},
			hide: {effect: 'fade', duration: 250},
			title: 'Login',
			position: ['center',150],
			buttons: {
				'Login': function() {
					$.app.login($('#dialog-login .formWrapper form')); return false;
					$(this).dialog('close');
				},
				Cancel: function() {
					$(this).dialog('close');
				}
			}
		});
	},
	
	signup: function(source) {
		$('#signup-form input').removeClass('signup-error');
		$.app.postForm(source,null,function(json) {
			if (!json.status) {
				var message = '';
				
				$.each(json.errors, function(index, value) {
					$('input[name="' + index + '"]').addClass('signup-error');
					if (value.message) {
						message += value.message + '<br /><br />';
					}
				});

				content = '<div class="messageError ui-state-error ui-corner-all"><table cellpadding="1" cellspacing="0"><tr><td></td><td class="message"><br />' + message + '</td></tr></table></div><br />';
				$('html,body').animate({scrollTop: 0}, 200);
				

				$('#signup-message')
					.clearQueue()
					.dequeue('fx')
					.stop(true, true)
					.html(content)
					.animate(
						{ height: 'show', opacity: '1'},
						{ duration: 300, specialEasing: { height: 'easeOutQuart' }}
					);
			} else {
				location.href = '/subscribe';
			}
		});

		return status;
	},
	
	login: function(source) {
		var status = false;
		if (!$('#save-password').attr('hasevent')) {
			$('#save-password').bind('load',function(){
				location.href = '/panel';
			}).attr('hasevent',true);
		}
		
		$.app.postForm(source,null,function(json) {
			status = json.status;
		},false);

		return status;
	},
	
	give: function(source) {
		var parent = $(source).closest('.parentFormWrapper');
		parent.find('.loader').css('display','').fadeIn(200);
		parent.find('.button').css('display','none');
		parent.find('.formMessage')
			.empty()
			.fadeOut(400);
		source.submit();
	},
	
	newsDelete: function(id_news) {
		urlgo = appid ? 'app/' + appid : 'campaign/' + campaignid;
		$.ajax({
			url: '/panel/' + urlgo + '/news/delete',
			dataType: 'json',
			type: 'post',
			data: {id: id_news},
			success: function(json) {
				location.href = '/panel/' + urlgo + '/news';
			}
		});
	},
	
	permissionDeleteCampaign: function(login_id, campaign_id) {
		$.ajax({
			url: '/panel/users/delete-permission-campaign',
			dataType: 'json',
			type: 'post',
			data: {login_id: login_id, campaign_id: campaign_id},
			success: function(json) {
				location.href = location.href;
			}
		});
	},
	
	groupDeleteCampaign: function(app_id, app_campaign_group_id) {
		$.ajax({
			url: '/panel/app/' + app_id + '/groups/delete-campaign',
			dataType: 'json',
			type: 'post',
			data: {app_campaign_group_id: app_campaign_group_id},
			success: function(json) {
				location.href = location.href;
			}
		});
	},
	
	permissionDeleteApp: function(login_id, app_id) {
		$.ajax({
			url: '/panel/users/delete-permission-app',
			dataType: 'json',
			type: 'post',
			data: {login_id: login_id, app_id: app_id},
			success: function(json) {
				location.href = location.href;
			}
		});
	},
	
	paymentDelete: function(id_news) {
		urlgo = appid ? 'app/' + appid : 'campaign/' + campaignid;
		$.ajax({
			url: '/panel/' + urlgo + '/paymenttypes/delete',
			dataType: 'json',
			type: 'post',
			data: {id: id_news},
			success: function(json) {
				location.href = '/panel/' + urlgo + '/paymenttypes';
			}
		});
	},
	
	newsEdit: function(source) {
		urlgo = appid ? 'app/' + appid : 'campaign/' + campaignid;
		$.app.postForm(source,null,function(json) {
			if (json.status && json.id) {
				location.href = '/panel/' + urlgo + '/news';
			}
		});
	},
	
	paymentEdit: function(source) {
		urlgo = appid ? 'app/' + appid : 'campaign/' + campaignid;
		$.app.postForm(source,null,function(json) {
			if (json.status && json.id) {
				location.href = '/panel/' + urlgo + '/paymenttypes';
			}
		});
	},
	
	contact: function(source) {
		$.app.postForm(source,null,function(json) {
			if (json.status) {
				var parent = $(source).closest('.parentFormWrapper');
				parent.find('.button').css('display','').fadeOut(200).css('display','none');
				parent.find('.formWrapper')
					.clearQueue()
					.dequeue('fx')
					.stop(true, true)
					.animate(
						{ height: 'toggle', opacity: '1' },
						{ duration: 300, specialEasing: { height: 'easeOutQuart' } }
					);
			}
		});
	},
	
	postForm: function(source, destination, complete) {
		var async = arguments[3] == false ? false : true;
		var contentFormat = arguments[4] ? arguments[4] : false;
		var parent = $(source).closest('.parentFormWrapper');
		parent.find('.loader').css('display','').fadeIn(200);
		parent.find('.button').css('display','none');
		parent.find('.link-submit').css('display','none');
		parent.find('.formMessage')
			.empty()
			.fadeOut(400);
			
		$.ajax({
			url: destination || source.attr('action'),
			dataType: 'json',
			type: 'post',
			async: async,
			data: $.values($(source)),
			success: function(json) {

				content = '';
				if (!json.status) {
					if (json.response) {
						content = '<div class="messageError ui-state-error ui-corner-all"><table cellpadding="1" cellspacing="0"><tr><td><span class="ui-icon ui-icon-alert"></span></td><td class="message">' + json.response + '</td></tr></table></div>';
						$('html,body').animate({scrollTop: 0}, 200);
					}
				} else {
					if (json.response) {
						content = '<div class="messageSuccess ui-state-highlight ui-corner-all"><table cellpadding="1" cellspacing="0"><tr><td><span class="ui-icon ui-icon-alert"></span></td><td class="message">' + json.response + '</td></tr></table></div>';
					}
				}


				parent.find('.loader').css('display','none');
				parent.find('.button').css('display','').fadeIn(200);

				parent.find('.formMessage')
					.clearQueue()
					.dequeue('fx')
					.stop(true, true)
					.html(content)
					.animate(
						{ height: 'toggle', opacity: '1'},
						{ duration: 300, specialEasing: { height: 'easeOutQuart' }}
					);
	
				if (complete) {
					complete(json);
				}
			}
		});

		return false;
	},
	
	editorConfig: {
		basic: {
			css: '/assets/css/web/jquery.wysiwyg.iframe.css',
			controls: {

				justifyLeft   : { visible : false },
				justifyCenter : { visible : false },
				justifyRight  : { visible : false },
				justifyFull   : { visible : false },
      
				separator01 : { visible : false },

				indent  : { visible : false },
				outdent : { visible : false },

				separator02 : { visible : false },

				subscript   : { visible : false },
				superscript : { visible : false },

				separator03 : { visible : false },

				undo : { visible : false },
				redo : { visible : false },
				insertImage : { visible : false },
				separator04 : { visible : false },

				insertOrderedList    : { visible : true },
				insertUnorderedList  : { visible : true },
				insertHorizontalRule : { visible : false },

				h4mozilla : { visible : false },
				h5mozilla : { visible : false },
				h6mozilla : { visible : false },

				h1 : { visible : false },
				h2 : { visible : false },
				h3 : { visible : false },
				h4 : { visible : false },
				h5 : { visible : false },
				h6 : { visible : false },

				separator05 : { visible : false },
				separator06 : { visible : false },
				separator07 : { visible : false },
				separator08 : { visible : false },
      
				cut   : { visible : false },
				copy  : { visible : false },
				paste : { visible : false },
				
				removeFormat: { visible : true }
			}
		}
	}
}


$(document).ready(function() {
	$.app.init();
});

$.extend($, {values: function(o) {
	var q = o.serializeArray(), p = {};
	for (i in q) {
		p[q[i].name] = q[i].value;
	}
	return p;
}, app: app});

$.generateId = function() {
    return arguments.callee.prefix + arguments.callee.count++;
};
$.generateId.prefix = 'jq$';
$.generateId.count = 0;
$.fn.generateId = function() {
	return this.each(function() {
		this.id = $.generateId();
	});
};
