// Zmienne zależne od języka lc*, imgp itp. są zdefiniowane w show.php
jQuery( function ($) {
  function showOfferForm() {
    if(document.getElementById('divCaptchaCF').innerHTML == '') {
      document.getElementById('divCaptchaCF').innerHTML = '<img src=\"/rpc/captcha.php?key=' + $("#contact_form input[name='captchaKey']")[0].value + '\" alt=\"\" style=\"vertical-align: middle;\"/>';
    }
  
    offerForm.show();
  }

	var body = $(document.body);

// Formularz kontaktowy
// na otomoto.cz domyslnie form jest pokazywany
	var offerForm = $("#offerForm");
	if (offerForm && offerForm.length) {
		if(country_code == 2) {
			var offerLink = $("<a href=\".#\" tabindex=\"2\" class=\"otoLink\"><span>"+($.cookie("contactForm")=="hide" ? lcSHOW : lcHIDE)+"</span></a>");
		} else {
			var offerLink = $("<a href=\".#\" tabindex=\"2\" class=\"otoLink\"><span>"+($.cookie("contactForm")=="show" ? lcHIDE : lcSHOW)+"</span></a>");
		}
		var offerLinkTxt = offerLink.find("span");
		$("#offerFormHead").prepend(offerLink).click(function (e) {
			e.preventDefault();
			if(offerForm.is(":visible")) {
				offerForm.hide();
				if(country_code == 2) { 
					$.cookie("contactForm", "hide", { expires: 30 });
				}
				else { 
					$.cookie("contactForm", null);
				}
				offerLinkTxt.text(lcSHOW);
				offerLink.blur();
			} 
			else {
        showOfferForm();
				$("#email").focus();
				if(country_code == 2) {
					$.cookie("contactForm", null);
				}
				else {
					$.cookie("contactForm", "show", { expires: 30 });
				}
				offerLinkTxt.text(lcHIDE);
			}
		});

		if (((country_code != 2) && ($.cookie("contactForm") != "show")) || ((country_code == 2) && ($.cookie("contactForm") == "hide"))) {
			offerForm.hide();
		}
    else {
      showOfferForm();
    }

		// pola wymagane
		var phone = $("#phone");
		var email = $("#email");
		var phoneP = phone.parent();
		var emailP = email.parent();
		$("#phone, #email").bind("keyup change", function () {
			var phoneV = phone.val();
			var emailV = email.val();
			if (phoneV && emailV) {
			} else if (phoneV && !emailV) {
				emailP.removeClass("required");
				phoneP.addClass("required");
			} else if (!phoneV && emailV) {
				phoneP.removeClass("required");
				emailP.addClass("required");
			} else {
				phoneP.addClass("required");
				emailP.addClass("required");
			}
		});
	}

// Akordeon
	var accordion = $("#accordionOM");
	if (accordion && accordion.length) {
		var divs = accordion.children("div");
		var hs = accordion.children("h3");
		hs.click(function (e) { showDiv(e); });

		function showDiv(e) {
			divs.hide();
			hs.addClass("inactive");
			if (!e) {
				$(hs[0]).removeClass("inactive");
				$(divs[0]).show()
			} else {
				$(e.target).removeClass("inactive");
				$(e.target).next().show();
			}
		}
		showDiv(false);
	}

// Drukuj ogłoszenie
	if (window.lcPRINT)  {
		$("#offerFoot").append(
			$("<a href=\"#\" class=\"printLink\">"+lcPRINT+"</a>").click(function (e) {
				e.preventDefault();
				window.print();
			})
		);
	}

// Galeria zdjęć
	var photoB = $("#fotoGallerySmall");
	var photo = $("#show");
	if (photo.length) {
		var photoA = photo.find("a");
		var photoI = photo.find("img");

		pictures = [];
		if (photoB.length) {
			var photos = photoB.find("a")
				.each(function () { pictures.push($(this).attr("href")); })
				.click(function (e) {
					e.preventDefault();
					sl.trigger("loadStart");
					photoA.attr("href", $(this).attr("href"));
					slimg
						.one("load", function () {
							photoI.attr("src", $(this).attr("src"));
							sl.trigger("loadStop");	})
						.attr("src", $(this).attr("href").replace(/original/, "300x225"));
				});

			// AjaxLoader
			var slimg = $("<img/>");
			var sl = $("<div/>")
				.css({
					top: photoI.position().top+2,
					left: photoI.position().left+2,
					opacity: .5
				})
				.attr("id", "imgLoad")
				.bind("loadStart", function () { $(this).show(); })
				.bind("loadStop", function () { $(this).hide(); })
				.append(slimg);
			body.append(sl);

			// dodatkowe elementy nawigacyjne
			if (photoB.find("ul").length > 1) {
				var galleryCarousel = {
					navBox: $("<div id=\"navBox\" class=\"navBox\"></div>"),
					navNext: $("<span id=\"navNext\" class=\"navNext\"></span>"),
					navPrev: $("<span id=\"navPrev\" class=\"navPrev\"></span>"),
					navScreen: [],
					photoU: '',
					screen: 0,	// aktualnie wyswietlany screen

					init: function (el) {
						this.photoU = $(el.find("ul"));
				
						for (var i=0; i<this.photoU.length; i++) {
							this.navScreen.push($("<span id=\"screen"+i+"\"></span>"));
							this.navBox.append(this.navScreen[i]);
						}
						this.navBox.append(this.navPrev);
						this.navBox.append(this.navNext);

						el.prepend(this.navBox);
						var that = this;
						// zdarzenia onclick
						this.navBox.bind("click", {that:this}, function (e) {
							var el = $(e.target);
							// click w button "next"
							if (el.attr("id") == "navNext" && el.hasClass("active") && that.screen < that.photoU.length-1) {
								that.changeScreen(e.data.that.screen + 1);
							}
							// click w button "prev"
							else if (el.attr("id") === "navPrev" && el.hasClass("active") && that.screen > 0) {
								that.changeScreen(that.screen - 1);
							}
							// click w przelacznik "ekranu"
							else if (el.attr("id") != that.screen && el.hasClass("active")) {
								that.changeScreen(parseInt(el.attr("id").replace(/screen/,'')));
							}
						});
						this.updateNavigation();
					},

					changeScreen: function (nr) {
						$(this.photoU[this.screen]).addClass("inactive");
						this.screen = nr;
						$(this.photoU[this.screen]).removeClass("inactive");
						this.updateNavigation();
					},

					updateNavigation: function () {
						if (this.screen != 0) {
							this.navPrev.addClass("active").addClass("navPrev2");
						} else {
							this.navPrev.removeClass("active").removeClass("navPrev2");
						}
						if (this.screen < this.photoU.length-1) {
							this.navNext.addClass("active").addClass("navNext2");
						}	else {
							this.navNext.removeClass("active").removeClass("navNext2");
						}
						for (var i=0; i<this.photoU.length; i++) {
							if (this.screen == i) {
								this.navScreen[i].removeClass("active");
							}	else {
								this.navScreen[i].addClass("active");
							}
						}
					}
				}
				galleryCarousel.init(photoB);
			}
		} else {
			pictures.push(photoA.attr("href"));
		}

		photoA.click(function (e) {
			e.preventDefault();
			var pictures_count = pictures.length;
			for (var i=0; i<pictures_count; i++) {
				if (pictures[i] == $(this).attr("href")) {
					var current_img = i;
				}
			}

			var w = (screen.width) < 800 ? (screen.width) : 800;
			var h = (screen.height) < 600 ? (screen.height) : 600;
			var t = (screen.height) ? (screen.height - h) / 2 : 0;
			var l = (screen.width) ? (screen.width - w) / 2 : 0;
			var nv = window.open('', '', 'top='+t+',left='+l+',width='+w+',height='+h+',toolbar=no,directories=no,menubar=no,locations=no,status=no,scrollbars=yes,resizable=yes,fullscreen=no');
			nv.document.open();
			nv.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>otoMoto</title><link rel="stylesheet" media="all" type="text/css" href="/site_images/1/0/css/popup.css" /><script type="text/javascript">var pictures=['+$.map(pictures,function(n){return '"'+n+'"'})+'],curImg='+current_img+',imgp="'+imgp+'";</script><script type="text/javascript" src="/site_images/1/0/js/jquery-1.4.2.min.js?v=0"></script><script type="text/javascript" src="/site_images/1/0/js/popup.js?v=3"></script></head><body></body></html>');
			nv.document.close();
			nv.focus();
		});
	}

// raport spalania w akordeonie
	$("#allEngines").hide().after('<p id="moreEngines"><a href="#" class="otoLink"><span>Zobacz wszystkie silniki</span></a></p>');
	$("#moreEngines a span").click(function(){
		if ($(this).html() == 'Zobacz wszystkie silniki') {
			$(this).html('Tylko najpopularniejsze silniki');
			$("#popEngines").hide();
			$("#allEngines").show();
		} else {
			$(this).html('Zobacz wszystkie silniki');
			$("#allEngines").hide();
			$("#popEngines").show();
		}
		return false;
	});

	//kod wyswietla linki: nastepne ogłoszenie, poprzednie ogłoszenie - jesli bylo wejscie z listingu wyszukiwarki
	if (document.referrer.indexOf('?sect=search&') > -1) {
	  document.referrer.match(/&qid=([0-9]+)&/);
	  var qid = RegExp.$1;
	  $.cookie("SEARCH_QUERY_ID", qid);
	}
	//jesli poprzednia strona to ogloszenie to bez zmian
	else if (document.referrer.match(/[CTMPB]{1}[0-9]+\.html$/)) {
	  //bez zmian w cookie
	}
	//usuniecie qid z cookie jesli poprzednia strona to inna niz listing wyszukiwarki lub ogloszenie 
	else {
	  $.cookie("SEARCH_QUERY_ID", null);
	}
	//pokazanie przycskow jesli isnieje qid w cookie
	if ($.cookie("SEARCH_QUERY_ID")) {
	  $('#prevLink').show();
	  $('#nextLink').show();
	}
	
// poleć znajomemu
	var shareMail = {
		shareForm: '',
		window: '',
		init: function () {
			this.window = $(window);
			this.shareForm = $("#recommendForm");
			if (this.shareForm.length) {
				this.setListeners();
				// otwiera domyślnie
				if ((country_code == 1) && (show_recommend_form == "1")) {
					this.showForm();
				}
			}
		},
		showForm: function () {
			var left = (this.window.width() - this.shareForm.outerWidth())/2;
			var top = (this.window.height() - this.shareForm.outerHeight())/2;
			this.shareForm
				.show()
				.css({
					"top" : top,
					"left" : left
				});
			if(document.getElementById('divCaptcha').innerHTML == '') {
				document.getElementById('divCaptcha').innerHTML = '<img id="imgCaptchaInSendAdForm" src="rpc/captcha.php?key=' + document.getElementById('captchaKey').value + '" alt="" style="vertical-align: middle" />';
			}
		},
		hideForm: function () {
			this.shareForm.hide();
		},
		setListeners: function () {
			var that = this;
			// otwiera formularz
			$("#shareMailOM").bind("click", function (e) {
				e.preventDefault();
				that.showForm();
			});
			// nasluchuje na zamkniecie boksu
			$("#shareMailHead a:first").bind("click", function (e) {
				e.preventDefault();
				that.hideForm();
			});
		}
	};
	shareMail.init();
	
	// generuje link dla facebooka
	$("#facebookUrl").attr("href", "http://www.facebook.com/sharer.php?u=" + encodeURIComponent(document.URL) + "&src=sp");

});

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){options=options||{};if(value===null){value='';options.expires=-1;}var expires='';if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){var date;if(typeof options.expires=='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000));}else{date=options.expires;}expires='; expires='+date.toUTCString();}var path=options.path?'; path='+(options.path):'';var domain=options.domain?'; domain='+(options.domain):'';var secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('');}else{var cookieValue=null;if(document.cookie&&document.cookie!=''){var cookies=document.cookie.split(';');for(var i=0;i<cookies.length;i++){var cookie=jQuery.trim(cookies[i]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break;}}}return cookieValue;}};
