var IE=/*@cc_on!@*/!1;

$(document).ready(function(){
	if ((typeof(tycpr) != "undefined") && (currentPage == 'media') && (authorized))
		new AjaxUpload('import', {
			action: '/contrelement.php',
			name: 'uploadfile',
			autoSubmit: true,
							
			data: {
				mod: 'import',
				category: '#import-category'
			},
													
			onSubmit: function(file, ext){
				var re = new RegExp("^(txt|csv|xlsx?)$", "i");
				
				if (!ext.toString().match(re)){
					alert('File extension error! Only .txt, .csv, .xls and .xlsx files allowed!');
					return false;
				}	
			},

			onComplete: function(file, response){
				resetFilterLite();
				while (response.match(/(<[^>]+>)/)) response = response.replace(/(<[^>]+>)/, '');
				mediaMessage(response + ' ' + (response == 1 ? 'entry' : 'entries') + ' were successfully imported!');
				$('#import-halp').hide();
			}
		});
});

var popup = ['import-halp', 'add-category'];

function closePopups(event){
	for (var i = 0; i < popup.length; i++){
		var node = event.target;
		var pass = false;

		while (node.nodeName.toLowerCase() != 'html'){
			if (node.getAttribute('id') == popup[i]){
				pass = true;
				break;
			} else if (node.getAttribute('id') == popup[i] + '-toggle'){
				$('#' + popup[i]).toggle();
				pass = true;
				break;
			}
			node = node.parentNode;
		}

		if (!pass) $('#' + popup[i]).hide();
	}
}

function addCategory(){
	$.ajax({
		type: "POST",
		url: "/contrelement.php",
		data: "mod=addCategory&category=" + $('#add-category-input').attr('value'),
		success: function(msg){
			$('#add-category-input').attr('value', '');
			$('#mediaStatus').html(msg);
			setTimeout(function(){$('#mediaStatus').html('');}, 10000);
			$('#add-category').hide();
		}
	});
}

$(window).click(closePopups);

function addeditMedia(){
	$.ajax({
		type: "POST",
		url: "/contrelement.php",
		data: "mod=addeditMedia&" + $('#media').serialize(),
		success: function(msg){
			if (msg) alert(msg);
			else location.href = '/account/media/';
		}
	});	
}

function resetFilterLite(){
	$('#filter-search').attr('value', 'Search...');
	$('#filter-page').attr('value', 1);
	media();
}

function resetFilter(){
	$('#filter-category').attr('value', -1);
	$('#filter-order').attr('value', 0);
	$('#filter-search').attr('value', 'Search...');
	$('#filter-page').attr('value', 1);
	media();
}

function shiftPage(s){
	var cu = parseInt($('#filter-page').attr('value'));
	var ic = document.getElementById("filter-page").getElementsByTagName("option").length;
	
	var p = cu + s;
	if (p > ic) p = ic;
	else if (p < 1) p = 1;
	
	if (p != cu){
		$('#filter-page').attr('value', p);
		media();
	}
}

function getPages(){
	$.ajax({
		type: "POST",
		url: "/contrelement.php",
		data: "mod=getPages&category=" + $('#filter-category').attr('value') + 
		"&search=" + $('#filter-search').attr('value') + "&page=" + $('#filter-page').attr('value'),
		success: function(msg){
			$('#filter-page').html(msg);
		}
	});
}

function getCategories(){
	$.ajax({
		type: "POST",
		url: "/contrelement.php",
		data: "mod=getCategories&category=" + $('#filter-category').attr('value'),
		success: function(msg){
			$('#filter-category').html(msg);
		}
	});
}

function media(){
	var s = $('#filter-category').attr('value');
	s = s < 0 ? 0 : s;
	$('#import-category').attr('value', s);
	
	$.ajax({
		type: "POST",
		url: "/contrelement.php",
		data: "mod=media&category=" + $('#filter-category').attr('value') + "&order=" + $('#filter-order').attr('value') + 
		"&search=" + $('#filter-search').attr('value') + "&page=" + $('#filter-page').attr('value'),
		success: function(msg){
			getPages();
			getCategories();
			$('#media-contacts').html(msg);
		}
	});
}

function deleteMedia(id){
	if (confirm('Are you shure you want to delete this entry?'))
	$.ajax({
		type: "POST",
		url: "/contrelement.php",
		data: "mod=deleteMedia&id=" + id,
		success: function(msg){
			$('#media-contact-' + id).slideUp(300);
		}
	});
}

function formsend(){
	$('.form-right input, .form-right select').css('background-color', '#FFF');
	$.ajax({
		type: "POST",
		url: "/contrelement.php",
		data: "mod=formsend&" + $("#info").serialize(),
		success: function(msg){
			$('.resmice').show(300); 
			if (msg.match(/1/)){
				$('#sudada').html('E-mail incorrect or already exists!');
				$('*[name="email"]').css('background-color', '#F99');
			}
			if (msg.match(/2/)){
				$('#sudada').html('Password incorrect! Password length should be from 6 to 20 chars.');
				$('*[name="password"]').css('background-color', '#F99');
				$('*[name="password2"]').css('background-color', '#F99');
			}
			if (msg.match(/3/)){
				$('#sudada').html('Please choose your country');
				$('*[name="country"]').css('background-color', '#F99');
			}
			if (msg.match(/4/)){
				$('#sudada').html('Please choose your PR position');
				$('*[name="whoami"]').css('background-color', '#F99');
			}
			
			if (msg.length > 1) $('#sudada').html('Some fields are filled incorrect!');
			
			if (msg) $('.resmice').css('background-color', '#F66');
			else if (!$('*[name="type"]').attr('value') == 'Register'){ // register success
				$('#send').hide(300);
				$('.resmice').css('background-color', '#6C6');
				$('#sudada').html('Please follow link sent to your email to activate account');
			} else { // edit success
				$('.resmice').css('background-color', '#6C6');
				$('#sudada').html('You have successfully edited your profile');
				setTimeout(function(){
					$('.resmice').hide(300);
				}, 5000);
			}
		}
	});
}

var authOk = false;
function auth(){
	if (authOk)	return true;
	$.ajax({
		type: "POST",
		url: "/contrelement.php",
		data: "mod=auth&" + $("#auth").serialize(),
		
		success: function(msg){	
			if (!msg){
				authOk = true;
				$("#auth").submit();
			}
			else {
				if (msg == 1) msg = 'Incorrect e-mail or password!';
				else if (msg == 2) msg = 'You should enable cookies for authorization';
				$('#sudada').html(msg);
				$(".resmice").show(300);
				setTimeout(function(){
					$(".resmice").hide(300);
				}, 5000);
			}
		}
	});
	return false;
}

function indexAuth(){
	$.ajax({
		type: "POST",
		url: "/contrelement.php",
		data: "mod=auth&" + $("#indexAuth").serialize(),
		
		success: function(msg){	
			if (!msg) location.href = '/account/';
			else {
				if (msg == 1) msg = 'Incorrect e-mail or password!';
				else if (msg == 2) msg = 'You should enable cookies for authorization';
				alert(msg);
			}
		}
	});
	return false;	
}

function lostpassword(){
	$.ajax({
		type: "POST",
		url: "/contrelement.php",
		data: "mod=lostpassword&email=" + $("input[name='email']").attr('value'),
		
		success: function(msg){	
			if (!msg){
				$('.resmice').css('background-color', '#6C6');
				$('#sudada').html('E-mail with your password was successfully send!');
				$(".resmice").show(300);
				$('#send').attr('disabled', 'disabled');
				$('#send').attr('class', 'inactive-button');
			}
			else {
				$(".resmice").show(300);
				setTimeout(function(){
					$(".resmice").hide(300);
				}, 5000);
			}
		}
	});
}

function mediaMessage(msg){
	$('#mediaStatus').html(msg);
	setTimeout(function(){$('#mediaStatus').html('');}, 10000);
}

function deleteSelectedMedia(){
	var ch = $('.mediacheckbox');
	if (ch.length == 0){
		mediaMessage('No entries found');
		return;
	} 
	var entriesSelected = 0;
	var ids = "";
	for (var i = 0; i < ch.length; i++){
		if (ch[i].checked){
			entriesSelected++;
			ids += "|" + ch[i].id.replace(/^media\-check\-/, "");
		}
	}
	
	if ((entriesSelected == 1) && (!confirm('Are you shure you want to delete this entry?'))) return;
	if ((entriesSelected > 1) && (!confirm('Are you shure you want to delete these entries?'))) return;
	if (!entriesSelected){
		mediaMessage('No entries selected');
		return;
	}
	
	$.ajax({
		type: "POST",
		url: "/contrelement.php",
		data: "mod=deleteSelectedMedia&ids=" + ids.substr(1),
		success: function(msg){	
			media();
			mediaMessage((entriesSelected == 1 ? "One entry was" : entriesSelected + " entries were") + " successfully deleted");
		}
	});
}

function ajaxsend() {
	$('.form').css('background-image', 'url(img/form.png)');
	$('.codefl').css('background-image', 'url(img/capha.png)');
	$('.text').css('background-image', 'url(img/message.png)');
	$.ajax({
		type: "POST",
		url: "/contrelement.php",
		data: "mod=abuse&" + $("#abuse").serialize(),
		success: function(msg){
		if (msg == ''){
			$('#xx').css('display', 'none');
			$('#resulr').html("Thank you! Your message has been sent.");
			return;
		}
		if (msg.match(/8/)){
			$('#xx').html('<div id="xx2"><img src="/img/cookie.png"/> You should enable cookies to send message</div>');
			return;
		}
		if (msg.match(/5/)){
			$('#email').css('background-image', 'url(img/form_er.png)');
			$('#resulr').html("Some fields are filled incorrectly");
			if (!IE)
				$('#resulr').html("Some fields are filled incorrectly");
		}
		if (msg.match(/7/)){
			$('#name').css('background-image', 'url(img/form_er.png)');
			$('#resulr').html("Some fields are filled incorrectly");
			if (!IE)
				$('#resulr').html("Some fields are filled incorrectly");
		}
		if (msg.match(/4/)){
			$('#text').css('background-image', 'url(img/message_er.png)');
			$('#resulr').html("Some fields are filled incorrectly");
			if (!IE)
				$('#resulr').html("Some fields are filled incorrectly");
		}
		if (msg.match(/1/)){
			$('#resulr').html("Some fields are filled incorrectly");
			$('.codefl').css('background-image', 'url(img/capha_er.png)');
			if (!IE)
				$('#resulr').html("Some fields are filled incorrectly");

		}
	}})}

$(document).ready(function () {
	$('.form').focus(function () {						
		$(this).css('background-image', 'url(img/form.png)');
	});
	$('#text').focus(function () {						
		$(this).css('background-image', 'url(img/message.png)');
	});
	$('.codefl').focus(function () {						
		$(this).css('background-image', 'url(img/capha.png)');
	});
	
	$('.form-right input, .form-right select').focus(function () {						
		$(this).css('background-color', '#FFF');
	});
	
});

function checkboxToggle(event, id){
	if ((event.target.getAttribute('id') != null) && (event.target.getAttribute('id').match(/^media\-check\-\d+$/))) return;
	if ($('#' + id).attr('checked')) $('#' + id).attr('checked', '');
	else $('#' + id).attr('checked', 'checked');
}

function selectAll(){
	var s = 'checked';
	if ($('input[type="checkbox"]:checked').length == $('input[type="checkbox"]').length) s = '';
	for (var i = 0; i < $('input[type="checkbox"]').length; i++) $('input[type="checkbox"]' + (i?':gt('+(i-1)+')':'')).attr('checked', s);
}

function showHint(text){
	$("#popup_text_hidden").html("<img class='quote' src='/img/cav_l.gif'><p>" + text + "</p><img class='quoter' src='/img/cav_r.gif'>"); 
	$(".popup_text").toggle();
}
