$(document).ready(function() {

	// jeśli nie istnieje objekt 'read_in' - stworzenie sztucznej kopii
    if (typeof read_in == 'undefined') {
		read_in = new Array;
    }

	// nadanie każdemu elementowi label wartości ID zgodnej z FOR
 	$("label").each(function(i) {
		$(this).attr("id", "label_"+$(this).attr('for'));
 	});

	// nadanie każdemu linkowi otwieranemu w nowym oknie, odpowiedniej klasy css
 	$("a").each(function(i) {
		if (($(this).attr("target") == "_blank") && !($(this).attr("class")))
			$(this).attr("class", "new_window");
 	});

    if (in_array(read_in, "formularz")) {

	// dodanie interakcji dla pól formularzy - input
	$('input:text, textarea').focus(function() {
		$(this).css(schema_style.input.on);
		var label_id = 'label_'+$(this).attr('id');
		$('#'+label_id).css(schema_style.input.on);
	});

	$('input:text, textarea').blur(function() {
		$(this).css(schema_style.input.off);
		var label_id = 'label_'+$(this).attr('id');
		$('#'+label_id).css(schema_style.input.off);
	});


	// dodanie interakcji dla pól formularzy - button
	$('input:submit, input:button, input:reset').mouseover(function() {
		$(this).css(schema_style.button.on);
	});

	$('input:submit, input:button, input:reset').mouseout(function() {
		$(this).css(schema_style.button.off);
	});
	

	// nadanie pierwszemu elementowi formularza zdarzenia 'focus'
    if (typeof auto_focus == 'undefined') $("input:text:first").focus();
	
    }
	
	if (in_array(read_in, "corners:[n]")) {
	
	// dodanie zaokrąglonych rogów dla wskazanych elementów
	$(get_args('corners')).corner("15px");
	
	}

    if (in_array(read_in, "captcha")) {

	// dodanie interakcji do zabezpieczenia captcha
	$('#img_captcha').attr('title', 'Kliknij, aby wygenerować nowy kod zabezpieczający.').css('cursor', 'hand');
	$('#img_captcha').bind("click", function() {
		this.src = page_path+'/libs/securimage/securimage_show.php?' + Math.random();
		$('#form_captcha').attr('value', '').focus();
	});

    }


    if (in_array(read_in, "test")) {

    // zmiana koloru tła po najechaniu na komórkę
    $('div.row_one').bind("mouseover", function() {
	  $(this).css(schema_style.test_one.on)
	}).bind("mouseout", function() {
	  $(this).css(schema_style.test_one.off)
	});

    $('div.row_two').bind("mouseover", function() {
	  $(this).css(schema_style.test_two.on)
	}).bind("mouseout", function() {
	  $(this).css(schema_style.test_two.off)
	});
	
	// zaokrąglenie rogów div pytań z wyjątkiem IE - komplikacje z jquery.checkbox
	if (!$.browser.msie)
	  $('div.row_one, div.row_two').corner("15px");

    }

	
    if (in_array(read_in, "tabelka")) {
	
	$('tr').bind("mouseover", function() {
	  $(this).css(schema_style.table.on)
	}).bind("mouseout", function() {
	  $(this).css(schema_style.table.off)
	});
	
	}

	
    // jeśli zostanie zmieniona wartość select - przesłanie formularza
    if (in_array(read_in, "select:[n]")) {
	
	$(get_args('select')).bind("change",  function() {
	
		var new_location;
	
		if (typeof file_name != 'undefined') {
			
			if (file_name == 'milosne-testy') {
				new_location = file_name + '/' + $(this).attr('value');
			} else if (file_name == 'autorzy') {
				new_location = file_name + '/' + $('#sort').attr('value') + ',' + $('#pokaz').attr('value') + ',' + znak;
			} else if (file_name == 'milosne-wiersze') {
				new_location = file_name + '/' + $('#sort').attr('value') + ',' + znak + ',' + $('#jezyk').attr('value');
			} else if (file_name == 'przypowiesci') {
				new_location = file_name + '/' + $('#sort').attr('value') + ',' + $('#pokaz').attr('value');
			} else if (file_name == 'milosne-ksiazki') {
				new_location = file_name + '/' + $('#sort').attr('value') + ',' + $('#pokaz').attr('value');
			} else {
				new_location = null;
			}
			
		} else {
			
			new_location = null;
			
		}
			
	    if (page_path == '.') new_location = null;
		
		if (new_location != null) {
		
			window.location.href = 'http://prawdziwa-milosc.pl/' + new_location;
			
		} else {
			$(this).parents('form').submit();
		}

		
	});
	
	}
	
	
    // testy składające się z kilku pytań
    if (in_array(read_in, "multiple:[n]")) {
	
	// dodanie hover dla tekstu odpowiedzi
	$('ul.test label').bind("mouseover", function() {
	  $(this).css(schema_style.text_label.on);
	}).bind("mouseout", function() {
	  $(this).css(schema_style.text_label.off);
	});
	
	// zamiana standardowych formularzy na ładniejsze
	if (get_args('multiple') == 1) {
	  $('input:checkbox').checkbox();
	} else {
	  $('ul.test input:radio').checkbox();
	}

	// określenie ilości odpowiedzi w pytaniu
	var how_much_in_quest = get_args('multiple') || 3;
	
    // walidacja formularza
	$('input:submit').bind("click", function() {
	    var num_required_checked = $("input:radio").length / how_much_in_quest;
	    var num_now_checked = $("input:radio:checked").length;
		
		if (num_required_checked != num_now_checked) {
			alert("Proszę odpowiedzieć na wszystkie pytania!");
			return false;
		}
	});

    }
	

	// testy polegające na wystawianiu ocen
    if (in_array(read_in, "rating")) {
	
    // zamiana elementów radio na serduszka :)
    $('form#test input:radio').rating();

    // walidacja formularza
	$('input:submit').bind("click", function() { err = false;
		$("input:hidden:input_star").each(function() {
			if (!$(this).val()) {
				alert("Proszę odpowiedzieć na wszystkie pytania!");
					err = true; return false;
			}
		});
			if (err) return false;
	});
	
    }
	
	
	// podmienianie obrazka zakupu
    if (in_array(read_in, "order_card")) {
	
      if (document.images) {
		var card_on = new Image();
		card_on.src = page_path+'/images/zamow_on.jpg';
      } 
	
	  $('#order_card').bind("mouseover", function() {
	    $(this).attr('src', card_on.src);
	  }).bind("mouseout", function() {
	    $(this).attr('src', page_path+'/images/zamow_off.jpg');
	  });
	
	}
	
	
    if (in_array(read_in, "img_zoom:[n]")) {
	  var img_to_zoom = $(get_args('img_zoom'));
	  img_to_zoom.flyout({loadingSrc: page_path+'/images/thumb-loading.gif', loader: 'loader'});
	}
	
	
	// gwiazdki umożliwiające ocenę tekstu w tle aplikacji
    if (in_array(read_in, "ocenianie")) {
	
	$('#hover-test').before('<div class="clear" /></div>');
	
    // zamiana elementów radio na serduszka :)
    $('input.star').rating({
	
		focus: function(value, link) {
			if (i > 0) {
				var tip = $('#hover-test'); 
				tip[0].data = tip[0].data || tip.html();
				tip.html(link.title || 'value: '+value);
			} else {
				i++;
			}
		},
		
		blur: function(value, link) { 
			var tip = $('#hover-test'); 
			$('#hover-test').html(tip[0].data || 'Średnia ocen: <span id="numbers"><strong>-</strong>/6</span> (<span id="numbers">0</span> oddanych głosów)');
		},
		
		callback: function(value, link) {
			$('#hover-test').hide(500, save_this_shit);
			
			function save_this_shit() {
				$.ajax({
					type: "POST",
					url: page_path+"/ajax/rating.php",
					data: "id="+this_num+"&catid="+this_cat+"&rating="+value,
				
					success: function(msg){
						eval(msg);
						$('#hover-test').html('Średnia ocen: <span id="numbers"><strong>'+user_rating.new_rating+'</strong>/6</span> (<span id="numbers">'+user_rating.num_voices+'</span> oddanych głosów). <span style="color: green;">Dziękujemy za ocenę.</span>').show(500);
					}
				});
			}
			
		}
	});
	
    }
	
	
    // pokazanie loadera u góry logo
    if (in_array(read_in, "loader")) {
      $('#wrapper').append('<span id="load">..</span>');
    }

	if (in_array(read_in, "tinymce:[n]")) {
	
	// wczytanie edytora wysiwyg - tinymce
	tinyMCE.init({
		theme : "advanced",
		mode : "exact",
		elements : get_args('tinymce'),
		language : "pl",
		strict_loading_mode : true,
		cleanup : true,
		convert_fonts_to_spans : true,
		valid_elements : "blockquote,strong/b,em/i,u,cite,abbr,acronym,a[href|target|title|lang],ul,ol,li,p,br,span[style]",
		plugins : 'safari,inlinepopups,advlink,paste',

		theme_advanced_buttons1 : "pasteword,separator,bold,italic,underline,separator,fontsizeselect,separator,forecolor,backcolor,separator,link,unlink,separator,bullist,numlist,separator,code,small", 
		theme_advanced_buttons2 : "", 
		theme_advanced_buttons3 : "", 
		theme_advanced_toolbar_location : "top", 
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : true
	});
	
	}


    if (in_array(read_in, "kontakt")) {

      // dodanie reguł walidujących formularz kontaktowy
      $("#zostaw_wiadomosc").validate({
		errorPlacement: function(error, element) {
			error.appendTo( element.parent("div").append("<div></div>") );
		},
		rules: {
			form_nazwisko: {
				required: true,
				minlength: 2,
				maxlength: 22
			},
			form_temat: {
				minlength: 5,
				maxlength: 255
			},
			form_tresc: {
				required: true,
				minlength: 30,
				maxlength: 12255
			},
			form_mail: {
				email: true
			},
			form_captcha: {
				required: true,
				minlength: 4,
				maxlength: 6,
				remote: page_path+"/ajax/captcha.php"
			}
		},
		messages: {
			form_captcha: {
				remote: 'Proszę wprowadzić prawidłowy kod zabezpieczający.'
			}
		}
	});
    }
	
	
    if (in_array(read_in, "komentarze")) {

    // dodanie reguł walidujących formularz dla komentarzy
    $("#dodaj_komentarz").validate({
		errorPlacement: function(error, element) {
			error.appendTo( element.parent("div").append("<div></div>") );
		},
		rules: {
			form_nazwisko: {
				required: true,
				minlength: 2,
				maxlength: 22
			},
			form_tresc: {
				required: true,
				minlength: 10,
				maxlength: 1000
			},
			form_mail: {
				email: true
			},
			form_www: {
				url: true
			},
			form_captcha: {
				required: true,
				minlength: 4,
				maxlength: 6,
				remote: page_path+"/ajax/captcha.php"
			}
		},
		messages: {
			form_captcha: {
				remote: 'Proszę wprowadzić prawidłowy kod zabezpieczający.'
			}
		}
	});
	
    }

	
    if (in_array(read_in, "nowy-autor")) {
	
    // dodanie reguł walidujących formularz dla komentarzy
    $("#dodaj_autora").validate({
		errorPlacement: function(error, element) {
			error.appendTo( element.parent("div").append("<div></div>") );
		},
		rules: {
			form_mail: {
				email: true
			},
			form_lang: {
				required: true
			},
			form_captcha: {
				required: true,
				minlength: 4,
				maxlength: 6,
				remote: page_path+"/ajax/captcha.php"
			}
		},
		messages: {
			form_captcha: {
				remote: 'Proszę wprowadzić prawidłowy kod zabezpieczający.'
			}
		}
	});
	
    }
	
	
    if (in_array(read_in, "nowy-wiersz")) {

    // dodanie reguł walidujących formularz dodawania wiersza
    $("#dodaj_autora").validate({
		errorPlacement: function(error, element) {
			error.appendTo( element.parent("div").append("<div></div>") );
		},
		rules: {
			lyric_title: {
				required: true,
				minlength: 3,
				maxlength: 255
			},
			lyric_author: {
				required: true
			},
			lyric_lang: {
				required: true
			},
			form_mail: {
				email: true
			},
			form_declare: {
				required: true
			},
			form_statute: {
				required: true
			},
			form_captcha: {
				required: true,
				minlength: 4,
				maxlength: 6,
				remote: page_path+"/ajax/captcha.php"
			}
		},
		messages: {
			form_captcha: {
				remote: 'Proszę wprowadzić prawidłowy kod zabezpieczający.'
			},
			lyric_author: {
				required: 'Proszę wybrać z listy autora tekstu lub dodać nowego.'
			},
			form_declare: {
				required: 'Aby możliwym było dodanie tekstu, należy zatwierdzić powyższą klauzulę.'
			},
			form_statute: {
				required: 'Proszę zapoznać się z Regulaminem i zaakceptować założone warunki.'
			}
		}
	});
    }
	
	

    if (in_array(read_in, "nowy-text")) {

    // dodanie reguł walidujących formularz dodawania wiersza
    $("#dodaj_autora").validate({
		errorPlacement: function(error, element) {
			error.appendTo( element.parent("div").append("<div></div>") );
		},
		rules: {
			text_title: {
				required: true,
				minlength: 3,
				maxlength: 255
			},
			text_lang: {
				required: true
			},
			form_declare: {
				required: true
			},
			form_statute: {
				required: true
			},
			form_captcha: {
				required: true,
				minlength: 4,
				maxlength: 6,
				remote: page_path+"/ajax/captcha.php"
			}
		},
		messages: {
			form_captcha: {
				remote: 'Proszę wprowadzić prawidłowy kod zabezpieczający.'
			},
			form_declare: {
				required: 'Aby możliwym było dodanie tekstu, należy zatwierdzić powyższą klauzulę.'
			},
			form_statute: {
				required: 'Proszę zapoznać się z Regulaminem i zaakceptować założone warunki.'
			}
		}
	});
    }
	
	

    if (in_array(read_in, "test_podsumowanie")) {

		// dodanie przyjaznych ikonek
		if (!$.browser.msie) {
			$('input:checkbox').checkbox();
		}
	
		// dodanie reguł walidujących akceptację regulaminu

	
	
		// dodanie reguł walidujących formularz kontaktowy
		$("#test").validate({
			errorPlacement: function(error, element) {
				error.appendTo( element.parent("td").append("<div></div>") ).appendTo( element.parent().next() );
			},
			rules: {
				form_nazwisko: {
					required: true,
					minlength: 2,
					maxlength: 22
				},
				form_mail: {
					required: true,
					email: true
				},
				form_statute: {
					required: true
				},
				form_sms: {
					required: true,
					remote: page_path+"/ajax/sms.php"
				}
			},
			messages: {
				form_statute: {
					required: 'Proszę zapoznać się z Polityką Prywatności i zaakceptować założone warunki.'
				},
				form_sms: {
					remote: 'Proszę wprowadzić prawidłowy kod dostępu.'
				}
			}
		})
		
		$("#test input:submit").bind("click", function() {
			if ($("#form_statute").attr('checked') == false) $("#test").submit();
		});
		
		
	}



    // wywołanie funkcji naprawiającej bugi pod ie
    if ($.browser.msie) init_repair_bugs();
	
	// dodanie kodu odpowiedzialnego za statystyki google
	if (page_path != '.') init_google_analytics('UA-7334981-1');
	
});


function init_google_analytics(GAID) {
  var head = document.getElementsByTagName('head')[0];
  var scr = document.createElement('script');
  
  scr.type = 'text/javascript';
  scr.src = (location.protocol == 'http:' ? 'http://www.' : 'https://ssl.') + 'google-analytics.com/'+'ga.js';
  var once = 0;
  var timer = setInterval(runMe, 2000);
  
  function runMe() { 
    if (scr.readyState == 'loading' || once) return;
    clearInterval(timer);
    once++;
    var pageTracker = _gat._getTracker(GAID);
	pageTracker._trackPageview();
  }
  
  scr['onload'] = runMe;
  scr['onreadystatechange'] = runMe;
  head.appendChild(scr);
}



function in_array(array, value) {
  if (array && value) {
  for (var i=0; i<array.length; ++i) {
  
    if (value.search('[n]') != -1) {
	  var read = value.slice(0, value.length-4);
	  if (array.join(',').search(read) != -1)
	    return true;
    };
	
    if (array[i] == value)
      return true;
    }
	
  return false;
  }
}

function get_args(readin) {
  var readin_string = read_in.join(',');
  var readin_kotwica = readin_string.search(readin);
  if (readin_kotwica != -1) {
    var readin_start = readin_string.slice(readin_kotwica+readin.length+2);
    var readin_end = readin_start.indexOf(']');
    return readin_start.slice(0, readin_end);
  }
}

function is_int(input){
  return typeof(input)=='number'&&parseInt(input)==input;
}

function CookieHandler() {

	this.setCookie = function (name, value, seconds) {

		if (typeof(seconds) != 'undefined') {
			var date = new Date();
			date.setTime(date.getTime() + (seconds*1000));
			var expires = "; expires=" + date.toGMTString();
		}
		else {
			var expires = "";
		}

		document.cookie = name+"="+value+expires+"; path=/";
	}

	this.getCookie = function (name) {

		name = name + "=";
		var carray = document.cookie.split(';');

		for(var i=0;i < carray.length;i++) {
			var c = carray[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
		}

		return null;
	}

	this.deleteCookie = function (name) {
		this.setCookie(name, "", -1);
	}

}


// window.error = return false;
