jQuery.fn.filter = function() {
  
  var working = jQuery('<img src="/images/spinner2.gif" width="16" height="16" alt="Samo tren..." />');
  
  // Center type event
  jQuery('#filter-form input:radio[name=tip]').change(function() {
    jQuery('#filtering-submit').html(working);
    jQuery.ajax({
      data:'authenticity_token=' + encodeURIComponent(AUTH_TOKEN) + '&tip=' + jQuery('#filter-form input:radio[name=tip]:checked').val(),
      success:function(request){jQuery('#filtering').html(request);jQuery.fn.filter();},
      type:'get', url:jQuery('#filter-form').attr('action')});
    
    return false;
  });
  
  // Town event
  jQuery('#grad').change(function() {
    jQuery('#filtering-submit').html(working);
    jQuery.ajax({
      data:'authenticity_token=' + encodeURIComponent(AUTH_TOKEN) + '&tip=' + jQuery('#filter-form input:radio[name=tip]:checked').val() + '&grad=' + jQuery('#grad').val(),
      success:function(request){jQuery('#filtering').html(request);jQuery.fn.filter();},
      type:'get', url:jQuery('#filter-form').attr('action')});
    
    return false;
  });
  
  // Quart event
  if(jQuery('#kvart')) {
    jQuery('#kvart').change(function() {
      jQuery('#filtering-submit').html(working);
      jQuery.ajax({
        data:'authenticity_token=' + encodeURIComponent(AUTH_TOKEN) + '&tip=' + jQuery('#filter-form input:radio[name=tip]:checked').val() + '&grad=' + jQuery('#grad').val() + '&kvart=' + jQuery('#kvart').val(),
        success:function(request){jQuery('#filtering').html(request);jQuery.fn.filter();},
        type:'get', url:jQuery('#filter-form').attr('action')});
      
      return false;
    });
  }
}

jQuery.fn.notice = function(href) {
	jQuery.get(href, function(data) {
		$.fn.colorbox({html: '<p>'+ data +'</p>',
									transition: 'none',
									scrolling: false,
									width: '408px',
									opacity: 0.4,
									onComplete: function() {setTimeout(function() {$.fn.colorbox.close();}, 3000);}});
	});
}

// DOM.ready
jQuery(document).ready(function() {
  
  // jQuery('#send-message').colorbox({href:"/gradovi/zagreb/blato", scrolling: false, opacity: 0.4});
	
	jQuery('.login').live('click', function() {
		var url = $(this).attr('href');
		$.fn.colorbox({
			href: url,
			open: true,
			scrolling: false,
			width: '408px',
			opacity: 0.4,
			onComplete: function() {$('#cboxLoadedContent #user_session_login').focus();}
		});
		return false;
	});
	
	jQuery('.register').live('click', function() {
		var url = $(this).attr('href');
		$.fn.colorbox({
			href: url,
			open: true,
			scrolling: false,
			width: '408px',
			opacity: 0.4,
			onComplete: function() {$('#cboxLoadedContent #user_nick').focus();}
		});
		return false;
	});
	
	jQuery('.forgotten').live('click', function() {
		var url = $(this).attr('href');
		$.fn.colorbox({
			href: url,
			open: true,
			scrolling: false,
			width: '408px',
			opacity: 0.4,
			onComplete: function() {$('#cboxLoadedContent #user_email').focus();}
		});
		return false;
	});
	
	jQuery('.message').live('click', function() {
		var url = $(this).attr('href');
		$.fn.colorbox({
			href: url,
			open: true,
			scrolling: false,
			width: '408px',
			opacity: 0.4,
			onComplete: function() {$('#cboxLoadedContent #message_title').focus();}
		});
		return false;
	});
	
	jQuery("#cboxLoadedContent #frmLogin :submit").live('click',
	function() {
		var form = $(this).closest('form');
		var type = 'post';
		var url = form.attr('action');
		// alert(url);
		// var data = $(this).closest('form').serialize();
		var data = "user_session[login]="+ $('#cboxLoadedContent #user_session_login').val() +"&user_session[password]="+ $('#cboxLoadedContent #user_session_password').val() +"&authenticity_token="+ $("#cboxLoadedContent input[name='authenticity_token']").val();
		// alert(data);
		var target = $('#cboxLoadedContent');
		$('#cboxLoadingOverlay, #cboxLoadingGraphic').show();
    $.ajax({type: type, url: url, data: data,
      success: function(data) {
        if (data) {
					$('#cboxLoadingOverlay, #cboxLoadingGraphic').hide();
					if(data.match(/current-profile-name/)) {
						$(target).html('<h2>'+ $(data).find('#current-profile-name').text() +',</h2><br /><h3>uspješno ste prijavljeni!</h3><br /><p>Samo trenutak...</p>');
						var href = document.location.href.split('#');
						document.location.href = href[0];
					} else {
						$(target).html(data);
					}
					$.fn.colorbox.resize();
        }
      }
    });
		
		return false;
	});
	
	jQuery("#cboxLoadedContent #frmRegister :submit").live('click',
	function() {
		var form = $(this).closest('form');
		var type = 'post';
		var url = form.attr('action');
		// alert(url);
		// var data = $(this).closest('form').serialize();
		var data = "user[nick]="+ $('#cboxLoadedContent #user_nick').val() +"&user[login]="+ $('#cboxLoadedContent #user_login').val() +"&user[email]="+ $('#cboxLoadedContent #user_email').val() +"&authenticity_token="+ $("#cboxLoadedContent input[name='authenticity_token']").val();
		// alert(data);
		var target = $('#cboxLoadedContent');
		$('#cboxLoadingOverlay, #cboxLoadingGraphic').show();
    $.ajax({type: type, url: url, data: data,
      success: function(data) {
        if (data) {
					$('#cboxLoadingOverlay, #cboxLoadingGraphic').hide();
					if(data.match(/current-profile-name/)) {
						$(target).html('<h2>'+ $(data).find('#current-profile-name').text() +',</h2><br /><h3>uspješno ste prijavljeni!</h3><br /><p>Samo trenutak...</p>');
						var href = document.location.href.split('#');
						document.location.href = href[0];
					} else {
						$(target).html(data);
					}
					$.fn.colorbox.resize();
        }
      }
    });
		
		return false;
	});
	
	jQuery("#cboxLoadedContent #frmForgotten :submit").live('click',
	function() {
		var form = $(this).closest('form');
		var type = 'post';
		var url = form.attr('action');
		// var data = $(this).closest('form').serialize();
		var data = "user[email]="+ $('#cboxLoadedContent #user_email').val() +"&authenticity_token="+ $("#cboxLoadedContent input[name='authenticity_token']").val();
		var target = $('#cboxLoadedContent');
		$('#cboxLoadingOverlay, #cboxLoadingGraphic').show();
    $.ajax({type: type, url: url, data: data,
      success: function(data) {
        if (data) {
					$('#cboxLoadingOverlay, #cboxLoadingGraphic').hide();
					if(data.match(/current-profile-name/)) {
						$(target).html('<h2>'+ $(data).find('#current-profile-name').text() +',</h2><br /><h3>uspješno ste prijavljeni!</h3><br /><p>Samo trenutak...</p>');
						var href = document.location.href.split('#');
						document.location.href = href[0];
					} else {
						$(target).html(data);
					}
					$.fn.colorbox.resize();
        }
      }
    });
		
		return false;
	});
	
	jQuery("#cboxLoadedContent #frmSendMessage :submit").live('click',
	function() {
		var form = $(this).closest('form');
		var type = 'post';
		var url = form.attr('action');
		// var data = $(this).closest('form').serialize();
		var data = "message[title]="+ $('#cboxLoadedContent #message_title').val() +"&message[replay]="+ $('#cboxLoadedContent #message_replay').val() +"&quick_send="+ $('#cboxLoadedContent #quick_send').val() +"&authenticity_token="+ $("#cboxLoadedContent input[name='authenticity_token']").val();
		var target = $('#cboxLoadedContent');
		$('#cboxLoadingOverlay, #cboxLoadingGraphic').show();
    $.ajax({type: type, url: url, data: data,
      success: function(data) {
        if (data) {
					$('#cboxLoadingOverlay, #cboxLoadingGraphic').hide();
					$(target).html(data);
					$.fn.colorbox.resize();
					if(data.match(/oruka je uspješno poslana/)) setTimeout(function() {$.fn.colorbox.close();}, 3000);

        }
      }
    });
		
		return false;
	});
	
	jQuery('#messages #per_page').change(function() {
		var href = document.location.href.split('?');
		document.location.href = href[0] +'?per_page='+ jQuery(this).val();
	});
	
	jQuery('#messages #check_all:checkbox').change(function() {
		var group = ':checkbox[name=check[]]';
		$(group).attr('checked', $(this).attr('checked'));
	});
	
	jQuery('#messages-inbox-list li input[name=check[]], #messages-inbox-list li a:not(:first)').click(function(e) {
		e.stopPropagation();
	});
	
	jQuery('#messages-inbox-list li').click(function() {
		var link = jQuery('h3', this).children('a:first').attr('href');
		if(link) document.location.href = link;
	});
	
	jQuery('#messages #delete-messages').click(function() {
		// if(confirm('Sigurno želiš brisati?')) {
			var group = '#messages #messages-inbox-list :checkbox:checked';
			$(group).closest('li').blindUp('normal', function() {$(group).attr('checked', false);});
			
			var arr = [];
			$(group).each(function(index, el) {
				arr[index] = 'check[]='+ el.value;
			});
			
			if(arr.length > 0) {
				var current_href = $(this).attr('href');
				current_href += '?'+ arr.join('&')
				$.get(current_href);
				// jQuery.fn.notice(current_href);
			}
		// }
		return false;
	});
	
	// jQuery('ul.profiles-list.oneliner li:odd').attr('style', 'background-color: #F5F5F5;');
	jQuery('ul.profiles-list.oneliner li .status-info select').change(function() {
		var ms = jQuery(this).val();
		var u = jQuery(this).prev().attr('href').split('/')[4];
		$.post('/clanovi/'+ u +'/tip', {ut:ms});
		jQuery(this).closest('li').highlight(2000);
	});
	
	//$('div.edit-links').hover(function() {
	//	$(this).animate({opacity: 'hide', height: 'hide'}, 'slow');		
	//}, function() {
	//	$(this).animate({opacity: 'show', height: 'show'}, 'slow');		
	//});
	
	
	if(jQuery('#catalog-nav')) {
		var categories = jQuery('#catalog-nav a.first-level');
		categories.each(function(i, link) {
			var slideParent = jQuery(link).closest('li');
			var currentSlide = jQuery(slideParent).find('ul');
			var currentItems = jQuery(slideParent).find('li.current');
			if(currentItems.length>0) slideParent.addClass('current');
			if(jQuery(slideParent).hasClass('current')) currentSlide.show();
			jQuery(link).click(function() {
				slideParent.toggleClass('current');
				currentSlide.slideToggle('slow');
				return false;
			});
		});
	}
	
	//***** Alphabeth smooth scrolling handling
  if(jQuery('#alphabeth')) {
    var links = jQuery('#alphabeth a');
    jQuery(links).each(function(link_i, link) {
			if(jQuery(link).attr('href').match(/#/)) {
				jQuery(link).click(function() {
					jQuery.scrollTo(jQuery('.item-text a[name='+ jQuery(link).attr('href').split('#')[1] +']'), 800);
					return false;
				});
			}
    });
  }
  
  //***** New window open handling
  var links = jQuery('a.new-win');
  if(jQuery(links).length>0) {
    jQuery(links).each(function(link_i, link) {
      jQuery(link).click(function() {
        window.open(this, '');
        return false;
      });
    });
  }
  
  if(jQuery('#filtering')) {
    jQuery.fn.filter();
  }
  
  if(jQuery('#item-info')) {
    jQuery('#info-link').click(function() {jQuery('#item-info').slideToggle(); return false;});
  }
	
  if(jQuery('#hide-ebuttons')) {
    jQuery('#hide-ebuttons').click(function() {
			if( jQuery(this).attr('href').match(/sakrij-gumbe-uredjivanja/) ) {
				jQuery('.edit-links').fadeOut();
				jQuery(this).attr('href', '/prikazi-gumbe-uredjivanja');
				jQuery(this).html('<span id="show-edit-buttons">Prikaži gumbe uređivanja</span>');
				jQuery.get('/sakrij-gumbe-uredjivanja');
			} else {
				jQuery(this).attr('href', '/sakrij-gumbe-uredjivanja');
				jQuery(this).html('<span id="hide-edit-buttons">Sakrij gumbe uređivanja</span>');
				jQuery('.edit-links').fadeIn();
				jQuery.get('/prikazi-gumbe-uredjivanja');
			}
			return false;
		});
  }
	
	if(jQuery('#comments')) {
		jQuery('#comments .review-useful a').click(function() {
			var current_href = jQuery(this).attr('href');
			var aniel = jQuery(this).closest('.review-useful');
			jQuery(aniel).html('<span>Vaš glas je zaprimljen.</span>');
			jQuery.get(current_href);
			return false;
		});
	}
		
  if(jQuery('#like')) {
    jQuery('#like').click(function() {
			var current_href = jQuery(this).attr('href');
			if( jQuery(this).attr('href').match(/ne-svidja-mi-se/) ) {
				jQuery(this).attr('href', current_href.replace('ne-svidja-mi-se', 'svidja-mi-se'));
				jQuery(this).html('Sviđa mi se');
			} else {
				jQuery(this).attr('href', current_href.replace('svidja-mi-se', 'ne-svidja-mi-se'));
				jQuery(this).html('Ne sviđa mi se više');
			}
			jQuery.fn.notice(current_href);
			return false;
		});
  }
	
	jQuery('#link-favorite-profile').click(function() {
		var current_href = jQuery(this).attr('href');
		if( jQuery(this).attr('href').match(/ukloni$/) ) {
			jQuery(this).attr('href', current_href.replace(/ukloni$/, 'prati'));
			jQuery(this).html('<span id="favorite-profile">Dodaj u omiljene profile</span>');
		} else {
			jQuery(this).attr('href', current_href.replace(/prati$/, 'ukloni'));
			jQuery(this).html('<span id="unfavorite-profile">Ukloni iz omiljenih profila</span>');
		}
		jQuery.fn.notice(current_href);
		return false;
	});
	
	jQuery('#follow-activities').click(function() {
		var current_href = jQuery(this).attr('href');
		if( jQuery(this).attr('href').match(/prestani-pratiti$/) ) {
			if(confirm('Sigurno želiš prestati pratiti?')) {
				jQuery(this).attr('href', current_href.replace(/prestani-pratiti$/, 'prati-aktivnosti'));
				jQuery(this).html('<span id="follow-me">Prati aktivnosti</span>');
				jQuery.fn.notice(current_href);
			}
		} else {
			jQuery(this).attr('href', current_href.replace(/prati-aktivnosti$/, 'prestani-pratiti'));
			jQuery(this).html('<span id="unfollow-me">Prestani pratiti</span>');
			jQuery.fn.notice(current_href);
		}
		return false;
	});
	
	jQuery('#become-center-member').click(function() {
		var current_href = jQuery(this).attr('href');
		if( jQuery(this).attr('href').match(/(prekini-clanstvo|prekini-cekanje)$/) ) {
			if(confirm('Sigurno želiš prekinuti čekanje članstva?')) {
				jQuery(this).attr('href', current_href.replace(/(prekini-clanstvo|prekini-cekanje)$/, 'postani-clan'));
				jQuery(this).html('<span id="become-member">Postani član centra</span>');
				jQuery.fn.notice(current_href);
			}
		} else {
			jQuery(this).attr('href', current_href.replace(/postani-clan$/, 'prekini-cekanje'));
			jQuery(this).html('<span id="unpatiented-member">Prekini čekanje članstva</span>');
			jQuery('#follow-activities').closest('li').hide();
			jQuery.fn.notice(current_href);
		}
		return false;
	});
	
	if(jQuery('#article_event_location')) {
		if(jQuery('#article_event_start_timeb').is(':checked')) {
			jQuery('#article_event_start_time_4i').removeAttr('disabled');
			jQuery('#article_event_start_time_5i').removeAttr('disabled');
		}
		
		jQuery('#article_event_start_timeb').change(function() {
			if(jQuery('#article_event_start_timeb').is(':checked')) {
				jQuery('#article_event_start_time_4i').removeAttr('disabled');
				jQuery('#article_event_start_time_5i').removeAttr('disabled');
			} else {
				jQuery('#article_event_start_time_4i').attr('disabled', 'disabled');
				jQuery('#article_event_start_time_5i').attr('disabled', 'disabled');
			}
		});
		
		if(jQuery('#article_event_end_dateb').is(':checked')) {
			jQuery('#article_event_end_date_1i').removeAttr('disabled');
			jQuery('#article_event_end_date_2i').removeAttr('disabled');
			jQuery('#article_event_end_date_3i').removeAttr('disabled');
			jQuery('#article_event_end_timeb').removeAttr('disabled');
		}
		
		jQuery('#article_event_end_dateb').change(function() {
			if(jQuery('#article_event_end_dateb').is(':checked')) {
				jQuery('#article_event_end_date_1i').removeAttr('disabled');
				jQuery('#article_event_end_date_2i').removeAttr('disabled');
				jQuery('#article_event_end_date_3i').removeAttr('disabled');
				jQuery('#article_event_end_timeb').removeAttr('disabled');
			} else {
				jQuery('#article_event_end_date_1i').attr('disabled', 'disabled');
				jQuery('#article_event_end_date_2i').attr('disabled', 'disabled');
				jQuery('#article_event_end_date_3i').attr('disabled', 'disabled');
				jQuery('#article_event_end_timeb').attr('disabled', 'disabled');
				jQuery('#article_event_end_timeb').removeAttr('checked');
			}
		});
		
		if(jQuery('#article_event_end_timeb').is(':checked')) {
			jQuery('#article_event_end_time_4i').removeAttr('disabled');
			jQuery('#article_event_end_time_5i').removeAttr('disabled');
		}
		
		jQuery('#article_event_end_timeb').change(function() {
			if(jQuery('#article_event_end_timeb').is(':checked')) {
				jQuery('#article_event_end_time_4i').removeAttr('disabled');
				jQuery('#article_event_end_time_5i').removeAttr('disabled');
			} else {
				jQuery('#article_event_end_time_4i').attr('disabled', 'disabled');
				jQuery('#article_event_end_time_5i').attr('disabled', 'disabled');
			}
		});
  }
	
	var homepage_premiums = jQuery('#homepage-premiums div.premium');
	if(homepage_premiums.length) {
		var total = homepage_premiums.length;
		var current = 0;
		var next = 1;
		var prev = total-1;
		
		jQuery(homepage_premiums).each(function(i, premium) {
			if(!jQuery(premium).hasClass('hide')) {
				current = i;
				next = ( (i+1) > (total-1) ) ? 0 : i+1;
				prev = ( (i-1) < 0 ) ? total-1 : i-1;
			}
		});
		
		var slide_show = setInterval(function() {
			jQuery(jQuery(homepage_premiums)[current]).fadeOut();
			jQuery(jQuery(homepage_premiums)[next]).fadeIn();
			current = next;
			next = ( (current+1) > (total-1) ) ? 0 : current+1;
			prev = ( (current-1) < 0 ) ? total-1 : current-1;
		}, 6000);
		
		jQuery('#premium-left').click(function() {
			clearInterval(slide_show);
			jQuery(jQuery(homepage_premiums)[current]).fadeOut();
			jQuery(jQuery(homepage_premiums)[prev]).fadeIn();
			next = current;
			current = prev;
			prev = ( (current-1) < 0 ) ? total-1 : current-1;
			return false;
		});
		
		
		jQuery('#premium-right').click(function() {
			clearInterval(slide_show);
			jQuery(jQuery(homepage_premiums)[current]).fadeOut();
			jQuery(jQuery(homepage_premiums)[next]).fadeIn();
			prev = current;
			current = next;
			next = ( (current+1) > (total-1) ) ? 0 : current+1;
			return false;
		});
	}
	
	var article_big_images = jQuery('#article-text img[width=364]');
	if(article_big_images.length) {
		jQuery(article_big_images).each(function(index, img) {
			jQuery(img).wrap('<div style="text-align: center;"></div>');
		});
	}
  
});

// Otvara sliku u popup-u velicine slike
function popup(path, width, height) {
	var win = window.open('', 'popup_win', 'width='+width+',height='+height+',top='+(screen.height/2-(height/2))+',left='+(screen.width/2-(width/2)));
	win.document.write('<html>\n<head>\n<title>Preglednik</title>\n</head>\n');
	win.document.write('<body marginwidth=0 marginheight=0 topmargin=0 leftmargin=0 onblur="window.close()">\n');

	if( path.substring( (path.length-3),path.length )=='swf' ) {
		win.document.write('<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0" WIDTH='+width+' HEIGHT='+height+'><PARAM NAME=movie VALUE="'+path+'"> <PARAM NAME=quality VALUE=high> <EMBED src="'+path+'" quality=high WIDTH='+width+' HEIGHT='+height+' TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=Shockwav eFlash"></EMBED> </OBJECT>');
	} else {
		win.document.write('<a href="javascript:void(0);" onclick="window.close()" title="Kliknite za zatvaranje prozora"><img src="'+path+'" width="'+width+'" height="'+height+'" border="0" /></a>');
	}

	win.document.write('</body>\n');
	win.document.write('</html>\n');
	win.document.close();
}