$(document).ready(function() {
	$('a[rel*=external]').each(function() {
		this.target = "_blank";
	});
});

var supernewsTimeout;
var supernews = [];
var j = 1;

function showSupernews(i, k, speed) {
	clearTimeout(supernewsTimeout);
	
	if (i > 0) {
		if (i >= supernews.length - 1) {
			j = 0;
		} else {
			j = i + 1;
		}
	} else {
		i = j;
		
		if (k >= 0) {
			j = k;
		} else {
			j = i + 1;
		}
	}

	if (i != j) {
		if (speed == 'normal') {
			$('#thumbNews_' + j).addClass("active");
			$("#supernews_" + j).fadeIn(2000);
			$('#imgThumbSupernews_' + j).fadeTo("fast", 1);
			$('#thumbNews_' + i).removeClass("active");
			$("#supernews_" + i).fadeOut(2000);
			$('#imgThumbSupernews_' + i).fadeTo("fast", 0.5);
		} else {
			$('#thumbNews_' + j).addClass("active");
			$("#supernews_" + j).show();
			$('#imgThumbSupernews_' + j).fadeTo("fast", 1);
			$('#thumbNews_' + i).removeClass("active");
			$("#supernews_" + i).hide();
			$('#imgThumbSupernews_' + i).fadeTo("fast", 0.5);
		}
	} else {
		$("#supernews_" + i).show();
	}
	
	try {
		$('#supernewsTitle').html(unescape(supernews[j].type));
		$('#supernewsSubtitle').html(unescape(supernews[j].title));
		$('#lnkSupernews_' + j).bind('click', function() { getUrl(supernews[j].url) });
		$('#lnkThumbSupernews_' + j).bind('click', function() { getUrl(supernews[j].url) });
		$('#subtitles').bind('click', function() { getUrl(supernews[j].url) });
	} catch(ex) {
		
	}
	supernewsTimeout = setTimeout('showSupernews('+j+', -1, \'normal\')', 5000);
}

function getUrl(url) {
	window.location.href = url;
}

//functie care face verificare JS pe email
function checkEmail(emailStr){
	var regex = /^([a-z0-9._-](\+[a-z0-9])*)+@[a-z0-9.-]+\.[a-z]{2,6}$/i;

	if (regex.test(emailStr)) return true;
	else return false;
}

function validateEmail(listId) {
	var err=0; 
	var msg="Nu ai completat corect formularul: "; 
	obj = null;
	 
	var so1 = $('#email_' + listId);
	
	if(so1.val() == "") { 
		err++; 
		msg+= "\nNu ai introdus adresa de email"; 
		if(obj==null){
			obj=so1;
		}
	}else{ 
		if(checkEmail(so1.val()) == false){
			err++; 
			msg += "\nAdresa de e-mail este invalidă"; 
			if(obj==null){obj=so1;}
		}
	}
	
	 if(err!=0){jAlert(msg, "Avertizare"); if(obj!=null){ obj.focus(); } return false;}else{return true;}
}

function show_comments_settings(id){
	$("#head" + id).hide();
	
	$("#comments" + id).hide();
	$("#settings" + id).show();
}

function hide_comments_settings(id){
	$("#head" + id).show();
	
	$("#settings" + id).hide();
	$("#comments" + id).show();
}

function show_media(index, mediaType){
	if(index >= 0 && mediaType != ''){
		var htmlString = '';
		//window.console.log(pageType + ' - ' + index + ' - ' + nrMediaItems);
		$("#article_media").attr('src', $("#media_item_" + index).attr('rel') + "?width=" + $("#article_media").attr("width"));
		$("#gallery_navigation").empty();
		
		if(pageType == 'imagini' || pageType == 'videoclipuri'){
			if(index != 0) htmlString += '<a class="anav prev" title="Poza anterioară" href="javascript:;" onclick="show_media(' + (index-1) + ', \'' + mediaType + '\'); return false;">Poza anterioară</a>';
			if(index != (nrMediaItems-1)) htmlString += '<a class="anav next" title="Poza următoare" href="javascript:;" onclick="show_media(' + (index + 1) + ', \'' + mediaType + '\'); return false;">Poza următoare</a>';
			$("#current_number_media").html(index+1);
		}else{
			htmlString += '<li class="prev">';
			htmlString += '<a class="icon ';
			if(index == 0) htmlString += 'icGNavLInactive"';
			else htmlString += 'icGNavL" onclick="show_media(' + (index-1) + ', \'' + mediaType + '\'); return false;" ';
			htmlString += 'title="Înapoi" href="javascript:;">Înapoi</a>';
			htmlString += '<li class="next"><a class="icon ';
			if(index == (nrMediaItems-1)) htmlString += 'icGNavRInactive"';
			else htmlString += 'icGNavR" onclick="show_media(' + (index + 1) + ', \'' + mediaType + '\'); return false;" ';
			htmlString += ' title="Înainte" href="javascript:;">Înainte</a></li>';
		}
		
		$("#gallery_navigation").html(htmlString);
	}
}

function show_advanced_search(){
	$("#advanced_search").toggle();
}

//functie care face url_title()-ul din PHP
function url_title(string) {
	$.ajax({
		type: "POST",
		url: baseUrl + "/unelte/url_title",
		data: "string=" + string.replace('&', ''),
		async: false,
		success: function(msg){
			urlTitle = msg;
		}
	});
	return urlTitle;
}

function search_pagination(pageUrl){
	if(pageUrl != ''){
		$('#advSearchForm').attr('action', pageUrl)
		$('#advSearchForm').submit();
	}
}

function switch_to_advanced_search(){
	$('#advSearchForm').attr('action', baseUrl + '/cautare/' + stringToSearch)
}

function refresh_captcha(){
	$.ajax({
		url: baseUrl+"/comentarii/refresh_captcha",
		type: "POST",
		data: "",
		success: function(data){
			//data = eval("(" + data + ")");
			$("#captcha_code").html(data);
		}
	});
}

function add_comments(form){
	//window.console.log($(form));
	actionUrl = $(form).attr('action');
	//window.console.log($("#cMessage"));
	if ($("#cName").val()=='nume*') {
		$("#cName").val(''); 
	}
	//window.console.log($("#cName"));
	if ($("#cEmail").val()=='e-mail*') {
		$("#cEmail").val('');
	} 
	if ($("#cMessage").val()=='mesaj*') {
		$("#cMessage").val('');
	}
	//return false;
	$.ajax({
		type: "POST",
		url: actionUrl,
		data: $(form).serialize(),
		dataType : 'json',
		//async: false,
		success: function(msg){
			
			if (msg.error==1){
				//window.console.log($("#captcha_code_container .c-error"));
				//window.console.log(msg.error_field);
				//(jQuery.inArray("John", arr));
				$("#commentsForm input,textarea").removeClass('error');
				var errorMessage = '';
				if ($.inArray("captcha",msg.error_field)>-1){
					//window.console.log('intra aici');
					$("#captcha_code_container .c-error").show();
					$("#captcha").addClass('error');
				}
				if ($.inArray("comment_name",msg.error_field)>-1){
					//$("#captcha_code_container .c-error").show();
					$("#cName").addClass('error');
				}
				if ($.inArray("comment_email",msg.error_field)>-1){
					//$("#captcha_code_container .c-error").show();
					$("#cEmail").addClass('error');
				}
				if ($.inArray("comment_message",msg.error_field)>-1){
					//$("#captcha_code_container .c-error").show();
					$("#cMessage").addClass('error');
				}
				$.each(msg.message, function(i,message) {
					errorMessage+=message+"<br>";
					//window.console.log(errorMessage);
				});
				$("#comments_error").addClass("error");
				$("#comments_error").addClass("error-message");
				$("#comments_error").html(errorMessage);
				$("#comments_error").show();
				refresh_captcha();
				//refresh
			} else {
				//$("#commentsForm input:text").val('');
				$("#commentsForm")[0].reset();
				$("#commentsForm input,textarea").removeClass('error');
				$("#captcha_code_container .c-error").hide();
				$("#comments_error").removeClass("error");
				$("#comments_error").removeClass("error-message");
				
				//error error-message
				//$("#comments_error").html('Comentariu publicat cu succes');
				$("#comments_error").html('Comentariu adaugat cu succes. Acesta va fi publicat pe site dupa moderare.');
				$("#comments_error").show();
				show_comments(msg.url);
				refresh_captcha();
			}
			//window.console.log(msg);
			//alert(msg);
			//urlTitle = msg;
			//window.console.log(msg);
		}
	});
	return false;
}
function show_comments(link){
		var comments_limit=0;
		if (typeof($("#comments_limit").val())!='undefined'){
			comments_limit = $("#comments_limit").val();
		}
		$.ajax({
				type: "POST",
				url: link,
				//async: false,
				data: "comments_limit="+comments_limit,
				success: function(msg) {
					$('#comment_pages').remove();
					$('#comments_list').replaceWith(msg);
					
				}
			});
}

function show_comments_pagination(link){
}

function report_comment(commentId){
		$.ajax({
				type: "POST",
				data: "comment_id=" + commentId,
				url: baseUrl + "/comentarii/report",
				//dataType: "json",
				success: function(msg) {
					if (msg=='OK'){
						$("#report_"+commentId).hide();
						//window.console.log($("#report_"+commentId));
					}
				}
			});
}

function subscribe_comment(){
	$.ajax({
				type: "POST",
				data: $("#subscribeComments").serialize(),//"email=" + commentId,
				url: baseUrl + "/comentarii/subscribe",
				dataType: "json",
				success: function(msg) {
					window.console.log(msg);
				}
			});
}

function respond_comment(commentId,name){
	//var prev = $("#cMessage").val();
	//window.console.log($("#response_id"));
	
	$("#response_id").val(commentId);
	$("#cMessage").val('@'+name);
	window.location.href='#comenteaza';
}

function show_article_page(elemName){
	var itemUrl = $("#" + elemName).val();
	//window.location.href = itemUrl;
}

function toggleLogin(){
	$("#header .user-login").toggle(); 
}

function toggleSubscribeComment(){
	$("#subscribeCommentsBox").toggle();
}

function closeUserInfo(){
	$("#userInfoBox").hide();
	//var exdate=new Date();
	setCookie('hide_user_info',1,7);
}

function save_comments_settings(id){
	//window.console.log($("#commentPreferences #commentsNo").val());
	setCookie('comments_settings',$("#commentPreferences" + id + " #commentsNo" + id).val(),7);
	//window.console.log($("#commentPreferences #commentsNo").val());
	hide_comments_settings(id);
}

function setCookie(name,value,days)
{
	$.cookie(name, value, { expires: days, path: '/', secure: false });
}

function poll_vote(){
	//window.console.log($('#pollForm input:radio[name=poll_answer]:checked').val()); 
	//window.console.log($("#pollForm input:radio"));
	//return false;
	if(typeof($('#pollForm input:radio[name=poll_answer]:checked').val())!="undefined"){
		$.post(baseUrl+'/poll/vote', $("#pollForm").serialize(), function(data) {
  			$("#w_poll").replaceWith(data);
		});
	}
}
function show_poll_results(pollId){
	$.get(baseUrl+'/poll/result/'+pollId,'', function(data) {
  		$("#w_poll").replaceWith(data);
	});
}

function show_poll_form(){
	$.post(baseUrl+'/poll/form','', function(data) {
  		$("#w_poll").replaceWith(data);
	});
}


