var loader		= {
		white:		$('<div class="loader"></div>'),
		grey:		$('<div class="loader grey"></div>')
	},
	finalized	= {
		tab : false,
		load: {}
	},
	inputs		= {
		picture:	$('<input type="hidden" />')
	},
	notify		= {
		error:		$('<div><div class="error" /></div>').addClass('notify'),
		success:	$('<div><div class="success" /></div>').addClass('notify')
	};

function openNear(where, what, top)
{
	if (!where || !what)
		return false;
	
	if (what.parents('div.popup:first').length > 0) {
		what.parents('div.popup:first').find('div.popup').addClass('hide');
	} else {
		$('div.popup').addClass('hide');
	}
	
	if (typeof top == 'undefined')
		top = -10;
	
	what.css('top', where.offset().top + top + 'px').removeClass('hide');
}

function tick(el)
{
	return setActive(el, 'div.list-item', 'div.content:first', 'ticked');
}

function activate(el)
{
	return setActive(el, 'input[type="button"]', 'table.switch:first', 'active');
}

function setActive(el, what, where, cssclass)
{
	if (typeof cssclass == 'undefined')
		cssclass = 'active';
	
	if (el.hasClass(cssclass))
		return false;
	
	if (typeof where != 'undefined' && typeof what != 'undefined')
		el.parents(where).find(what).removeClass(cssclass);
	
	el.addClass(cssclass);
	
	return true;
}

function loadContent(el, url, params, l)
{
	if (typeof l == 'undefined') {
		l = loader.white;
	}
	
	el.html(l);
	
	if (typeof params == 'undefined')
		params = {};
	
	$.ajax({
			type: 		"POST",
			url : 		url,
			async : 	true,
			data: 		(params),
			complete:	function(xhr) {
				if (xhr.status != 200) {
					el.html('<p class="error c-align">Can\'t load content</p>');
				} else {
					if (isNaN(parseInt(xhr.responseText))) {
						el.html(xhr.responseText);
					} else {
						el.html = '';
						switch (parseInt(xhr.responseText)) {
							case -201:
								window.location = ajax_urls['no_access'];
						}
					}
				}
			}
		});
}

function increase(what, num, callback)
{
	if (typeof num == 'undefined')
		num = 1;
	
	if (what.is('input') || what.is('textarea')) {
		current = what.val();
	} else {
		current = what.html();
	}
	
	if (isNaN(current))
		current = 0 + num;
	else	
		current = parseInt(current) + num;
	
	if (current < 0) {
		current = 0;	
	}
	
	if (what.is('input') || what.is('textarea')) {
		what.val(current);
	} else {
		what.html(current);
	}
	
	if (typeof callback == 'function') {
		callback(current);
	}
}

function setValue(what, viewer, callback)
{
	if (viewer.is('input') || viewer.is('textarea')) {
		viewer.val(what);
	} else {
		viewer.html(what);
	}
	
	if (typeof callback == 'function') {
		callback();
	}
}

// calback(result, error);
function call(url, params, callback)
{
	if (typeof params == 'undefined') {
		params = {};	
	}
	
	$.ajax({
		'type'		: "POST",
		'url'		: url,
		'async' 	: true,
		'data'		: params,
		'complete'	: function(xhr) {
			if (xhr.status != 200) {
				if (typeof callback == 'function') {
					callback(xhr.responseText, true);
				}
			} else {
				if (typeof callback == 'function') {
					callback(xhr.responseText, false);
				}
			}
		}
	});
}

function toggle(show, hide) {
	if (typeof show != 'object') {
		show	= [];
	}
	if (typeof hide != 'object') {
		hide	= [];
	}
	for (var i in show) {
		$(show[i]).removeClass('hide');
	}
	for (var i in hide) {
		$(hide[i]).addClass('hide');
	}
}

function imitate(where) {
	content = where.html();
	where.html(loader.grey.clone().width(700));
	setTimeout(function() {
		where.html(content);
	}, 2000);
}

function bindTriggers()
{
	$('input[type="button"].checkbox.ipad').live('click', function(e)
	{
		$(this).toggleClass('checked');
		if ($(this).hasClass('checked')) {
			$("input[type='checkbox']#" + $(this).attr("name")).val($(this).attr("name") == 'profile_visible_via_bt' ? 0 : 1);
		} else {
			$("input[type='checkbox']#" + $(this).attr("name")).val($(this).attr("name") == 'profile_visible_via_bt' ? 1 : 0);
		}
		
	});
	
	$('div.list-item.checkbox').live('click', function(e)
	{
		if ($(e.target).is('input')) {
			return false;
		} else {
			$(this).find('input[type="button"].checkbox').click();
		}
	});
	
	$('textarea.resizable').live('focusin', function(){
		$(this).attr('rows', 5);
	});
	
	$('div.redirect, li.redirect').live('click', function(e) {
		deep = $(this).parents('div.redirect').length + 1;
		if (!$(e.target).is('a')
			&& !$(e.target).is('input')
			&& !$(e.target).attr('onclick')
			&& !$(e.target).parents('a.redirect').length)
		{
			a = $(this).find('a.redirect').filter(function() { return $(this).parents('div.redirect').length == deep; });
			if (!a.length) {
				a = $(this).find('a:first');
			}
			if (a.attr('onclick')) {
				a.click();
			} else if (a.attr('href') && a.attr('href').indexOf('javascript') < 0) {
				window.location = a.attr('href');
			}
		}
	});
	
	$('.tabs .tab:not(.redirect), .tabs .tab a:not(.redirect)').live('click', function()
	{
		if ($(this).is('a')) {
			if ($(this).parents('div.tab').hasClass('active') && finalized.tab) {
				return false;
			} else {
				$(this).parents('div.tabs').find('div.tab').removeClass('active');
				$(this).parents('div.tab').addClass('active');
				finalized.tab	= true;
				return true;
			}
		} else {
			if ($(this).hasClass('active')) {
				return false;
			} else {
				finalized.tab	= false;
				$(this).parents('div.tabs').find('div.tab').removeClass('active');
				$(this).addClass('active');
				$(this).find('a').click();
			}
		}
	});
	
	$(window).scroll(function(e) {
		$('.loadup').each(function() {
			loadUp($(this));
		});
	});
	
	$('form.ajax').live('submit', function(e) {
		var form = $(this);
		call($(this).attr('action'), $(this).serialize(), function(response, error) {
			response = toJSON(response);
			if (error || typeof response.code == 'undefined') {
				message = notify.error;
				message.find('div.error:first').html('Unable to process your request');
			} else {
				if (parseInt(response.code) === 0) {
					message	= notify.success;
					message.find('div.success:first').html(response.message);

					if (typeof response.reset != 'undefined' && form.attr('name')) {
						for (var i in response.reset) {
							form.find('#' + form.attr('name') + '_' + i).val(response.reset[i]);
						}
					}
					
					if (typeof form.attr('container') != 'undefined' && $(form.attr('container')).length > 0 && typeof response.html != 'undefined') {
						$(form.attr('container')).append(response.html);
					}
				} else {
					message	= notify.error;
					message.find('div.error:first').html(response.message);
				}
			}
			$('table.layout td.content').find('div.notify').remove();
			$('table.layout td.content').prepend(message);
		});
		e.preventDefault();
		return false;
	});
	
	$(document).click(function(e) {
		$(document).find('div.notify').remove();
		if (!$(e.target).hasClass('open')) {
			$('.hidable').filter(function(){
				if ($(e.target).parents('.hidable').length == 0 && !$(e.target).hasClass('hidable')) {
					if ($(this).hasClass('total')) {
						$(this).remove();
						return false;
					} else {
						return true;
					}
				}
				return false;
			}).addClass('hide');
		}
	});
	
	$('input[type="text"].autosave, input[type="radio"].autosave, input[type="checkbox"].autosave, textarea.autosave').live('change', function(e) {
		if ($(this).parents('form:first').length) {
			$(this).parents('form:first').submit();
		}
	});
	
	$('input.no-submit').live('keypress', function(e) {
		if ((e.keyCode || event.which || event.charCode || 0) == 13) {
			e.preventDefault();
			return false;
		}
		
		return true;
	});
	
	$('.countable').live('keyup', function()
	{
		if ($('span#' + $(this).attr('id') + '_counter').length)
			if ($('span#' + $(this).attr('id') + '_counter').attr('max') - $(this).val().length < 0)
				$(this).val($(this).val().substr(0, $('span#' + $(this).attr('id') + '_counter').attr('max')));
			else
				$('span#' + $(this).attr('id') + '_counter').html($('span#' + $(this).attr('id') + '_counter').attr('max') - $(this).val().length);
	});
			
	$('.countable').keyup();
}

function toJSON(data){
	try {
		data = JSON.parse(data);
	} catch (err) {
		data = { 'code' : -999, 'message' : 'Error while processing response' };
	}
	
	if (typeof data.debug != 'undefined') {
		console.log(data.debug);
	}
	
	return data;
}

function  loadUp(el) {
	
	if (typeof el.attr('loadup-id') == 'undefined') {
		id = Math.random() + '_loadup';
		el.attr('loadup-id', id);
	} else {
		id = el.attr('loadup-id');
	}

	if (typeof el.attr('load-locked') != 'undefined') {
		return true;
	}
	
	if (typeof (l = el.attr('on-waiting')) == 'undefined') {
		l = loader.white;
	}
	
	if (typeof (by = el.attr('by')) == 'undefined' || parseInt(by) == NaN) {
		by = 10;
	}
	
	if (typeof (ch = el.attr('child')) == 'undefined') {
		ch = 'div';	
	}
	
	if (el.find(ch).length < by || $('[loadup-id="' + id + '"]:first').find(ch).length % by) {
		el.attr('load-locked', true);
		return true;
	} else {
		page = Math.floor(el.find(ch).length / by) + 1;
	}
	
	if (typeof (url = el.attr('url')) == 'undefined') {
		url = window.location.href;
	}
	
	if (el.offset().top + el.height() - window.pageYOffset - window.innerHeight < 0) {
		el.append(l);
		if (typeof (f = el.attr('onloadup')) == 'undefined') {
			f = null;
		}
		
		if (finalized.load[id] || typeof finalized.load[id] == 'undefined') {
			finalized.load[id] = false;
			call(url, { 'by' : by, 'page' : page }, function(response, error) {
				nodes = $('<div />').html(response).find(ch).length;
				if (nodes != by) {
					el.attr('load-locked', true);
				}
				if (response == '' || error) {
					el.find('.' + l.attr('class').replace(/\s/gi, '.'))
						.remove();
					if (f) {
						eval(f);
					}
				} else {
					el.find(ch + ':last').after(response);
					el.find('.' + l.attr('class').replace(/\s/gi, '.'))
						.remove();
					
					if (f) {
						eval(f);
					}
				}
				finalized.load[el.attr('loadup-id')] = true;
			});
		}
	}
}

function remove(el, url, callback) {
	call(url, {}, function(response, error) {
		if (processResponse(response, error)) {
			el.remove();
			
			if (typeof callback == 'function') {
				callback(toJSON(response));
			} 
		}
	});
}

function processResponse(response, error) {
	response = toJSON(response);
	if (error || typeof response.code == 'undefined') {
		message = notify.error;
		message.find('div.error:first').html('Unable to process your request');
	} else if (parseInt(response.code) === 0) {
		message	= notify.success;
		message.find('div.success:first').html(response.message);
	} else {
		message	= notify.error;
		message.find('div.error:first').html(response.message);
	}
	$('table.layout td.content').find('div.notify').remove();
	$('table.layout td.content').prepend(message);
	
	return typeof response.code != 'undefined' && !error && parseInt(response.code) == 0;
}

//callback(el)
function bind(select, view, form, selectors, o, callback) {
	
	if (typeof selectors == 'undefined' || !selectors) {
		selectors = {
			what	: '.to-bind.active',
			reset	: 'input[type="hidden"].to-bind',
			view	: '.to-bind.active'
		};
	}
	
	if (typeof selectors.what == 'undefined' || !selectors.what) {
		selectors.what = '.to-bind.active';
	}

	if (typeof selectors.reset == 'undefined' || !selectors.reset) {
		selectors.reset = 'input[type="hidden"].to-bind';
	}

	if (typeof selectors.view == 'undefined' || !selectors.view) {
		selectors.view = '.to-bind.active';
	}
	
	if (typeof o == 'undefined' || !o) {
		o = {
			name	: 'binding[:I:]',
			attr	: 'db-id'	// attr name
		};
	}
	
	if (typeof o.name == 'undefined' || !o.name) {
		o.name	= 'binding[:I:]';
	}
	
	if (typeof o.attr == 'undefined' || !o.value) {
		o.attr = 'db-id';
	}
	
	if (typeof form == 'undefined' || !form) {
		form = view.parents('form:first');
	}
	
	form.find(selectors.reset).remove();
	view.find(selectors.view).remove();
	i = 0;
	select.find(selectors.what).each(function() {
		input = inputs.picture
			.clone()
			.attr('name', o.name.replace(/:I:/gi, i++))
			.val($(this).attr(o.attr))
			.addClass(selectors.reset.replace(/\./gi, ' '));
		
		form.append(input);
		if (view.find(selectors.view + '[' + o.attr + '="' + $(this).attr(o.attr) + '"]').length == 0) {
			if (typeof callback == 'function') {
				callback($(this));
			} else {
				view.prepend($(this).clone());
			}
		}
	});
}

function addTag(el, to) {
	if (typeof el.attr('url') != 'undefined') {
		call(el.attr('url'), { 'tag[name]' : el.val() }, function(response, error) {
			if (processResponse(response, error)) {
				response= toJSON(response);
				if (typeof response.exists == 'undefined' || !response.exists) {
					to.append($('<span />').addClass('tag').html(el.val()));
				}
			}
		});
	}
}

function show(url) {
	call(url, {}, function(response, error) {
		if (!error) {
			$('body').append(response);
		}
	});
}

$(document).ready(function(){
	bindTriggers();
});
