function redirect(url,timer) {
	if(timer==null)
		timer=5000;
	
	setTimeout(function(){
		document.location.href=url;
	},timer);
}


function redirectProcess(event,url,timer) {
	if ('bubbles' in event) {   // all browsers except IE before version 9
		if (event.bubbles) {
			event.stopPropagation ();
			redirect(url,0);
		}
	}
	else {  // Internet Explorer before version 9
			// always cancel bubbling
		event.cancelBubble = true;
		redirect(url,0);
	}
}

function addTooltip() {
	$("a.title, div.title, img.title").each(function(i){
		var title = $(this).attr("title");

		if(title.length>0) {
			$(this)
				.unbind("mouseover")
				.bind("mouseover",function(){
					Tip(title);
				})
				.unbind("mouseout")
				.bind("mouseout",function(){
					UnTip();
				});
		}
	});
	
	$("div.infoLine,div.infoLineMonth").each(function(i){
		var contentId = $(this).attr("id");
		var stat = false;
		
		if(contentId.length>0) {
			$(this)
				.unbind("mouseover")
				.bind("mouseover",function(e){
					e.stopPropagation();
					
					TagToTip("_" + contentId + "");
				})
				.unbind("mouseout")
				.bind("mouseout",function(e){
					UnTip();
				});
		}
	});
}

function verifyMe(){
  $("#galleryFormSubmit").attr('disabled','disabled');
  msg = "";
  if($("#gallery_name").val() == "") msg += "Nazwa galerii\n";
  if($("#gallery_description").val() == "") msg += "Opis galerii\n";
  if(msg!=""){
    alert("Poniższe pola są wymagane:\n"+msg);
    $("#galleryFormSubmit").attr('disabled','');
    return false
  }else{
    if ($('.uploadifyQueueItem').length == 0) {
      if($("#gallery_link").val() == ""){
        msg += "Link do galerii lub zdjęcia z dysku\n";
        alert("Poniższe pola są wymagane:\n"+msg);
        return false
      }
      $("#gallery_form").submit();
    } else {
      $("#file_upload").uploadifyUpload();
    }
  } 
}

function verifyEdit(){
  if ($('.uploadifyQueueItem').length == 0) {
    $("#galleryEditForm").submit();
  }else{
    $("#file_upload").uploadifyUpload();
  }
}

function validateComment(){
  
  msg = "";
  if($("#komentarz_frm").val() == "") msg += "Brak komentarza\n";
  if($("#autor_frm").val() == "") msg += "Brak autora\n";
  if($("#email_frm").val() == ""){
    msg += "Brak adresu e-mail\n";
  } else {
    if (validateEmail($("#email_frm").val()) === false){ 
      msg += "E-mail jest niepoprawny\n"
    }
  }
  if(msg!=""){
    alert("Prosimy poprawić następujące błędy:\n"+msg);
    return false
  }
  return true 
}

function validateGoodPractice(){
  msg = "";
  if($("#title").val() == "") msg += "Brak tytułu\n";
  if($("textarea#_lead").val() == "") msg += "Brak leada\n";
  if($("textarea#_body").val() == "") msg += "Brak body\n";
  if($("#autor").val() == "") msg += "Brak autora\n";
  if($("#company_select").val() == "-1") msg += "Brak wybranej firmy\n";
   
  if(msg!=""){
    alert("Prosimy poprawić następujące błędy:\n"+msg);
    return false
  }
  return true;
}



function validateEmail(email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   if(reg.test(email) == false) {
      return false;
   }
}


function presidentsImg() {
	$(".presidentsImg")
		.mouseover(function(){
			$(this).stop().fadeTo(300,0);
		})
		.mouseout(function(){
			$(this).stop().fadeTo(300,1);
		});
}

function goToTopPage() {
	$("#goToTopPage")
		.click(function(){
			$.scrollTo(0,800);
		});
	
	$(".movieItem, .prezentationItem, .galleryBox")
		.click(function(){
			$.scrollTo("#previewTitle", 800);
		});
}

function addCounter(field,counter) {
	$("#" + field + "").NobleCount("#_" + field + "", {
		on_negative: "go_red",
		on_positive: "go_green",
		block_negative: true,
		max_chars: counter
	});
}

function checkFormSubmit(id) {
	$("#"+id).val("1");
}

function checkFormSubmit(id) {

	$("#"+id).val("1");

}

function addTargetBlank() {
	$(".targetBlank").click(function(){
		this.target = "_blank";
	});
}

function addArticleDatePicker(){
	$('#publish_start, #publish_end').datepicker({
		dateFormat: 'yy-mm-dd',
		dayNames: ['Niedziela', 'Poniedziałek', 'Wtorek', 'Środa', 'Czwartek', 'Piątek', 'Sobota'],
		dayNamesMin: ['Nd', 'Pn', 'Wt', 'Śr', 'Cz', 'Pi', 'So'],
		monthNames: ['Styczeń','Luty','Marzec','Kwiecień','Maj','Czerwiec','Lipiec','Sierpień','Wrzesień','Październik','Listopad','Grudzień'],
		monthNamesShort: ['Sty','Lut','Mar','Kwi','Maj','Cze','Lip','Sie','Wrz','Paź','Lis','Gru'],
		firstDay: 1,
		nextText: 'Następny',
		prevText: 'Poprzedni',
		onChangeMonthYear: function() {}
	});
}

function addContentPart(lang){
	$(".addContentPart").unbind("click").bind("click",function(){
		var content="";
		
		content+="<div class=\"formLineAdmin articleContentDiv\">";
		content+="	<div class=\"formLineAdmin formPadding\">" + $("#typeText").html() + "</div>";
		content+="	<div class=\"formLineAdmin\">" + $("#typeContent").html() + "</div>";
		content+="	<div class=\"formLineAdmin formPadding\"></div>";
		content+="	<div class=\"formLineAdmin formLineNone\"><input type=\"hidden\" name=\"content[]\" value=\"\" /></div>";
		content+="	<div class=\"formLineAdmin formLineDisplay\"><input type=\"hidden\" name=\"idKey[]\" value=\"\" /></div>";
		content+="	<div class=\"formLineAdmin formLineNone formLineAdminRight\">";
		content+="		" + $("#navigation").html() + "";
		content+="	</div>";
		content+="</div>";
		
		$(this).parent().parent().before(content);
		
		addContentPart(lang);
		addFieldByChange(lang);
		generateId();
		addTooltip();
		return false;
	});
	
	$(".addContentPartUp").unbind("click").bind("click",function()
	{
	
		var ids=$(this).parent().parent().attr("id").replace('_','');
		var elements=$(".articleContentDiv");
		
		if(elements.length>1 && ids>0) 
		{
			var select=$("#_"+ids+" select[name^='type']").val();
			var idKey=$("#_"+ids+" input[name^='idKey']").val();
			var content="";
			
			if(select==1 || select==3 || select==4)	
				content=$("#_"+ids+" input[name^='content']").val();
			else if(select==2) {
				content=$("#_"+ids+" textarea").elrte('val');
				$("#_"+ids+" .ui-resizable").parent().html("<textarea name=\"content[]\" class=\"inputTextarea\"></textarea>");
			} else if(select==5) 
				content=$("#_"+ids+" select[name^='content']").val();
			
			
			var div = $("#_"+ids).html();
			var newId = parseInt(ids)-1;
			
			
			
			$("#_"+newId).before("<div class=\"formLineAdmin articleContentDiv\" id=\"new_" + newId + "\">" + div + "</div>");
			

			
			if(select==1 || select==3 || select==4) 
				$("#new_"+newId+" input[name^='content']").val(content);
			else if(select==2) {
				addWysiwyg("#new_"+newId+" textarea",0);
				$("#new_"+newId+" textarea").elrte('val', content);
			} else if(select==5) 
				$("#new_"+newId+" select[name^='type']").val(content);
			
			$("#new_"+newId+" select[name^='type'] option[value='" + select + "']").attr("selected","selected");
			$("#new_"+newId+" input[name^='idKey']").val(idKey);
			
			$("#_"+ids).remove();
		}
		
		addContentPart(0);
		addFieldByChange(0);
		generateId();
		addTooltip();
	
		return false;
	});
	
	$(".addContentPartDown").unbind("click").bind("click",function(){
		var ids=$(this).parent().parent().attr("id").replace('_','');
		var elements=$(".articleContentDiv");
		
		if(elements.length>1 && ids<(elements.length-1)) {
			var select=$("#_"+ids+" select[name^='type']").val();
			var idKey=$("#_"+ids+" input[name^='idKey']").val();
			var content="";
			
			if(select==1 || select==3 || select==4)  
				content=$("#_"+ids+" input[name^='content']").val();
			else if(select==2) {
				content=$("#_"+ids+" textarea").elrte('val');
				$("#_"+ids+" .ui-resizable").parent().html("<textarea name=\"content[]\" class=\"inputTextarea\"></textarea>");
			} else if(select==5) 
				content=$("#_"+ids+" select[name^='content']").val();
			
			var div = $("#_"+ids).html();
			var newId = parseInt(ids)+1;
			
			$("#_"+newId).after("<div class=\"formLineAdmin articleContentDiv\" id=\"new_" + newId + "\">" + div + "</div>");
			
			if(select==1 || select==3 || select==4) 
				$("#new_"+newId+" input[name^='content']").val(content);
			else if(select==2) {
				addWysiwyg("#new_"+newId+" textarea",lang);
				$("#new_"+newId+" textarea").elrte('val', content);
			} else if(select==5) 
				$("#new_"+newId+" select[name^='type']").val(content);
			
			$("#new_"+newId+" select[name^='type'] option[value='" + select + "']").attr("selected","selected");
			$("#new_"+newId+" input[name^='idKey']").val(idKey);
			
			$("#_"+ids).remove();
		}
		
		addContentPart(lang);
		addFieldByChange(lang);
		generateId();
		addTooltip();
		
		return false;
	});
	
	$(".addContentPartDelete").unbind("click").bind("click",function(){
		$("#"+$(this).parent().parent().attr("id")).remove();
		generateId();
		
		return false;
	});
	
	$("#contSave,#contSaveDraft,#contPublic").unbind("click").bind("click",function(){
		$("#navigation, #typeContent, #typeText, #contentPeople, #systemGallery").remove();
	});
}

function addFieldByChange(lang){
	$("select[name^='type'].inputSelect").unbind("change").bind("change",function(){
		var val = $(this).val();
		
		if(val<6) {
			$(this).parent().next().html("" + $("#contentText").html() + "");
		}
		
		if(val==1 || val==3 || val==4)
			$(this).parent().next().next().html("<input type=\"text\" name=\"content[]\" class=\"inputText\" />");
		else if(val==2)
			$(this).parent().next().next().html("<textarea name=\"content[]\" class=\"inputTextarea\"></textarea>");
		else if(val==5)
			$(this).parent().next().next().html($("#contentPeople").html());
		/*else if(val==6)
			$(this).parent().next().next().html($("#systemGallery").html());	*/
		else {
			$(this).parent().next().next().html("");
			$(this).parent().next().html("");
		}
		
		
		if(val<6) {
			$(this).parent().next().next().next().children().val("");
			var element = $(this).parent().next().next().children();
			
			if(element.attr("class")=="inputTextarea")
				addWysiwyg(element,lang);
		}
	});
}

function generateId(){
	$("div.articleContentDiv").each(function(i){
		$(this).attr("id","_"+i);
	});
}

function clearFieldMyName(name) {
	$(""+name+"").bind("click",function(){
		$(this).val("").unbind("click");
	});
}


function externalLinks() {
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		if (
			anchor.getAttribute("href") && ( 
			anchor.getAttribute("rel") == "external" || 
			anchor.getAttribute("rel") == "external nofollow" || 
			anchor.getAttribute("rel") == "nofollow external" )
			)
		anchor.target = "_blank";
	}
}

function addWysiwyg(layer,lang,style){
	var opts = {
		cssClass 	: 'el-rte',
		lang  	 	: lang,
		height   	: 200,
		resizable 	: false,
		toolbar  	: style,
		allowSource	: false
	}
	$(layer).elrte(opts);
}

function delThumbEvent(){
	$('input[name=delThumb]').unbind('click').bind('click',function(){
		$("#logoMin").html("");
		$("input[name='imgUpload']").val("");
		$("input[name='error']").val("");
		
		return false;
	});
}

// Funkcje Google Maps
var geocoder;
var map;
var bounds = null;
var objects = 0;


//Funckja inicjalizuje mape Google Maps
function initialize(layer) {
	try {
		geocoder = new google.maps.Geocoder();
		var myOptions = {
			zoom: 6,
			center: new google.maps.LatLng(52.124046,19.180298),
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		
		map = new google.maps.Map(document.getElementById(layer),myOptions);
		bounds = new google.maps.LatLngBounds();
	} catch(exception) {
		
	}
}


//Funckja odpowiada za dodanie punktu na mape Google Maps
function addOverlays(coordinatesX,coordinatesY,content){
	
	
	if(coordinatesX.length>0 && coordinatesY.length>0) {
		++objects; //zliczam ilosc dodanych obiektow
		
		var marker = new google.maps.Marker({
			map: map,
			position: new google.maps.LatLng(coordinatesX,coordinatesY)
		});
		
		var infowindow = new google.maps.InfoWindow({
			content: content
		});
		
		google.maps.event.addListener(marker, 'click', function() {
			infowindow.open(map,marker);
		});
		
		
		bounds.extend(new google.maps.LatLng(coordinatesX,coordinatesY));
		map.setCenter(bounds.getCenter());
		
		//gdy ilosc obiektow jest wieksza od 1, 
		//wielkosc i powiekszenie mapy dopasowane zostaje do dodanych markerow
		if(objects>1) map.fitBounds(bounds);
		else if(objects==1) map.setZoom(12);
	}
}

//nadanie pluginu na linki do okienka wyswietlajacego google maps
function showGoogleMaps() {
	$("a[class^='showGoogleMaps']").prettyPhoto({theme: "dark_rounded"});
}

//nadanie pluginu na linki do okienka wyswietlajacego google maps
function showImages() {
	$("a[class^='showPrettyPhoto'],a[rel^='prettyPhoto']").prettyPhoto({theme: "dark_rounded"});
}

//nadanie pluginu na linki do okienka wyswietlajacego google maps
function showReports() {
	$("a[class$='showReports']").prettyPhoto({theme: "dark_rounded"});
}

//wyszukiwanie wydarzen
function searchEvents(category){
	$("#searchES").bind('click',function(){
		var textES 	= $("#textES").val();
		var startES = $("#startES").val();
		var endES 	= $("#endES").val();
		var firmES 	= $("#firmES").val();
		var rangeES = $("#rangeES").val();
		var typeES 	= $("#typeES").val();
		
		var url="";
		
    textES = textES.replace(/,/gi, " ");
    
		if(category!=="") url="/"+category;
		
		url=url+"/events/search/"+typeES+","+rangeES+","+textES+","+startES+","+endES+","+firmES+"/";
		
		redirect(url,0);
	});
}

function searchGP(category){
	$("#searchGP").bind('click',function(){
		var textGP 	= $("#textGP").val();
		var firmGP = $("#firmGP").val();
		
		var url="";
		
		if(category!=="") url="/"+category;
		
    textGP = textGP.replace(/,/gi, " ");
    
		url=url+"/goodPractice/search/"+textGP+","+firmGP+"/";
		
		redirect(url,0);
	});
}

function searchNews(category){
	$("#searchNews").bind('click',function(){
		var textGP 	= $("#textNews").val();
		
		var url="";
		
		if(category!=="") url="/"+category;
		
    textGP = textGP.replace(/,/gi, " ");
    
    if (textGP !=="") textGP="search/"+textGP+"/";
    
		url=url+"/news/"+textGP;
		
		redirect(url,0);
	});
}

function searchAllContent(category){
	$("#searchNews").bind('click',function(){
		var textGP 	= $("#topSearchText").val();
		
		var url="";
		
		if(category!=="") url="/"+category;
		
		textGP = textGP.replace(/,/gi, " ");
		
		if (textGP !=="") 
			url=url+"/search/"+textGP+"/";
		
		redirect(url,0);
	});
}

//tworzy i nadaje na elementy kalendarz
function createCalender(lang) {
	if(lang===0) {
		$(".datapicker").datepicker({
			dateFormat: 'yy-mm-dd',
			dayNames: ['Niedziela', 'Poniedziałek', 'Wtorek', 'Środa', 'Czwartek', 'Piątek', 'Sobota'],
			dayNamesMin: ['Nd', 'Pn', 'Wt', 'Śr', 'Cz', 'Pi', 'So'],
			monthNames: ['Styczeń','Luty','Marzec','Kwiecień','Maj','Czerwiec','Lipiec','Sierpień','Wrzesień','Październik','Listopad','Grudzień'],
			monthNamesShort: ['Sty','Lut','Mar','Kwi','Maj','Cze','Lip','Sie','Wrz','Paź','Lis','Gru'],
			firstDay: 1,
			nextText: 'Następny',
			prevText: 'Poprzedni',
			onChangeMonthYear: function() {}
		});
	} else if(lang===1) {
		
		
		
		
		
	}
}

//nadawanie zdarzenia na wyszukiwarke zawartosci serwisu
function searchAllContent(){
	$("#topSearch").bind('click',function(){
		var phrase 	= $("#topSearchText").val();
		
		if(phrase.length>0)
			redirect("/searchContent/" + phrase + "/0/",0);
	});
}

//Ladowanie jakiegos flasha do odpowiedniej warstwy
function addFlash(div,source,name,width,height,url){
	$('#'+div).flash({
		wmode: "transparent",
		src: source+name,
		width: width,
		height: height,
		flashvars: { clickTag: url }
	});
}

function changeContactPerson(){
	$("input[name='isOpenParticipant'],input[name='isOpenVolunteer'],input[name='isOpenCoorganizers']").click(function(){
		
		var isOpenParticipant = $("input[name='isOpenParticipant']:checked").val();
		var isOpenVolunteer = $("input[name='isOpenVolunteer']:checked").val();
		var isOpenCoorganizers = $("input[name='isOpenCoorganizers']:checked").val();
		
		if(isOpenParticipant=="1" || isOpenVolunteer=="1" || isOpenCoorganizers=="1") 
			$("div.contactLayer,hr.contactLayer").removeClass("displayNone");
		else 
			$("div.contactLayer,hr.contactLayer").addClass("displayNone");
		
	});
}

function getArticlesByCategory(){
	$("div[id^='_art_category_']").bind('click',function(){
		var param = $(this).attr("id").replace('_art_category_','');
		
		$("div[id^='_art_content_'],div[id^='_art_spec_content_']").html("");
		$('#_art_loader_'+param).css({"display":"inline"});
		
		$.ajax({
			url: "/admin/articles/articles/",
			
			type: "POST",
			data: {
				param: param
			},
			
			success: function(html)
			{
				var obj='';
				if(obj = $.parseJSON(html)) {
					$('#_art_loader_'+param).css({"display":"none"});
					$('#_art_content_'+param).html(obj.content);
				}
			},
			error: function(xhr, ajaxOptions, thrownError) {}
		});
	});
}

function addPrint() {
	$('#print').click(function(){
		window.print();
		return false;
	});
}



function addLetter(lang) {
	$(".dictionaryAlphabet span[class^='isWords']")
		.unbind('click')
		.bind('click', function(){
			$(".dictionaryAlphabet span").removeClass("letterChecked");
			$(this).addClass("letterChecked");
			
			$(".dictionaryLetter").html($(this).html());
			$(".dictionaryWords, .dictionaryDescription").html("").addClass("dictionaryLoader");
			
			getWordDescription(lang,$(this).attr("id").replace("_",""));
		});
}

function addWord(lang) {
	$(".dictionaryWords div span")
		.unbind('click')
		.bind('click', function(){
			$(".dictionaryDescription div[id^='_desc']").removeClass("checkWord");
			$("#_desc"+$(this).attr("id")).addClass("checkWord");
			
			$(".dictionaryWords span[class='checkLetter']").removeClass("checkLetter");
			$(this).addClass("checkLetter");
		});
}

function getWordDescription(lang,letter) {
		$.ajax({
			url: "/ajax/ajax.php",
			
			type: "POST",
			data: {
				type:	'getWordDescription',
				letter:	letter,
				lang:	lang
			},
			
			success: function(html){
				var obj='';
				if(obj = $.parseJSON(html)) {
					$(".dictionaryWords").html(obj.content);
					$(".dictionaryDescription").html(obj.content2);
					
					$(".dictionaryLoader").removeClass("dictionaryLoader");
					addWord(lang);
				}
			},
			error: function(xhr, ajaxOptions, thrownError) {}
		});
}


