var Service = {

	login: function(_dest_url, _error_url) {
		if (_dest_url)
		{
			$('#login-burl').attr('value', _dest_url);
		}
		else
		{
			$('#login-burl').attr('value', window.location.href.replace(/#.*$/gi, ''));
		}

		if (_error_url)
		{
			$('#login-eurl').attr('value', _error_url);
		}
		else
		{
			$('#login-eurl').attr('value', window.location.href.replace(/#.*$/gi, ''));
		}
		$('#jqmLogin').jqm();
		$('#jqmLogin').jqmShow();
	},

	isLogin: function() {
		if ($.cookie('s_us_nick') && $.cookie('s_us_id'))
			return true;
   	else 
			return false;
	},


	loginBox: function() {
		if (Service.isLogin())
		{
			$(".linksLogin ").hide();
			$("#user-login").text(unescape($.cookie('s_us_nick')).replace(/\+/g,' '));
			$(".linksLogout").show();
			if ($.cookie('s_us_name'))
			{
				$(".myBlog").attr("href", "http://" + $.cookie('s_us_name') + "/");
			}
			else
			{
				$("#user-blog").hide();
			}
		}
	},

	loginMyZone: function(_dest_url) {
		if (Service.isLogin()) {
	  		return true;
	  	}
	  	else{
			Service.login(_dest_url);
			return false;
		}
	},
	
	togglePosts: function(_obj){
		css_class = $(_obj).attr('class');
		
		if (css_class == 'latest_order'){
			$(".latest_order").css("font-weight", "bold");
			$(".popular_order").css("font-weight", "normal");
			$(".popular_list").hide();
			$(".latest_list").show();
		}
		
		if (css_class == 'popular_order'){
			$('.latest_order').css('font-weight', 'normal');
			$('.popular_order').css('font-weight', 'bold');
			$(".popular_list").show();
			$(".latest_list").hide();
		}
	},
	

	AttachAdminTool: function(poid){
		if (Service.isLogin && $.cookie('s_us_ir'))
		{
			$("#post-"+poid).css('position', 'relative');
			$('<a href="#" class="button_blue">pozycjonuj</a>').css({position: 'absolute', right: 0, 'z-index': 1000}).click(function(){
				$('#jqmAdminCss').remove();
				$('#jqmAdmin').remove();
				var _manscr = $('#service-navi-manage').attr('href');
				if (_manscr)
					$.getScript(_manscr+"admin-position/"+poid, function(){});
			}).prependTo("#post-"+poid);
		}
	},

	AnchorAction: function (_config)
	{
		url = window.location.href;
		reg = new RegExp(/^.*#(.*)$/g);
		reg_dest = reg.exec(url);
		if (reg_dest != null)
		{
			args = reg_dest[1].split("_");
			action = args[0].replace(/[^a-z0-9]/gi, '');
			param = (typeof args[1] == 'undefined') ? null : args[1].replace(/[^a-z0-9\-:,\[\]]/gi, '');

			if (action)
			{
				exec = "if (_config." + action + ") _config." + action + "(param)";
				eval(exec);
			}
		}
	},

	addCommentBlackList: -1,

	addCommentOld: function() {
		if (Service.isLogin()) {

			if (Service.addCommentBlackList>=0) {
				$("#post-comment-wait").hide();
				$("#post-comment-on-bl").hide();
				$("#comment-failed").hide();
				$("#comment-saved").hide();

				if (Service.addCommentBlackList){
					$("#post-comment-on-bl").show();
				}
				else {
					var oFCKeditor = new FCKeditor( 'message' ) ;
					oFCKeditor.BasePath = "/fckeditor/" ;
					oFCKeditor.Config["CustomConfigurationsPath"] = "/fckeditor/myconfig.js";
					oFCKeditor.Height = '250'; 
					oFCKeditor.ReplaceTextarea() ;
					
					$("#post-add-comment").show('slow');
					$("#comment_form").show();
				}
			}
			else {
				$("#post-comment-wait").show();
				$.getJSON("/on-black-list/", {}, function(json){
					if (!json.error) {
						Service.addCommentBlackList = json.status;
						Service.addComment();
					}
					
				});
			}
			return false;
		}
		else {
			window.location = window.location.href.replace(/#.*$/gi, '') + '#';
			if (!$.cookie('s_us_waslogged'))
				$('#comment-register').show();
			Service.login();
			$('#login-burl').attr('value', window.location.href.replace(/#.*$/gi, '') + "#commentadd");
			return false;
		}
	},
	
	
	
	addComment: function() {
		
		if (Service.addCommentBlackList < 0) {
			$.ajax({
				type: "GET",
				dataType: "json",
				url: "/on-black-list/",
				async: false, // !!! WAZNE
				success: function(json){
					if (!json.error) {
						Service.addCommentBlackList = json.status;
					}
				}
			});		
			
		}
		
		
		if (Service.isLogin()) {
			//$('#commentauthorbody').empty();
			Service.commentBody();
		}
		else {
			
			// zabronione anonimowe
			if (Service.addCommentBlackList == 11) {
				window.location = window.location.href.replace(/#.*$/gi, '') + '#';
				if (!$.cookie('s_us_waslogged'))
					$('#comment-register').show();
				Service.login();
				$('#login-burl').attr('value', window.location.href.replace(/#.*$/gi, '') + "#commentadd");
				return false;				
			}
			else {
				
				FB.Event.subscribe('auth.login', function(response) {
					Service.fbUserConnectedStatus = 1;
					Service.commentBody();
				});
				
				FB.Event.subscribe('auth.logout', function(response) {
					Service.fbUserConnectedStatus = 0;
					Service.commentBody();
				});	
				
				FB.getLoginStatus(function(response){
					if (response.session) {
						Service.fbUserConnectedStatus = 1;
						Service.commentBody();
					}
					else {
						Service.fbUserConnectedStatus = 0;
						Service.commentBody();
					}
				});
			}
		}

	},
	
	fbUserConnectedStatus: 0,
	
	
	commentBody: function(){
		if (Service.isLogin()) {
			$('#commentauthorbody').hide();
			$('#captchabody').hide();
			$('#commentextauthorbody').hide();
		}
		else {
			if (Service.fbUserConnectedStatus) {
				$('#commentauthorbody').hide();
				$('#captchabody').hide();
				$('#commentextauthorbody').html('<fb:profile-pic uid="loggedinuser" facebook-logo="true" size="square" style="float:left;margin-right: 5px"></fb:profile-pic><strong><fb:name uid="loggedinuser" useyou="false"></fb:name></strong><br /><img onclick="FB.logout()" style="cursor: pointer;" src="https://s-static.ak.fbcdn.net/rsrc.php/z2Y31/hash/cxrz4k7j.gif"/><div class="cb" style="height:10px"></div>');
			}
			else {
				$('#commentauthorbody').show();
				$('#commentextauthorbody').html('<div style="position: absolute; right: 10px; width: 320px"><b>Komentujesz anonimowo.</b><br /><a href="javascript: void(0)" onclick="Service.login()">Zaloguj się</a> w serwisie lub przez <fb:login-button v="2"><fb:intl>Facebook</fb:intl></fb:login-button></div>');
				$('#captchabody').show();
			}
			FB.XFBML.parse();
		}

		var oFCKeditor = new FCKeditor( 'message' ) ;
		oFCKeditor.BasePath = "/fckeditor/" ;
		oFCKeditor.Config["CustomConfigurationsPath"] = "/fckeditor/myconfig.js";
		oFCKeditor.Height = '250'; 
		oFCKeditor.ReplaceTextarea() ;
		
		$("#post-add-comment").show('slow');
		$("#comment_form").show();
	},
	
	
	
	reportAbuse: function(_type, _oid) {
		$("#abuse-failed").hide();
		$("#abuse-saved").hide();
		$("#abuse_form").show();
		$('#abuse_type').attr('value', _type)
		$('#abuse_oid').attr('value', _oid)
		$('#jqmAbuse').jqm();
		$('#jqmAbuse').jqmShow();
	},
	
	showLink: function(url) {
		prompt('Potrzebujesz wskazać konkretny komentarz?\nSkopiuj poniższy link do schowka.', url);
	},
	
	
	sendMail: function(_user_oid, _admin_domain) {
		url = "http://" + _admin_domain + "/mail-new/" + _user_oid;
		if (Service.isLogin()) {
			window.location = url;
		}
		else {
			Service.login();
			$('#login-burl').attr('value', url);
			return false;
		}
	},
	
	addAuthorToFavorite: function(_user_oid) {
		if (Service.isLogin()) {
			burl = window.location.href.replace(/#.*$/gi, '');
			url = "/favorite-author-add/" + _user_oid + "?burl=" + burl;
			window.location = url;
		}
		else {
			window.location = window.location.href.replace(/#.*$/gi, '') + '#';
			Service.login();
			$('#login-burl').attr('value', window.location.href.replace(/#.*$/gi, '') + "#addtouserfav");
			return false;
		}
	},
	
	addPostToFavorite: function(_post_oid) {
		if (Service.isLogin()) {
			burl = window.location.href.replace(/#.*$/gi, '');
			url = "/favorite-post-add/" + _post_oid + "?burl=" + burl;
			window.location = url;
		}
		else {
			window.location = window.location.href.replace(/#.*$/gi, '') + '#';
			Service.login();
			$('#login-burl').attr('value', window.location.href.replace(/#.*$/gi, '') + "#addtopostfav");
			return false;
		}
	},
	
	watchPostMark: function(_post_oid, _cookie_domain) {
		if (Service.isLogin()){
			var fpost_list = $.cookie('w_fpost');
			if (fpost_list){
				var fpost_arr = fpost_list.split(',');
				index = fpost_arr.indexOf(_post_oid.toString());
				if (index >= 0){
					//delete fpost_arr[index];
					//$.cookie('w_fpost', fpost_arr.toString(), {domain: _cookie_domain});
					jQuery.post('/watch-mark-post/', {
						oid : _post_oid
						});
				}
			}
		}
	},
	
	watchUserMark: function(_user_oid, _cookie_domain) {
		if (Service.isLogin()){
			var fuser_list = $.cookie('w_fuser');
			if (fuser_list){
				var fuser_arr = fuser_list.split(',');
				var index = fuser_arr.indexOf(_user_oid.toString());
				if (index >= 0){
					//delete fuser_arr[index];
					//$.cookie('w_fuser', fuser_arr.toString(), {domain: _cookie_domain});
					jQuery.post('/watch-mark-user/', {
						oid : _user_oid
						});
				}
			}
		}
	},
	
	lockUserShow: function(_user_oid) {
		if (Service.isLogin()){
			if(window.location.href.indexOf($.cookie('s_us_name')) >=0 )	
			{
			 	var html = '<a href="#" onclick="Service.lockUserPopup(' + _user_oid + ');" title="dodaj do listy zablokowanych użytkowników">zablokuj</a>&nbsp;&raquo;&nbsp;&nbsp;&nbsp;&nbsp;';
			 	var lockuser_list = $.cookie('w_lockuser');
			 	if (lockuser_list) {
			 		var lockuser_arr = lockuser_list.split(',');
			 		var index = lockuser_arr.indexOf(_user_oid.toString());
			 		if (index < 0) {
			 			document.write(html)
			 		}
			 	}
			 	else {
			 		document.write(html)
			 	}
		 	}
		}
	},
	
	lockUserPopup: function(_user_oid) {
		$('#jqmLockUser').jqm();
		$('#jqmLockUser').jqmShow(); 
		Service.lockUserId = _user_oid;
	},
	
	lockUser: function(_cookie_domain) {
		if (Service.isLogin()) {
			var lockuser_list = $.cookie('w_lockuser');
			lockuser_list += ',' + Service.lockUserId;
			$.cookie('w_lockuser', lockuser_list, {domain: _cookie_domain, path: '/'});
			var burl = window.location.href.replace(/#.*$/gi, '');
			var url = "/lockusers-lock/" + Service.lockUserId + "?burl=" + burl;
			window.location = url;
		}
	}
}

if(!Array.indexOf){
    Array.prototype.indexOf = function(obj){
        for(var i=0; i<this.length; i++){
            if(this[i]==obj){
                return i;
            }
        }
        return -1;
    }
}

jQuery.validator.addMethod("login", function(value, element) {
	return this.optional(element) || /^[a-z0-9\-\._]+$/i.test(value);
}, ""); 



// WEBalbum embed
$.fn.WEBalbumEmbed = function() {
	this.each(function(){
		url = $(this).attr('href');

		if (url)
		{
			$(this).css('display', 'none');
			$.ajax({
				type: "GET",
				dataType: "jsonp",
				url: url + '?jsonp=1',
				success: jQuery.hitch(this, function(msg){
					if(typeof msg.error != 'undefined' && msg.error == 0){
						
						if (typeof msg.thumbnail != 'undefined' && msg.thumbnail && typeof msg.photos != 'undefined' && msg.photos.length) {
							photos_cnt = msg.photos.length;
							rel = 'WA-rel_' + Math.round(Math.random() * 10000);
							css_class = (photos_cnt > 1) ? 'wa_slideshow' : 'wa_single';
							if (photos_cnt > 0) {
								for (i = 1; i < msg.photos.length; i++) {
									html = '<a class="' + css_class + '" style="display:none" href="' + msg.photos[i].url + '" rel="' + rel + '">WEBalbum Photo</a>';
									$(this).after(html);
								}
							}
							html = '<div style="margin:auto" class="wa_embed_container"><a class="' + css_class + '" href="' + msg.photos[0].url + '" rel="' + rel + '"><img src="' + msg.thumbnail + '" alt="" /></a></div>';
							$(this).after(html);
							$("a.wa_slideshow").colorbox({slideshow:true, slideshowSpeed: 4000, current : "{current} / {total}"});
							$("a.wa_single").colorbox();
						}
					}
			   })
			});
		}
	})
};


