var baseUrl = 'http://gniezno.com.pl/';
function linkify(inputText) {
    var replaceText, replacePattern1, replacePattern2, replacePattern3;

    //URLs starting with http://, https://, or ftp://
    replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
    replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');

    //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
    replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
    replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');

    //Change email addresses to mailto:: links.
    replacePattern3 = /(\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,6})/gim;
    replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');

    return replacedText
}

$(document).ready(function(){
	$("#komentarze").find('.komentarz_tresc').each(function(){
		var text = $(this).html();
		//$(this).html(linkify(text)); 
	});
});

function strpos(str,szukaj){
	str+='';szukaj+=''; //auto-konwersja do stringa
	var w=str.indexOf(szukaj);
	if(w==-1) return false;
	return w;
}

function openImg(id,obj){
	$('#linkOfAll_'+(id-1)).click();
	//alert($('#linkOfAll_'+id).attr('href'));
 	//	hs.expand(document.getElementById('#linkOfAll_'+id), config1 )
}
(function($){
    $.fn.extend({
        pastecatch: function() {
 			return this.each(function() {
					var el = $(this);
	                el.bind('paste', function(e) {
				        var el = $(this);
				        setTimeout(function() {
				            $(el).val(strip_tags($(el).val()));
				        }, 100);
					});           
 			});
        }
    });
})(jQuery);
function findTextlinkToPhoto(){
	var ile = $('body').find('.zdjecie').length;
	
		//alert($('#komentarze').find('p.komentarz_tresc').length);
		$('#komentarze').find('div.komentarz').each(function(){
			var cHtml = 'xxd'+$(this).html()+' ';
			for (i=0;i<=ile;i++){
				 
				var lista = Array(
				"zdjęcie index[^0-9]",
				"zdjęciu index[^0-9]",
				
			
				">index zdjęcie",
				"zdjęcie nr \</strong\> index[^0-9]",
				"zdjęcie nr index[^0-9]",
				"zdjęcie nr\. index[^0-9]",				
				"zdjęcie nr\.index[^0-9]",				
				"fot\. index[^0-9]",				
				"fot\.index[^0-9]",
				"fot index[^0-9]",				
				"fot nr index[^0-9]",
				"fot\. nr index[^0-9]",
				"fot\. nr\. index[^0-9]",
				
				"fot \</strong\> index[^0-9]",
				"zdjęcie nr. \</strong\> index[^0-9]",
				"zdjęcie nr. \</strong\> index[^0-9]",
				"zdjęcie \</strong\> nr. index[^0-9]",
				"fot\. \</strong\> index[^0-9]",
				"fot\. nr \</strong\> index[^0-9]",
				"fot\. nr\. \</strong\> index[^0-9]",
				 
				"zdjęciu \</strong\> index[^0-9]",
				"index \</strong\> zdjęciu",
				"index zdjęcie"
				);
				for (iter in lista)
				{
					//alert(lista[iter]);
					var reg = lista[iter].replace('index',i);
					var match = cHtml.match(reg);
					
					if(match!=null){
						//var link = $('#photoOfAll_'+i).parent().attr('rel');
						cHtml = str_replace(match,'<a href="javascript:openImg('+i+',this);" class="komentarz_zdjecie" staus="0">'+str_replace('>','',match)+'</a>',cHtml);
						$(this).html(cHtml);
					}
				} 
				$(this).html(str_replace('xxd','',$(this).html()));
			}
		});
}

function xxsetVoteComment(id,vote,art){
	var cResult = cookieGet('komentarz_xxx_'+id+'_'+art);
	if(cResult == 'undefined'){
		cookieSet('komentarz_xxx_'+id+'_'+art);
		var url = baseUrl+"komentarze/glosuj/"+id+"/"+vote+"/"+art+".html";
		$.get(url, function(data) {
			if(data=='0xA'){
				alert("Już glosowales");
			}else{
				$('#votes_'+id).html(data);
			}
			  
			});
		var cont = parseInt($('#ocen').html());
		cont++;
		$('#ocen').html(cont);	
	}else{
		$('#votes_'+id).html("Już głosowałeś");
	}

}

function clickstat(tag){
	var url = baseUrl+"home/click/"+tag+"?x="+Math.random();
	$.get(url, function(data) {	
		return true;
	});
}

formatUnits = function (baseNumber, unitDivisors, unitLabels, singleFractional) {
	var i, unit, unitDivisor, unitLabel;

	if (baseNumber === 0) {
		return "0 " + unitLabels[unitLabels.length - 1];
	}
	
	if (singleFractional) {
		unit = baseNumber;
		unitLabel = unitLabels.length >= unitDivisors.length ? unitLabels[unitDivisors.length - 1] : "";
		for (i = 0; i < unitDivisors.length; i++) {
			if (baseNumber >= unitDivisors[i]) {
				unit = (baseNumber / unitDivisors[i]).toFixed(2);
				unitLabel = unitLabels.length >= i ? " " + unitLabels[i] : "";
				break;
			}
		}
		
		return unit + unitLabel;
	} else {
		var formattedStrings = [];
		var remainder = baseNumber;
		
		for (i = 0; i < unitDivisors.length; i++) {
			unitDivisor = unitDivisors[i];
			unitLabel = unitLabels.length > i ? " " + unitLabels[i] : "";
			
			unit = remainder / unitDivisor;
			if (i < unitDivisors.length -1) {
				unit = Math.floor(unit);
			} else {
				unit = unit.toFixed(2);
			}
			if (unit > 0) {
				remainder = remainder % unitDivisor;
				
				formattedStrings.push(unit + unitLabel);
			}
		}
		
		return formattedStrings.join(" ");
	}
};

formatBPS = function (baseNumber) {
	var bpsUnits = [1073741824, 1048576, 1024, 1], bpsUnitLabels = ["Gbps", "Mbps", "Kbps", "bps"];
	return formatUnits(baseNumber, bpsUnits, bpsUnitLabels, true);

};


formatTime = function (baseNumber) {
	var timeUnits = [86400, 3600, 60, 1], timeUnitLabels = ["d", "h", "m", "s"];
	return formatUnits(baseNumber, timeUnits, timeUnitLabels, false);

};
formatBytes = function (baseNumber) {
	var sizeUnits = [1073741824, 1048576, 1024, 1], sizeUnitLabels = ["GB", "MB", "KB", "bytes"];
	return formatUnits(baseNumber, sizeUnits, sizeUnitLabels, true);

};
formatPercent = function (baseNumber) {
	return baseNumber.toFixed(2) + " %";
};
	function simpleGet(url,response) {
		var y = $('#'+response).height(); 
		$('#'+response).html("<center><img src='http://gniezno.com.pl/admin/grafika/ajax.gif'></center>");
		$.get(url, function(data) {
			  $('#'+response).html(data);
		});		
		
	}	

function getSeeAlsoMore(art){
	clickstat('see_also'); 
	$("alsoClicker").attr('disabled','disabled');
	var page = parseInt($("#see_also_page").val());
	var url = baseUrl+"api/seealso/"+art+"/"+page;
	$("#seeLoad").show();
	$.get(url, function(data) {
		
		 if(data=="empty"){
			 $("#seeBelka").hide();
			 $("#seealsoMore").append("<p style='text-align:center;font-weight:bold;'>Nie znalezionow więcej</p>");
		 }else{			 
			//var fHeight =  $("#seealsoMore").heigth();
			 $("#seealsoMore").append(data);
			 
			 
			 $("#see_also_page").val((page+1));
		 }
		 
	});	
	$("#seeLoad").hide();
	$("alsoClicker").removeAttr('disabled');

}

function getSeeAlsoAdverts(art,act){
	$("alsoClicker").attr('disabled','disabled');
	var page = parseInt($("#see_also_page").val());
	var url = baseUrl+"ogloszenia/zobacz/"+art+"/"+act+"/"+page;
	$("#seeLoad").show();
	$.get(url, function(data) {
		
		 if(data=="empty"){
			 $("#seeBelka").hide();
			 $("#seealsoMore").append("<p style='text-align:center;font-weight:bold;'>Nie znalezionow więcej</p>");
		 }else{			 
			 //$("#seealsoMore").append(data);
			 $("#seealsoMore").append(data).show("slide", {direction: "down"},"1000");
			 
			 $("#see_also_page").val((page+1));
		 }
		 
	});	
	$("#seeLoad").hide();
	$("alsoClicker").removeAttr('disabled');

}

function SendRequest(forma,response) {
	$('#'+response).html('proszę czekać..'); 
	$('form').submit(function(){
		 $('input[type=submit]', this).attr('disabled', 'disabled');
		 $('input[type=button]', this).attr('disabled', 'disabled');
	});	
	$.ajax({
		   type: "POST",
		   url: $('#'+forma).attr("action"),
		   data: $('#'+forma).serialize(),
		   success: function(msg){
				$('#'+response).html(msg); 
		   }
	   /*
	   		,
		   error:function (xhr, ajaxOptions, thrownError){
			   $('#'+response).html("Wystąpił błąd : "+xhr.status);
               // SendRequest
           }
    */ 
		 });
	$('form').submit(function(){
		 $('input[type=submit]', this).removeAttr('disabled');
		 $('input[type=button]', this).removeAttr('disabled');
	});		 
	 return true;
}; 


function setVoteComment(id,vote,art){
	var ec = new evercookie();
	$('#votes_'+id).html('Trwa oddanie głosu..');
	ec.get('commentC'+id+'art'+art, function(best, all) {
		//alert(all+ ' -> '+ best);
		if(best != 'saved'){
			ec.set('commentC'+id+'art'+art,'saved');
				var opt = {
					    type:        'GET',
					    url:        baseUrl+"komentarze/glosuj/"+id+"/"+vote+"/"+art+".html",
					    timeout:     20*1000,
					    error:       function(xhr) { 
							console.log("error", arguments); 
						},
					    success:     function(data) { 
							if(data=='0xA'){
								$('#votes_'+id).html('Już głosowałeś');
							}else{
								
								$('#votes_'+id).html(data);
							} 
						},error: function(data) { 
							alert('sa') ;
						}
					};
			
					jQuery.ajax(opt);
			
				var cont = parseInt($('#ocen').html());
				cont++;
				$('#ocen').html(cont);		
		}else{
			$('#votes_'+id).html('Już głosowałeś');
		}
					
	});
	

}
function setVotePhoto(id,vote,art){
	var ec = new evercookie();
	$('#votes_'+id).html('Trwa oddanie głosu..');
	ec.get('photoV'+id+'art'+art, function(best, all) {
		//alert(all+ ' -> '+ best);
		if(best != 'saved'){
			ec.set('photoV'+id+'art'+art,'saved');
			var opt = {
				    type:        'GET',
				    url:        baseUrl+"obraz/glosuj/"+id+"/"+vote+"/"+art+".html",
				    timeout:     20*1000,
				    error:       function(xhr) { 
						console.log("error", arguments); 
					},
				    success:     function(data) { 
						if(data=='0xA'){
							$('#votes_'+id).html("Już glosowales");
						}else{
							
							$('#votes_'+id).html(data);
						} 
					}
				};
		
				jQuery.ajax(opt); 
		
				var cont = parseInt($('#ocen').html());
				cont++;
				$('#ocen').html(cont);		
		}else{
			$('#votes_'+id).html('Już głosowałeś');
		}
					
	});
	


}

function simpleGet(url,response) {
	$.get(url, function(data) {
		  $('#'+response).html(data);
	});
}
function clearInput(thefield){
	if (thefield.defaultValue==thefield.value)
	thefield.value = ""
} 

function oneFileUpload(file,urlLink,response,animation)
{
	$("#"+animation).ajaxStart(function(){
		$(this).show();
	}).ajaxComplete(function(){
		$(this).hide();
	});
	$.ajaxFileUpload
	(
		{
			url:urlLink, 
			secureuri:false,
			fileElementId:file,
			dataType: 'text',
			success: function (data, status)
			{
				$("#"+response).html(data);
			},
			error: function (data, status, e)
			{
				alert(e);
			}
		}
	)
	
	return false;

}
function setVoteChmurka(id,vote){
	var url = baseUrl+"chmurki/glosuj/"+id+"/"+vote+".html";
	$.get(url, function(data) {
		$('#votes_'+id).html(data);		  
	});
	//alert('#votes_'+id);
}

function visit(art,typ){
	var gdzie = 'a';
	if(typ==0){
		gdzie = 'a';
		$("#article_visit_c_resp").html('');
		$("#article_visit_b_resp").html('');
	}
	if(typ==1){
		gdzie = 'b';
		$("#article_visit_c_resp").html('');
		$("#article_visit_a_resp").html('');
	}
	if(typ==2){
		gdzie = 'c';
		$("#article_visit_b_resp").html('');
		$("#article_visit_a_resp").html('');
	}
	var url = baseUrl+"zapowiedzi/visit/"+art+"/"+typ;
	$.get(url, function(data) {	
		
			if(data=='byl'){
				$("#article_visit_"+gdzie+"_resp").html("już głosowałeś");	
			}else{
				$("#article_visit_"+gdzie).html(data);		
				$("#article_visit_"+gdzie+"_resp").html("głos oddany");	
			}
		});
}
function removeSpaces(nsText){
	
	
	var nospaces = false;
	var notabs = true;

	
	nsText = nsText.replace(/(\n\r|\n|\r)/gm,"<1br />");
	
	if(nospaces == 1 || nospaces ==  true){
	nsText = nsText.replace(/\t/g,"");
	}else{
	nsText = nsText.replace(/\t/g," ");
	}
	
	re1 = /\s+/g;
	nsText = nsText.replace(re1," ");
	
	re2 = /\<1br \/>/gi;
	nsText = nsText.replace(re2, "\n");
	return nsText; 
}
function ismaxlength(obj,result,max){
	//$(obj).val(removeSpaces($(obj).val()));
	if($(obj).val().length > max){
		$(obj).val($(obj).val().substr(0, max));
	}
	$("#"+result).html((max - $(obj).val().length));
}


	function stopWheel(e){
	    if(!e){ e = window.event; } /* IE7, IE8, Chrome, Safari */
	    if(e.preventDefault) { e.preventDefault(); } /* Chrome, Safari, Firefox */
	    e.returnValue = false; /* IE7, IE8 */
	}	
	// Wylaczenie srolla
	function disableWheel(){
		document.onmousewheel = function(){ stopWheel(); } /* IE7, IE8 */
		if(document.addEventListener){ /* Chrome, Safari, Firefox */
		    document.addEventListener('DOMMouseScroll', stopWheel, false);
		}
	}
	// Wlaczenie scrolla
	function enableWheel(){
					document.onmousewheel = null;  /* IE7, IE8 */
					if(document.addEventListener){ /* Chrome, Safari, Firefox */
					    document.removeEventListener('DOMMouseScroll', stopWheel, false);
					}
	}
	function goToComments(){
		disableWheel();
		$.scrollTo($('p.komentarze'),1000,{onAfter:function(){$.scrollTo($('p.komentarze'),500,{onAfter:function(){
			$.scrollTo($('p.komentarze'),300,{onAfter:function(){
					enableWheel();
				}});
			}});
		}});
	}


$(document).ready(function() {
	
	
	var fn = function (e)
	{

	    if (!e)
	        var e = window.event;

	    var keycode = e.keyCode;
	    if (e.which)
	        keycode = e.which;

	    var src = e.srcElement;
	    if (e.target)
	        src = e.target;    

	    // 116 = F5
	    if (116 == keycode)
	    {
	        // Firefox and other non IE browsers
	        if (e.preventDefault)
	        {
	            e.preventDefault();
	            e.stopPropagation();
	        }
	        // Internet Explorer
	        else if (e.keyCode)
	        {
	            e.keyCode = 0;
	            e.returnValue = false;
	            e.cancelBubble = true;
	        }

	        return false;
	    }
	}

	// Assign function to onkeydown event
	document.onkeydown = fn;
	
	//$("highslide-container").
});


