var working = false;
$(function () {
	$('.login-box input').keydown(function (e) {
		if (e.keyCode == 13)
			$('#doLogin').click();
	}).focus(function () {
		$('label[for="' + $(this).attr('id') + '"]').hide();
	}).blur(function () {
		if ($(this).val() == '')
			$('label[for="' + $(this).attr('id') + '"]').show();
	});
	$('.login-box .login').click(function (e) {
		$(this).parent().parent().addClass('active');
		e.preventDefault();
	});

	$('.login-box .fechar').click(function (e) {
		if ($(this).text() == 'sair') {
			doLogout();
		} else {
			$(this).parent().parent().removeClass('active');
		}
		e.preventDefault();
	});

	$('.ico-favoritos:not(.doNothing)').live('click', function (e) {
		e.preventDefault();
		checkLogin({
			action: 'SetFavorite',
			params: {
				id_user: $(this).attr('user'),
				id_thing: $(this).attr('thing'),
				id_entity: $(this).attr('entity'),
				remove: $(this).attr('remove') == 1,
				location: window.location.href,
				onComplete: 'SetFavoriteOK("' + $(this).attr('user') + '","' + $(this).attr('thing') + '","' + $(this).attr('entity') + '");'
			}
		});
	});

	$('.ico-like:not(.doNothing)').live('click', function (e) {
		e.preventDefault();
		checkLogin({
			action: 'SetThumbUp',
			params: {
				id_user: $(this).attr('user'),
				id_thing: $(this).attr('thing'),
				id_entity: $(this).attr('entity'),
				location: window.location.href,
				onComplete: 'SetThumbUpOK("' + $(this).attr('user') + '","' + $(this).attr('thing') + '","' + $(this).attr('entity') + '");'
			}
		});
	});

	$('.ico-facebook:not(.doNothing)').live('click', function (e) {
		e.preventDefault();
		var url = 'http://www.endeavor.org.br/share?item=' + $(this).attr('entity') + '|' + $(this).attr('thing')
		window.open('http://www.facebook.com/sharer.php?u=' + url, '', 'width=600px,height=400px');
	});

	$('.ico-twitter:not(.doNothing)').live('click', function (e) {
		e.preventDefault();
		var url = 'http://www.endeavor.org.br/share?item=' + $(this).attr('entity') + '|' + $(this).attr('thing')
		var textTwitter = $(this).attr('title').toString();
		if ((textTwitter).length > 90) {
			textTwitter = encodeURIComponent(textTwitter.substring(0, 87) + '...');
		} else {
			textTwitter = encodeURIComponent(textTwitter);
		}
		window.open('https://twitter.com/intent/tweet?original_referer=' + encodeURIComponent(window.location.href) + '&source=tweetbutton&text=' + textTwitter + '&url=' + encodeURIComponent(url) + '&via=endeavorbrasil', '', 'width=600px,height=400px');
	});

	$('#doLogin').click(function (e) {
		e.preventDefault();
		return doLogin();
	});

	showPartners();
});

var added = new Array();
function showPartners() {
	var c = 0;
	var ar = $('.partners > div > ul > li').toArray();
	$('.partners > div > ul').remove();
	$('.partners > div').append('<ul style="height: 43px;"></ul>');
	for (var i = 0; i < ar.length; i++) {
		if (c == 12) {
			$('.partners > div').append('<ul style="height: 43px;"></ul>');
			c = 0;
		}
		var random = Math.round(Math.random() * (ar.length - 1));
		while (checkAdded(random))
			random = Math.round(Math.random() * (ar.length - 1));
		added.push(random);
		$('.partners > div > ul:last').append(ar[random]);
		c++;
	}
	$('.partners > div > ul:not(:first)').hide();
	$('.partners > div > ul:first > li').show();
	setTimeout(function () {
		setInterval(function () {
			$('.partners > div > ul:visible').addClass('notOpen').fadeOut(500, function () {
				$('.partners > div > ul:not(.notOpen):first').fadeIn(500, function () {
					$('.notOpen').removeClass('notOpen');
				});
			});
		}, 10000);
	}, 10000);
}
function checkAdded(v) {
	var isAdded = false;
	for (var k = 0; k < added.length; k++) {
		if (added[k] == v) {
			isAdded = true;
			break;
		}
	}
	return isAdded;
}

function SetFavoriteOK(user, thing, entity) {
	var obj = $('.ico-favoritos[user="' + user + '"][thing="' + thing + '"][entity="' + entity + '"]');
	if (obj.attr('remove') == '1') {
		obj.removeAttr('remove');
		obj.text('Favoritos');
	} else {
		obj.attr('remove', '1');
		obj.text('Remover do Favoritos');
	}
}

function SetThumbUpOK(user, thing, entity) {
	var obj = $('.ico-like[user="' + user + '"][thing="' + thing + '"][entity="' + entity + '"]');
	var txt = $('.ico-like[user="' + user + '"][thing="' + thing + '"][entity="' + entity + '"]:first').text();
	obj.addClass('doNothing');
	obj.text(parseInt(txt) + 1);
}

function getPageUrl(url) {
	if (url != '' && url != undefined) {
		url = url.split('/');
	} else {
		url = window.location.href.split('/');
	}
	return url[url.length - 1];
}
function getPageType(url) {
	if (url != '' && url != undefined) {
		url = url.split('/');
	} else {
		url = window.location.href.split('/');
	}
	return url[3].replace('_', '-');
}

function doAction(obj) {
	switch (obj.action) {
		case 'SaveComment':
			var obj_comment = {
				IDEntity: obj.params.id_entity,
				IDThing: obj.params.id_thing,
				IDUser: obj.params.id_user,
				Review: obj.params.text
			};
			if (obj_comment.IDUser == "" || obj_comment.IDUser == undefined) {
				obj_comment.IDUser = $('.idUser').val();
			}
			var jsonText = JSON.stringify({ obj_review: obj_comment });
			$.ajax({
				type: "POST",
				async: false,
				url: appPath + "services/wsReview.asmx/SaveComment",
				contentType: "application/json; charset=utf-8",
				dataType: "json",
				data: jsonText,
				beforeSend: function () {
				},
				success: function (data, textStatus, jqXHR) {
					tracker(getPageType() + '-comentario', 'enviar', getPageUrl($('.ico-comentarios:first a').attr('href').replace('#comments', '')));
					if (window.location.href != obj.params.location) {
						window.location.href = obj.params.location;
					} else {
						//eval(obj.params.onComplete);
						comment.GetComments(true);
					}
				},
				error: function (jqXHR, textStatus, errorThrown) {
					if (textStatus == 'error' && jqXHR.readyState == 4) alert('Erro:\n' + jqXHR.responseText);
				},
				complete: function () {
				}
			});
			break;
		case 'SetFavorite':
			var favorite = {
				id_user: obj.params.id_user,
				id_thing: obj.params.id_thing,
				id_entity: obj.params.id_entity,
				remove: obj.params.remove.toString()
			}
			if (favorite.id_user == "" || favorite.id_user == undefined) {
				favorite.id_user = $('.idUser').val();
			}
			var jsonText = JSON.stringify(favorite);
			$.ajax({
				type: "POST",
				async: false,
				url: appPath + "services/wsCommon.asmx/SetFavorite",
				contentType: "application/json; charset=utf-8",
				dataType: "json",
				data: jsonText,
				beforeSend: function () {
				},
				success: function (data, textStatus, jqXHR) {
					if (window.location.href != obj.params.location) {
						window.location.href = obj.params.location;
					} else {
						//eval(obj.params.onComplete);
						SetFavoriteOK(favorite.id_user, favorite.id_thing, favorite.id_entity);
					}
				},
				error: function (jqXHR, textStatus, errorThrown) {
					if (textStatus == 'error' && jqXHR.readyState == 4) alert('Erro:\n' + jqXHR.responseText);
				},
				complete: function () {
				}
			});
			break;
		case 'SetThumbUp':
			var thumb = {
				id_user: obj.params.id_user,
				id_thing: obj.params.id_thing,
				id_entity: obj.params.id_entity
			}
			if (thumb.id_user == "" || thumb.id_user == undefined) {
				thumb.id_user = $('.idUser').val();
			}
			var jsonText = JSON.stringify(thumb);
			$.ajax({
				type: "POST",
				async: false,
				url: appPath + "services/wsCommon.asmx/SetThumbUp",
				contentType: "application/json; charset=utf-8",
				dataType: "json",
				data: jsonText,
				beforeSend: function () {
				},
				success: function (data, textStatus, jqXHR) {
					if (window.location.href != obj.params.location) {
						window.location.href = obj.params.location;
					} else {
						//eval(obj.params.onComplete);
						SetThumbUpOK(thumb.id_user, thumb.id_thing, thumb.id_entity);
					}
				},
				error: function (jqXHR, textStatus, errorThrown) {
					if (textStatus == 'error' && jqXHR.readyState == 4) alert('Erro:\n' + jqXHR.responseText);
				},
				complete: function () {
				}
			});
			break;
	}
}

function doAfterLogged() {
	var jsonText = JSON.stringify({ key: "doAfterLogged" });
	$.ajax({
		type: "POST",
		async: false,
		url: appPath + "services/wsRegistration.asmx/GetSession",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		data: jsonText,
		beforeSend: function () {
		},
		success: function (data, textStatus, jqXHR) {
			var jsonText = JSON.stringify({ key: "doAfterLogged" });
			$.ajax({
				type: "POST",
				async: false,
				url: appPath + "services/wsRegistration.asmx/ClearSession",
				contentType: "application/json; charset=utf-8",
				dataType: "json",
				data: jsonText,
				beforeSend: function () {
				},
				success: function (data, textStatus, jqXHR) {

				},
				error: function (jqXHR, textStatus, errorThrown) {
					if (textStatus == 'error' && jqXHR.readyState == 4) alert('Erro:\n' + jqXHR.responseText);
				},
				complete: function () {
				}
			});
			var obj = eval('(' + data.d + ')');
			doAction(obj);
		},
		error: function (jqXHR, textStatus, errorThrown) {
			if (textStatus == 'error' && jqXHR.readyState == 4) alert('Erro:\n' + jqXHR.responseText);
		},
		complete: function () {
		}
	});
}

function checkLogin(obj) {
	var idUser = $('.idUser').val();
	if (idUser == '') {
		var jsonText = JSON.stringify({ key: "doAfterLogged", value: obj });
		$.ajax({
			type: "POST",
			async: false,
			url: appPath + "services/wsRegistration.asmx/SetSession",
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			data: jsonText,
			beforeSend: function () {
			},
			success: function (data, textStatus, jqXHR) {
				$('html, body').animate({
					scrollTop: $(".login-box").offset().top
				}, 1000, function () {
					$('.login-box .login').click();
				});
			},
			error: function (jqXHR, textStatus, errorThrown) {
				if (textStatus == 'error' && jqXHR.readyState == 4) alert('Erro:\n' + jqXHR.responseText);
			},
			complete: function () {
			}
		});
	} else {
		doAction(obj);
	}
}

function doLogout() {
	if (working) return false;
	$.ajax({
		type: "POST",
		url: appPath + "services/wsRegistration.asmx/DoLogout",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		beforeSend: function () {
			working = true;
			$('#loginStatusText').text('Entrando...');
		},
		success: function (data, textStatus, jqXHR) {
			document.location.reload(true);
			/*$('.loginStatusText').text('Faça seu login e acesse conteúdos restritos');
			$('#txtEmail').val('E-mail');
			$('#txtSenha').val('Senha');
			$('.btnLogin').css('display', '');
			$('.btnClose').text('fechar').css('display', '');
			$('.idUser').val('');
			$('.login-form').css('display', '');*/
		},
		error: function (jqXHR, textStatus, errorThrown) {
			if (textStatus == 'error' && jqXHR.readyState == 4) alert('Erro:\n' + jqXHR.responseText);
		},
		complete: function () {
			working = false;
		}
	});
}
function doLogin() {
	if (working) return false;

	$('#txtEmail, #txtSenha').removeClass('erro');
	var error = false;
	if (validator.isEmpty($('#txtSenha').val())) {
		$('#txtSenha').focus();
		$('#txtSenha').addClass('erro');
		error = true;
	}
	if (!validator.isEmail($('#txtEmail').val())) {
		$('#txtEmail').focus();
		$('#txtEmail').addClass('erro');
		error = true;
	}
	$('#loginErro').hide();
	if (error) {
		$('#loginErro').show();
		return false;
	}
	var email = $('#txtEmail').val();
	var password = $('#txtSenha').val();

	var jsonText = JSON.stringify({ email: email, password: password });
	$.ajax({
		type: "POST",
		url: appPath + "services/wsRegistration.asmx/GetByCredentials",
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		data: jsonText,
		beforeSend: function () {
			working = true;
			$('#loginStatusText').text('Entrando...');
		},
		success: function (data, textStatus, jqXHR) {
			if (data.d == '') {
				$('#txtEmail, #txtSenha').addClass('erro');
			} else {
				var obj = eval('(' + data.d + ')');
				document.location.reload(true);
				/*
				$('.loginStatusText').text('Bem vindo: ' + obj.Name);
				$('.btnLogin').hide();
				$('.btnClose').text('sair').show();
				$('.idUser').val(obj.ID);
				$('.login-form').hide();
				doAfterLogged();*/
			}
		},
		error: function (jqXHR, textStatus, errorThrown) {
			if (textStatus == 'error' && jqXHR.readyState == 4) alert('Erro:\n' + jqXHR.responseText);
		},
		complete: function () {
			working = false;
		}
	});




}

function textLimit(obj) {
	var maxlimit = obj.maxlimit;
	var element = obj.element;
	var countEl = obj.countEl;
	var textFormat = '';
	if (obj.textFormat != '') {
		textFormat = obj.textFormat;
	}
	if ($(element).val().length > maxlimit) {
		$(element).val($(element).val().substring(0, maxlimit));
	} else {
		$(countEl).text((maxlimit - $(element).val().length).toString() + ' Caracteres');
	}
}
function ShowSelection(textComponent) {
	var selectedText;
	// IE version
	if (document.selection != undefined) {
		textComponent.focus();
		var sel = document.selection.createRange();
		selectedText = sel.text;
	}
	// Mozilla version
	else if (textComponent.selectionStart != undefined) {
		var startPos = textComponent.selectionStart;
		var endPos = textComponent.selectionEnd;
		selectedText = textComponent.value.substring(startPos, endPos)
	}
	return selectedText;
}
function inscreveEvento(idEvento) {
	$("#ctl00_ctl00_main_columnContent_linkInscricao").hide();
	$.ajax({
		type: "GET",
		url: "/inscreveEvento.aspx",
		data: "idevento=" + idEvento,
		success: function (msg) {
			$("#ctl00_ctl00_main_columnContent_linkInscricao").attr('onclick', 'javascript:;');
			$("#ctl00_ctl00_main_columnContent_linkInscricao").html("Inscrição realizada com sucesso!");
			$("#ctl00_ctl00_main_columnContent_linkInscricao").show();
		}
	});
}
$(function () {
	$('a.list').click(function () {
		$(this).addClass('active');
		$('.box').removeClass('active');
		$('.tab-content').addClass('list');
	});
	$('a.box').click(function () {
		$(this).addClass('active');
		$('.list').removeClass('active');
		$('.tab-content').removeClass('list');
	});

});



