App = {};

$(document).ready(function () {
	
	if ($.browser.msie) {
		(function($) {
		    var originalLive = jQuery.fn.live;
		    jQuery.fn.live = function(types) {
		        var self = this;
		        var args = arguments;
		        if (types == 'click') {
		            setTimeout(function() {
		                originalLive.apply(self, args);
		            }, 0);
		        } else {
		            originalLive.apply(self, args);
		        }
		    };
		})(jQuery);
	}
	
	$(document).keydown(function(e) {
		if ((e.target.tagName.toLowerCase() == 'textarea') || (e.target.tagName.toLowerCase() == 'input')) {
			return;
		}
		
		if (e.keyCode == 37) { // left
			var href = $('a.key-nav-left').attr('href');
			if (href) {
				window.location.href = href;
				return false;
			}
		}
		if (e.keyCode == 39) { // right
			var href = $('a.key-nav-right').attr('href');
			if (href) {
				window.location.href = href;
				return false;
			}
		}
	});

	
	
	$('#userstatus').live('dblclick', function () {
		var p = $(this).find('p');
		var form = $('#userstatus form');
		if (form.size() > 0) {
			form.show().find('input:text').val(p.html()).select();
			p.hide();
		}
	});
	$('body').live('click', function (e) {
		try {
			if (!$(e.originalTarget).parents('#userstatus').length && !$(e.target).parents('#userstatus').length) {
				$('#userstatus form').hide();
				$('#userstatus p').show();
			}
		} catch (e) {
			
		}
	});
	
	
	$('.gallery-item-desc-edit').live('dblclick', function() {
		$('.gallery-item-desc-edit').hide();
		$('.gallery-item-desc-form').show();
		$('.gallery-item-desc-form input:text').select();
	});
	
	
	$('#add-more-photos').live('click', function () {
		$(this).parent().before('<label><span>&nbsp;</span><input type="file" name="userfile['+uniqid()+']" /></label>');
		$(this).parent().before('<label><span>&nbsp;</span><input type="file" name="userfile['+uniqid()+']" /></label>');
		$(this).parent().before('<label><span>&nbsp;</span><input type="file" name="userfile['+uniqid()+']" /></label>');
		$(this).parent().before('<label><span>&nbsp;</span><input type="file" name="userfile['+uniqid()+']" /></label>');
		$(this).parent().before('<label><span>&nbsp;</span><input type="file" name="userfile['+uniqid()+']" /></label>');
		
		return false;
	});
	
	$('#col-main div.comment a.respond').live('click', function () {
		$(this).hide();
		$(this).siblings('form').show();
		$(this).siblings().find('textarea').focus();
		
		return false;
	});
	
	$('#col-main div.comment textarea').live('blur', function () {
		if ($(this).hasClass('nohide')) return false;
		
		if ($(this).context.value == '') {
			$(this).parents('form').hide();
			$(this).parents('form').siblings('a.respond').show();
		}
	
		return false;
	});
	
	$('form.commentform').live('submit', function () {
		var txt = $(this).find('textarea').val();
		if (txt.length == 0) return false;
		
		var params = {txt: txt};

		$(this).find('input').each(function (idx, el) {
			params[el.name] = el.value;
		});
		
		var form = $(this);
		$.ajax({
			type: 'POST',
			url: this.action+'/ajax/1',
			data: params,
			success: function (msg) {
				if (msg.success) {
					var comments = form.siblings('.comments');
					if (!comments.length) {
						comments = $('.comments');
					}
					comments.append(msg.data);
					
					form.find('textarea').val('')
					if (form.hasClass('hidden')) {
						form.hide();
						form.siblings('a.respond').show();
					}
				} else {
					alert(msg.error);
				}
			},
			dataType: 'json'
		});
	
		return false;
	});
	
	$('#col-main div.comment a.allcomments').live('click', function () {
		var link = $(this);
		$.ajax({
			type: 'POST',
			url: this.href,
			success: function (msg) {
				if (msg.success) {
					link.siblings('.comments').html(msg.data);
					
					link.hide();
				} else {
					alert(msg.error);
				}
			},
			dataType: 'json'
		});
	
		return false;
	});
	
	$('#wall-more').live('click', function () {
		var link = $(this);
		$.ajax({
			type: 'POST',
			url: this.href,
			success: function (msg) {
				if (msg.success) {
					link.parent().before(msg.data);
					link.parent().remove();
				} else {
					alert(msg.error);
				}
			},
			dataType: 'json'
		});
	
		return false;
	});
	
	$('div.comment').live('mouseover', function () {
		$(this).find('a.remove').show();
	});
    $('div.comment').live('mouseout', function () {
		$(this).find('a.remove').hide();
	});
	
	$('div.comment a.remove').live('click', function () {
		if (!confirm('Ar tikrai trinti?')) return false;
		
		var that = $(this);
		
		$.ajax({
			type: 'POST',
			url: this.href+'/ajax/1',
			success: function (msg) {
				if (msg.success) {
					var response = that.parents('div.response');
					if (response.size() > 0) {
						response.remove();
					} else {
						that.parents('div.comment').remove();
					}
				} else {
					alert(msg.error);
				}
			},
			dataType: 'json'
		});
		
		return false;
	});
	
	
	$('div.user-list-item').live('mouseover', function () {
		$(this).find('a.makeadmin').show();
		$(this).find('a.removeuser').show();
	});
    $('div.user-list-item').live('mouseout', function () {
    	$(this).find('a.makeadmin').hide();
		$(this).find('a.removeuser').hide();
	});
	
	$('div.user-list-item a.makeadmin').live('click', function () {
		if (!confirm('Ar tikrai?')) return false;
		
		var that = this;
		
		$.ajax({
			type: 'POST',
			url: this.href+'/ajax/1',
			success: function (msg) {
				if (msg.success) {
					if (that.innerHTML[0] == '+') {
						that.innerHTML = '-Admin';
					} else {
						that.innerHTML = '+Admin';
					}
				} else {
					alert(msg.error);
				}
			},
			dataType: 'json'
		});
		
		return false;
	});
	$('div.user-list-item a.removeuser').live('click', function () {
		if (!confirm('Ar tikrai?')) return false;
		
		var that = this;
		
		$.ajax({
			type: 'POST',
			url: this.href+'/ajax/1',
			success: function (msg) {
				if (msg.success) {
					window.location.reload();
				} else {
					alert(msg.error);
				}
			},
			dataType: 'json'
		});
		
		return false;
	});
	
	
	
	$('.datepicker').datepicker({
		dateFormat: 'yy-mm-dd',
		dayNames: ['Sekmadienis', 'Pirmadienis', 'Antradienis', 'Trečiadienis', 'Ketvirtadienis', 'Penktadienis', 'Šeštadienis'],
		dayNamesMin: ['S', 'P', 'A', 'T', 'K', 'P', 'Š'],
		firstDay: 1,
		maxDate: '-5y',
		minDate: '-100y',
		monthNames: ['Sausis', 'Vasaris', 'Kovas', 'Balandis', 'Gegužė', 'Birželis', 'Liepa', 'Rugpjūtis', 'Rugsėjis', 'Spalis', 'Lapkritis', 'Gruodis'],
		showMonthAfterYear: true,
		yearRange: 'c-100:c',
		changeYear: true
	});
	
	$('.datepicker-full').datepicker({
		dateFormat: 'yy-mm-dd',
		dayNames: ['Sekmadienis', 'Pirmadienis', 'Antradienis', 'Trečiadienis', 'Ketvirtadienis', 'Penktadienis', 'Šeštadienis'],
		dayNamesMin: ['S', 'P', 'A', 'T', 'K', 'P', 'Š'],
		firstDay: 1,
		maxDate: '+5y',
		minDate: '-100y',
		monthNames: ['Sausis', 'Vasaris', 'Kovas', 'Balandis', 'Gegužė', 'Birželis', 'Liepa', 'Rugpjūtis', 'Rugsėjis', 'Spalis', 'Lapkritis', 'Gruodis'],
		showMonthAfterYear: true,
		yearRange: 'c-100:c+5',
		changeYear: true
	});
	
	$('input.toggle-blank').live('focus', function () {
		if (this.value == this.title) {
			this.value = '';
		}
	});
    $('input.toggle-blank').live('blur', function () {
		if (this.value == '') {
			this.value = this.title;
		}
	});
	
	
	
	if (typeof(tinyMCE) !== 'undefined') {
		tinyMCE.init({
		    // General options
			mode: "specific_textareas",
			editor_selector: "tiny_mce",
		    width: "600",
		    theme : "advanced",
		    plugins : "jbimages,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
		
		    // Theme options
		    theme_advanced_buttons1 : "preview,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
		    theme_advanced_buttons2 : "bullist,numlist,|,outdent,indent,|,undo,redo,|,link,unlink,anchor,jbimages,image,|,cleanup,code,|,hr,removeformat,|,sub,sup,|,charmap,emotions,media,advhr,|,fullscreen",
		    theme_advanced_buttons3 : "",
		    //theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
		    theme_advanced_toolbar_location : "top",
		    theme_advanced_toolbar_align : "left",
		    theme_advanced_statusbar_location : "bottom",
		    theme_advanced_resizing : true,
		    relative_urls: false,
		
		    // Example content CSS (should be your site CSS)
		    //content_css : "css/example.css",
		
		    // Drop lists for link/image/media/template dialogs
		    /*template_external_list_url : "js/template_list.js",
		    external_link_list_url : "js/link_list.js",
		    external_image_list_url : "js/image_list.js",
		    media_external_list_url : "js/media_list.js",*/
		
		    // Replace values for the template plugin
		    template_replace_values : {
		        username : "Some User",
		        staffid : "991234"
		    },
		    
			extended_valid_elements: "a[class|name|href|target|title|onclick|rel],iframe[src|style|width|height|scrolling|marginwidth|marginheight|frameborder],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],$elements"
		});
	}
	
	
	
	/*
	 * kalendoriukas
	 */
	 
	$('#datepicker a.nav').live('click', function () {
		$('#datepicker').load(this.href+'/ajax/1');
		
		return false;
	});
	
	
	
	/*
	 * dokumentai
	 */
	
	$('.document-create').live('click', function () {
		$('#document-form-container').show();
		$(this).hide();
		
		return false;
	});
	
	
	
	/*
	 * grupės vartotojai
	 */

	var inputSearch = $("#user-search input[name=user]");
	if (inputSearch.size() > 0) {
		inputSearch.autocomplete({
			source: function(request, response) {
				var groupId = $(this.element).parents('form').find('input[name=groupId]').val();
                $.ajax({
                    url: App.URL.user_search,
                    dataType: "json",
                    data: {
                        term: request.term,
                        groupId: groupId,
                        maxRows: 20
                    },
                    success: function(data) {
                        response(data);
                    }
                })
            },
			minLength: 2,
			select: function(event, ui) {
				inputSearch.val('');
				inputSearch.focus();
				
				$('#userlist').append('<li><label>' +
						'<input type="checkbox" name="users[]" value="'+ui.item.id+'" checked="checked" /> ' +
						(ui.item.age_group_id ? '<span class="user-list-triangle" style="background-image: url(/img/age-groups/' + ui.item.age_group_color + '.png);"></span>' : '') +
						ui.item.display_name +
					'</label></li>');
			}
		}).data('autocomplete')._renderItem = function(ul, item) {
			return $('<li></li>')
				.data('item.autocomplete', item)
				.append('<a><strong>' + item.display_name + '</strong> (' + item.username + ')'+ (item.age_group_id ? '<span class="user-search-triangle" style="background-image: url(/img/age-groups/' + item.age_group_color + '.png);"></span>' : '') +'</a>')
				.appendTo(ul);
		};
	}
	
	
	/*
	 * straipsniai
	 */
	
	var inputSearch = $("input.article-author-select");
	if (inputSearch.size() > 0) {
		inputSearch.autocomplete({
			source: App.URL.user_search,
			minLength: 2,
			select: function(event, ui) {
				inputSearch.val(ui.item.display_name);
				$("input[name=author_id]").val(ui.item.id);
			}
		}).data('autocomplete')._renderItem = function(ul, item) {
			return $('<li></li>')
				.data('item.autocomplete', item)
				.append('<a><strong>' + item.display_name + '</strong> (' + item.username + ')'+ (item.age_group_id ? '<span class="user-search-triangle" style="background-image: url(/img/age-groups/' + item.age_group_color + '.png);"></span>' : '') +'</a>')
				.appendTo(ul);
		};
	}
	
	$('a.link-rate').live('click', function () {
		var link = $(this);
		$.ajax({
			type: 'POST',
			url: this.href,
			success: function (msg) {
				if (msg.success) {
					$('.item-rating').html(msg.data);
				} else {
					alert(msg.error);
				}
			},
			dataType: 'json'
		});
	
		return false;
	});
	
});





function uniqid() {
	if (!window.uniq_uids) {
		window.uniq_uids = {};
	}
	
	var result, i, j;
	result = "";
	while (!j || window.uniq_uids[result] || document.getElementById(result)) {
    	result = "";
		for (j = 0; j < 32; j++) {
			if (j == 8 || j == 12 || j == 16 || j == 20) {
				result = result + "-";
			}
			
			i = Math.floor(Math.random()*16).toString(16).toUpperCase();
			result = result + i;
		}
	}

   //Add the GUID to our master index
   window.uniq_uids[result] = result;
   return result;
} 


