// The following block implements the string.parseJSON method
(function (s) {
  // This prototype has been released into the Public Domain, 2007-03-20
  // Original Authorship: Douglas Crockford
  // Originating Website: http://www.JSON.org
  // Originating URL    : http://www.JSON.org/JSON.js

  // Augment String.prototype. We do this in an immediate anonymous function to
  // avoid defining global variables.

  // m is a table of character substitutions.
  var m = {
    '\b': '\\b',
    '\t': '\\t',
    '\n': '\\n',
    '\f': '\\f',
    '\r': '\\r',
    '"' : '\\"',
    '\\': '\\\\'
  };

  s.parseJSON = function (filter) {

    // Parsing happens in three stages. In the first stage, we run the text against
    // a regular expression which looks for non-JSON characters. We are especially
    // concerned with '()' and 'new' because they can cause invocation, and '='
    // because it can cause mutation. But just to be safe, we will reject all
    // unexpected characters.

    try {
      if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.
        test(this)) {

          // In the second stage we use the eval function to compile the text into a
          // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
          // in JavaScript: it can begin a block or an object literal. We wrap the text
          // in parens to eliminate the ambiguity.

          var j = eval('(' + this + ')');

          // In the optional third stage, we recursively walk the new structure, passing
          // each name/value pair to a filter function for possible transformation.

          if (typeof filter === 'function') {

            function walk(k, v) {
              if (v && typeof v === 'object') {
                for (var i in v) {
                  if (v.hasOwnProperty(i)) {
                    v[i] = walk(i, v[i]);
                  }
                }
              }
              return filter(k, v);
            }
            j = walk('', j);
          }
          return j;
        }
      } catch (e) {

      // Fall through if the regexp test fails.
      }
	  // Nic nie robimy - zajmę się tym w funkcji która to wywołała
      // throw new SyntaxError("parseJSON");
    };
  }
) (String.prototype);

function flip_left_menu() {
	$main_left_list = $('#main_left_list');
	
	if($main_left_list.is(':visible')) {
		setcookie_leftmenu('so_leftmenu', '1', -10);
	}
	else {
		setcookie_leftmenu('so_leftmenu', '1', 365);
	}
	
	$main_left_list.slideToggle('slow');
	return false;
}

function setcookie_leftmenu(cookieName,cookieValue,nDays) {
	var today = new Date();
	var expire = new Date();
	if (nDays==null) nDays=1;
	expire.setTime(today.getTime() + 3600000*24*nDays);
	document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString();
	return true;
}

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.target = "_blank";
	}
}

function bind_hot_news() {
	$('#hot_news_1').click(function() {return switch_hot_news(1);});
	$('#hot_news_2').click(function() {return switch_hot_news(2);});
	$('#hot_news_3').click(function() {return switch_hot_news(3);});
}

function bind_hot_news_new() {
	$('#hot_news_1').click(function() {return switch_hot_news_new(1);});
	$('#hot_news_2').click(function() {return switch_hot_news_new(2);});
	$('#hot_news_3').click(function() {return switch_hot_news_new(3);});
	
	$('.hot_news_small_title_new').each(function() {
		var $this_ref = $(this);
		var ah = $this_ref.height();
		var ph = $this_ref.parent().height();
		var mh = ((ph - ah) / 2) - 3;
		$this_ref.css('margin-top', mh);
	});
}
		

function switch_hot_news(index) {
	index = parseInt(index);
	var $hot_news_title = $('.hot_news_title');
	var $hot_news_big_photo = $('.hot_news_big_photo');
	var $hot_news_link = $('.hot_news_link');
	
	$hot_news_title.fadeOut(500);
	
	$hot_news_big_photo
		.fadeOut(500)
		.queue(function(){
			var img = new Image();
			$(img).load(function() {
				$hot_news_big_photo.dequeue();
				$hot_news_title.text(hot_news_array[index][1]).fadeIn(500);
				$hot_news_big_photo.attr('src', hot_news_array[index][0]);
				$hot_news_link.attr('href', hot_news_array[index][2]);
			})
			.attr('src', hot_news_array[index][0]);
		})
		.fadeIn(500);
	
	// current_hot_index
	
	var $current_hot_news = $('#hot_news_' + index);
	var $current_hot_news_img = $('#hot_news_' + index + ' img');
	
	$current_hot_news_img
		.fadeOut(500)
		.queue(function(){
			var img2 = new Image();
			$(img2).load(function() {
				$current_hot_news_img.dequeue();
				$current_hot_news_img.attr('src', hot_news_array[current_hot_index][3]);
				$current_hot_news
					.attr('href', hot_news_array[current_hot_index][2])
					.attr('id', 'hot_news_' + current_hot_index)
					.attr('title', hot_news_array[current_hot_index][1])
					.unbind('click')
					.click(function() {
						var current_id = $(this).attr('id');
						current_id = current_id.substring(current_id.length - 1);
						return switch_hot_news(current_id);
					});
				current_hot_index = index;
			})
			.attr('src', hot_news_array[current_hot_index][3])
			.attr('alt', hot_news_array[current_hot_index][1]);
		})
		.fadeIn(500);
	
	return false;
}


function switch_hot_news_new(index) {
	index = parseInt(index);
	var $hot_news_title = $('.hot_news_title');
	var $hot_news_big_photo = $('.hot_news_big_photo');
	var $hot_news_link = $('.hot_news_link');
	
	$hot_news_title.fadeOut(500);
	
	$hot_news_big_photo
		.fadeOut(500)
		.queue(function(){
			var img = new Image();
			$(img).load(function() {
				$hot_news_big_photo.dequeue();
				$hot_news_title.text(hot_news_array[index][1]).fadeIn(500);
				$hot_news_big_photo.attr('src', hot_news_array[index][0]);
				$hot_news_link.attr('href', hot_news_array[index][2]);
			})
			.attr('src', hot_news_array[index][0]);
		})
		.fadeIn(500);
	
	// current_hot_index
	
	var $current_hot_news = $('#hot_news_' + index);
	var $current_hot_news_img = $('#hot_news_' + index + ' img');
	var $current_hot_news_span = $('#hot_news_' + index + ' span');
	
	$current_hot_news_img
		.fadeOut(500)
		.queue(function(){
			var img2 = new Image();
			$(img2).load(function() {
				$current_hot_news_img.dequeue();
				$current_hot_news_img.attr('src', hot_news_array[current_hot_index][3]);
				
				$current_hot_news_span.text(hot_news_array[current_hot_index][1]);
				var ah = $current_hot_news_span.height();
				var ph = $current_hot_news_span.parent().height();
				var mh = ((ph - ah) / 2) - 3;
				mh = mh < 0 ? 0 : mh;
				$current_hot_news_span.css('margin-top', mh);
				
				$current_hot_news
					.attr('href', hot_news_array[current_hot_index][2])
					.attr('id', 'hot_news_' + current_hot_index)
					.attr('title', hot_news_array[current_hot_index][1])
					.unbind('click')
					.click(function() {
						var current_id = $(this).attr('id');
						current_id = current_id.substring(current_id.length - 1);
						return switch_hot_news_new(current_id);
					});
				current_hot_index = index;
			})
			.attr('src', hot_news_array[current_hot_index][3])
			.attr('alt', hot_news_array[current_hot_index][1]);			
		})
		.fadeIn(500);
	
	return false;
}


function recommended_click() {
	var $recommended = $('.ul_recommended li');
	var current_index = 0;
	var $recommended_wrapper_inner = $('.recommended_wrapper_inner');
	
	$recommended.click(function(e){
		var $this_id = e.target.id;
		var was_move = false;
		$recommended.each(function(i) {
			if ($(this).is('.first') && $this_id == $(this).attr('id')) {
				if(current_index > 0) {
					current_index--;
				}
				else {
					current_index = 5;
				}
				var left = current_index * (-move_index);
				$recommended_wrapper_inner.animate({left: left + 'px'}, 500 );
			}
			else if ($(this).is('.last')  && $this_id == $(this).attr('id')) {
				if(current_index < 5) {
					current_index++;
				}
				else {
					current_index = 0;
				}
				var left = current_index * (-move_index);
				$recommended_wrapper_inner.animate({left: left + 'px'}, 500 );
			}
			else if($this_id == $(this).attr('id')) {
				var splitted = $this_id.split('_');
				current_index = splitted[1];
				var left = current_index * (-move_index);
				$recommended_wrapper_inner.animate({left: left + 'px'}, 500 );
			}
		});
		
		$recommended.removeClass('selected');
		$('.ul_recommended li#li_' + current_index).addClass('selected');
	});
}


function encouraged_click() {
	var $recommended = $('.ul_encouraged li');
	var current_index = 0;
	var $encouraged_wrapper_inner = $('.encouraged_wrapper_inner');
	var $encouraged_div = $('#encouraged-div-'+current_index);
	$encouraged_wrapper = $('.encouraged_wrapper');
	$encouraged_wrapper.animate({height: ($encouraged_div.height() + 20) + 'px'}, 500);
	
	$recommended.click(function(e){
		var $this_id = e.target.id;
		var was_move = false;
		$recommended.each(function(i) {
			if ($(this).is('.first') && $this_id == $(this).attr('id')) {
				if(current_index > 0) {
					current_index--;
				}
				else {
					current_index = 5;
				}
				var left = current_index * (-move_index);
				$encouraged_wrapper_inner.animate({left: left + 'px'}, 500 );
			}
			else if ($(this).is('.last')  && $this_id == $(this).attr('id')) {
				if(current_index < 5) {
					current_index++;
				}
				else {
					current_index = 0;
				}
				var left = current_index * (-move_index);
				$encouraged_wrapper_inner.animate({left: left + 'px'}, 500 );
			}
			else if($this_id == $(this).attr('id')) {
				var splitted = $this_id.split('_');
				current_index = splitted[1];
				var left = current_index * (-move_index);
				$encouraged_wrapper_inner.animate({left: left + 'px'}, 500 );
			}
		});
		
		var $encouraged_div = $('#encouraged-div-'+current_index);
		$encouraged_wrapper.animate({height: ($encouraged_div.height() + 20) + 'px'}, 500);
		
		$recommended.removeClass('selected');
		$('.ul_encouraged li#li_' + current_index).addClass('selected');
	});
}

function photos_of_the_month_click() {
	var $recommended = $('.ul_encouraged li');
	var current_index = 0;
	var $encouraged_wrapper_inner = $('.encouraged_wrapper_inner');
	var $encouraged_div = $('#encouraged-div-'+current_index);
	$encouraged_wrapper = $('.encouraged_wrapper');
	$encouraged_wrapper.animate({height: ($encouraged_div.height()) + 'px'}, 500);
	
	$recommended.click(function(e){
		var $this_id = e.target.id;
		var was_move = false;
		$recommended.each(function(i) {
			if ($(this).is('.first') && $this_id == $(this).attr('id')) {
				if(current_index > 0) {
					current_index--;
				}
				else {
					current_index = 5;
				}
				var left = current_index * (-move_index);
				$encouraged_wrapper_inner.animate({left: left + 'px'}, 500 );
			}
			else if ($(this).is('.last')  && $this_id == $(this).attr('id')) {
				if(current_index < 5) {
					current_index++;
				}
				else {
					current_index = 0;
				}
				var left = current_index * (-move_index);
				$encouraged_wrapper_inner.animate({left: left + 'px'}, 500 );
			}
			else if($this_id == $(this).attr('id')) {
				var splitted = $this_id.split('_');
				current_index = splitted[1];
				var left = current_index * (-move_index);
				$encouraged_wrapper_inner.animate({left: left + 'px'}, 500 );
			}
		});
		
		var $encouraged_div = $('#encouraged-div-'+current_index);
		$encouraged_wrapper.animate({height: ($encouraged_div.height()) + 'px'}, 500);
		
		$recommended.removeClass('selected');
		$('.ul_encouraged li#li_' + current_index).addClass('selected');
	});
}

function back_to_top() {
	$('html, body').animate({scrollTop:0}, 500);
	return false;
}

function change_font_size(e) {
	if(e.className == 'do_small_text') {
		var fontSize = '10px';
		var lineHeight = '13px';
	}
	else if(e.className == 'do_big_text') {
		var fontSize = '14px';
		var lineHeight = '18px';
	}
	else {
		var fontSize = '12px';
		var lineHeight = '15px';
	}
	
	$('.font_change').css({
		'fontSize': fontSize,
		'lineHeight': lineHeight
		});
	return false;
}

function change_slave(change_slave) {
	var slave = document.getElementById('tpllist_slave');
	var master = document.getElementById('tpllist_master');
	
	var slave_var = '0';
	if(change_slave == '1') {
		slave_var = slave.options[slave.selectedIndex].value;
	}
	
	// clear all
	slave.options.length = 1;
	
	for(var i = 0; i < slave_categories.length; i++) {
		if(master.options[master.selectedIndex].value == slave_categories[i][0] || master.options[master.selectedIndex].value == '') {
			slave.add(new Option(slave_categories[i][2], slave_categories[i][1]), null);
		}
	}
	
	for(var i = 0; i < slave.options.length; i++) {
		if(slave.options[i].value == slave_var) {
			slave.selectedIndex = i;
			break;
		}
	}
}

function flip_gallery_categories() {
	$('#gallery_categories_list').slideToggle('slow');
	return false;
}

// function flip_gallery_contests() {
	// $('#gallery_contests_list').slideToggle('slow');
	// return false;
// }

function flip_gallery_photo_managment() {
	$('#gallery_photo_managment').slideToggle('slow');
	return false;
}

function flip_gallery_contests() {
	$('#gallery_contests').slideToggle('slow');
	return false;
}

function flip_gallery_so_photos() {
	$('#gallery_swiatobrazu_photos').slideToggle('slow');
	return false;
}

function flip_gallery_trainings() {
	$('#gallery_trainings_photos').slideToggle('slow');
	return false;
}

function animate_image_big() {
	$(this).css({'z-index' : '10'});
	$(this).find('img')
		.animate({
			marginTop: '-110px',
			marginLeft: '-110px',
			top: '50%',
			left: '50%',
			width: '200px',
			height: '200px'
		}, 200);
}
		
function animate_image_small() {
	$(this).css({'z-index' : '0'});
	$(this).find('img')
		.animate({
			marginTop: '0',
			marginLeft: '0',
			top: '0',
			left: '0',
			width: '110px',
			height: '110px'
		}, 300);
}

function searchTop() {
	$('#top_list_main_element').click(function() {
		$('.top_search_list').slideToggle(250);
	});
	
	
	$('.top_search_list li a').click(function() {
		$('.top_search_list').slideUp(250);
		$('#top_list_current_element').text($(this).text());
		
		var curr_id = $(this).attr('id');
		var curr_id_splitted = curr_id.split('_');
		curr_id = curr_id_splitted[1];
		
		switch(curr_id) {
			case '2':
				$('#search_top_category').attr('value', 31);
				$('#search_top_type').attr('value', 0);
				break;
			case '3':
				$('#search_top_category').attr('value', 30);
				$('#search_top_type').attr('value', 0);
				break;
			case '4':
				$('#search_top_category').attr('value', 53);
				$('#search_top_type').attr('value', 0);
				break;
			default:
				$('#search_top_category').attr('value', '');
				$('#search_top_type').attr('value', curr_id);
				break;
		}
		return false;
	});
}

function removeAllNodes(ctrl) {
	while (ctrl.childNodes.length != 0) { ctrl.removeChild(ctrl.childNodes[0]); }
}

function removeChildNodes(ctrl) {
	var rem = 0;
	while (ctrl.childNodes.length != 1) {
		if(ctrl.childNodes[rem].id == 'photo_current_rating') {
			rem++;
		}
		ctrl.removeChild(ctrl.childNodes[rem]);
	}
}

function show_login_box() {
	$('#login_list').slideToggle(500);
}

function vote_article(article_id, vote) {
	if(!(vote == 1 || vote == -1)) {
		alert('Niepoprawna wartość oceny. Możliwe wartości to 1 oraz -1.');
		return false;
	}
	
	if(has_vote == 1) {
		return false;
	}
	
	var xmlhttp;
	
	if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); }
	else if (window.ActiveXObject) {  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
	else { alert("Twoja przeglądarka nie obsługuje AJAX'a");  return false; }
	
	var $votes_makers_inner = $('.votes_makers_inner');
	$votes_makers_inner.fadeOut('200');
	
	xmlhttp.onreadystatechange = function() {
		if(xmlhttp.readyState == 4) {
			if(xmlhttp.status == 200) {
				response_array = xmlhttp.responseText.split('|');
				if(response_array[0] != '1' || response_array.length != 3) {
					alert(xmlhttp.responseText);
					$votes_makers_inner.fadeIn('200');
				}
				else {
					var positive = parseInt(response_array[1]);
					var negative = parseInt(response_array[2]);
					
					var positive_percent = parseInt((positive / (positive + negative)) * 100);
					var negative_percent = 100 - positive_percent;
					
					$('.span-votes-positive-count').text(positive_percent + '%');
					$('.span-votes-negative-count').text(negative_percent + '%');
					$('.span-votes-all-count').text(positive + negative);
					
					has_vote = 1;
					
					$votes_makers_inner.fadeIn('200');
				}
			}
			else {
				alert("Niepoprawny adres serwera. Odpowiedź: " + xmlhttp.status);
				$votes_makers_inner.fadeIn('200');
			}
		}
	}

	xmlhttp.open("GET","ajax,ocen_artykul," + article_id + "," + vote,true);
	xmlhttp.send(null);
	return false;
}


function vote_article_new(article_id, vote) {
	if(!(vote == 1 || vote == -1)) {
		alert('Niepoprawna wartość oceny. Możliwe wartości to 1 oraz -1.');
		return false;
	}
	
	if(has_vote == 1) {
		alert('Już głosowałeś na ten artykuł');
		return false;
	}
	
	if(!is_logged) {
		$('#login_list_article')
			.css({
				'left': '330px',
				'top': '-150px'
			})
			.slideDown(500);
		return false;
	}
	
	var xmlhttp;
	
	if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); }
	else if (window.ActiveXObject) {  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
	else { alert("Twoja przeglądarka nie obsługuje AJAX'a");  return false; }
	
	var $votes_makers_inner = $('.votes_makers_inner');
	$votes_makers_inner.fadeOut('200');
	
	xmlhttp.onreadystatechange = function() {
		if(xmlhttp.readyState == 4) {
			if(xmlhttp.status == 200) {
				response_array = xmlhttp.responseText.split('|');
				if(response_array[0] != '1' || response_array.length != 3) {
					alert(xmlhttp.responseText);
					$votes_makers_inner.fadeIn('200');
				}
				else {
					var positive = parseInt(response_array[1]);
					var negative = parseInt(response_array[2]);
					
					var positive_percent = parseInt((positive / (positive + negative)) * 100);
					var negative_percent = 100 - positive_percent;
					
					$('.span-votes-positive-count').text(positive_percent + '%');
					$('.span-votes-negative-count').text(negative_percent + '%');
					$('.span-votes-all-count').text(positive + negative);
					
					has_vote = 1;
					
					$votes_makers_inner.fadeIn('200');
				}
			}
			else {
				alert("Niepoprawny adres serwera. Odpowiedź: " + xmlhttp.status);
				$votes_makers_inner.fadeIn('200');
			}
		}
	}

	xmlhttp.open("GET","ajax,ocen_artykul," + article_id + "," + vote,true);
	xmlhttp.send(null);
	return false;
}

function vote_article_2(article_id, vote, user_id) {
	if(!(vote == 1 || vote == -1)) {
		alert('Niepoprawna wartość oceny. Możliwe wartości to 1 oraz -1.');
		return false;
	}
	
	if(has_vote == 1) {
		alert('Już głosowałeś na ten artykuł');
		return false;
	}
	
	if(!is_logged) {
		$('#login_list_article')
			.css({
				'left': '330px',
				'top': '-150px'
			})
			.slideDown(500);
		return false;
	}
	
	var xmlhttp;
	
	if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); }
	else if (window.ActiveXObject) {  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
	else { alert("Twoja przeglądarka nie obsługuje AJAX'a");  return false; }
	
	var $votes_makers_inner = $('.votes_makers_inner');
	$votes_makers_inner.fadeOut('200');
	
	xmlhttp.onreadystatechange = function() {
		if(xmlhttp.readyState == 4) {
			if(xmlhttp.status == 200) {
				response_array = xmlhttp.responseText.split('|');
				if(response_array[0] != '1' || response_array.length != 3) {
					alert(xmlhttp.responseText);
					$votes_makers_inner.fadeIn('200');
				}
				else {
					var positive = parseInt(response_array[1]);
					var negative = parseInt(response_array[2]);
					
					var positive_percent = parseInt((positive / (positive + negative)) * 100);
					var negative_percent = 100 - positive_percent;
					
					$('.span-votes-positive-count').text(positive_percent + '%');
					$('.span-votes-negative-count').text(negative_percent + '%');
					$('.span-votes-all-count').text(positive + negative);
					
					$votes_makers_inner.fadeIn('200');
				}
			}
			else {
				alert("Niepoprawny adres serwera. Odpowiedź: " + xmlhttp.status);
				$votes_makers_inner.fadeIn('200');
			}
		}
	}

	xmlhttp.open("GET","ajax,ocen_artykul," + article_id + "," + vote + "," + user_id, true);
	xmlhttp.send(null);
	return false;
}

function doIframe(){
	o = document.getElementsByTagName('iframe');
	for(i=0;i<o.length;i++){
		if (/\bautoHeight\b/.test(o[i].className)){
			setHeight(o[i]);
			addEvent(o[i],'load', doIframe);
		}
	}
}

function setHeight(e){
	if(e.contentDocument){
		e.height = e.contentDocument.body.offsetHeight + 35;
	} else {
		e.height = e.contentWindow.document.body.scrollHeight;
	}
}

function addEvent(obj, evType, fn){
	if(obj.addEventListener)
	{
	obj.addEventListener(evType, fn,false);
	return true;
	} else if (obj.attachEvent){
	var r = obj.attachEvent("on"+evType, fn);
	return r;
	} else {
	return false;
	}
}

if (document.getElementById && document.createTextNode){
 addEvent(window,'load', doIframe);	
}

