var OM = OM || {};

// Plugin do powiększania zdjęć
(function ($, window, undefined) {
	$.fn.imagePreview = function (options) {
		var defaults = {
			id: "imagePreview",
			top: 0,
			left: 0
		},
				config = $.extend({}, defaults, options),
				imgs = this.find(".zoomPhoto");
		if (imgs.length) {

			var box = $("#" + config.id);
			if (!box.length) {
				box = $("<div id=\"" + config.id + "\"></div>")
				$(document.body).append(box);
			}

			imgs.bind({
				"mouseenter" : function () {
					var el = $(this);
					var d = $.data(el);
					if (d.pos === undefined) {
						d.pos = el.offset();
						d.img = $("<img src=\""+el.data("src")+"\" alt=\"\" />");
						d.img.appendTo(box);
					}
					box.css({
						left: d.pos.left + config.left < 0 ? 0 : d.pos.left + config.left + "px",
						top: d.pos.top + config.top + "px"
					});
					t = setTimeout( function () { box.fadeIn(); }, 800);
				},
				"mouseleave" : function () {
					box.hide().empty();
					clearTimeout(t);
				}
			});
		}
	};
})(jQuery, window);

jQuery( function ($) {

OM.Carousel = function (settings) {
	this.config = {
		"boxId": false,
		"navId" : false,	// id elementu z elementami navigacyjnymi
		"itemsNumber": false,
		"itemActive": 0,
		"repeat": true,	// z ostatniego elementu przechodzi do pierwszego
		"rotate": 0, // auto rotate, ile sekund wyświetlać boks
		"callback": false
	};
	if (settings) {
		$.extend(this.config, settings);
	}
	this.box = false;
	this.nav = false;
	this.timer = false;
}
OM.Carousel.prototype = {
	init: function () {
		if (this.config.boxId) {
			this.box = $("#" + this.config.boxId);
			if (this.box.length) {
				// przygotuj boks nawigacyjny, gdy zdefiniowano id
				if (this.config.navId && this.config.itemsNumber > 1) {
					this.prepareNav();
				}
				// wyswietl boks
				this.box.show();
				if (this.nav) {
					this.nav.show();
				}
				this.callback();
				// autorotacja
				if (this.config.rotate && this.config.itemsNumber > 1) {
					this.prepareTimer();
				}
			}
		}
	},

	prepareNav: function () {
		this.nav = $("#" + this.config.navId);
		if (this.nav.length) {
			this.nav.addClass("navBox");
			var html = [];
			for (var i=0, j=this.config.itemsNumber; i<j; i++) {
				html.push("<span></span>");
			}
			// back & forward button
			html.push("<span class=\"bck\"></span>");
			html.push("<span class=\"fwd\"></span>");
			this.nav.append(html.join(""));
			this.navEls = this.nav.find("span");
			$.each(this.navEls, function (i, j) { $(j).data("i", i); });
			// set event listeners on this.nav
			this.nav.delegate("span", "click", $.proxy(this.onClick, this));
			if (this.config.repeat) {
				this.nav.find(".bck, .fwd").addClass("active");
			}
		}
	},

	prepareTimer: function () {
		this.setTimer();
		var listeners = {
			"mouseenter": $.proxy(function () { clearInterval(this.timer); }, this),
			"mouseleave": $.proxy(function () { this.setTimer(); }, this)
		}
		this.box.bind(listeners);
		if (this.nav) {
			this.nav.bind(listeners);
		}
	},

	setTimer: function () {
		this.timer = setInterval($.proxy(function () {
			this.changeItem(this.config.itemActive+1);
			this.callback();
		}, this), this.config.rotate * 1000);
	},

	onClick: function (e) {
		var el = $(e.target);
		if (el.hasClass("bck")) {
			this.changeItem(this.config.itemActive-1);
		}
		else if (el.hasClass("fwd")) {
			this.changeItem(this.config.itemActive+1);
		}
		else {
			this.changeItem(el.data("i"));
		}
	},

	changeItem: function (nr) {
		if (nr < 0) {
			if (this.config.repeat) {
				nr = this.config.itemsNumber-1;
			} else {
				nr = 0;
			}
		} else if (nr >= this.config.itemsNumber) {
			if (this.config.repeat) {
				nr = 0;
			} else {
				nr = this.config.itemsNumber-1;
			}
		}
		// wywołuje funkcje callback
		// przeyła numer aktywnego elementu (aktywny element zostanie zmieniony dopiero po wywołaniu metody update).
		this.callback(nr);
	},

	callback: function (nr) {
		if (this.config.callback) {
			if (nr || nr === 0) {
				var nr = nr;
			} else {
				var nr = this.config.itemActive;
			}
			this.config.callback(nr);
		}
	},

	updateMe: function (nr) {
		if (nr || nr === 0) {
			this.config.itemActive = nr;
			if (this.nav) {
				this.navEls.removeClass("selected").eq(this.config.itemActive).addClass("selected");
			}
		}
	}
}


OM.dealerPromoBox = {
	data: false, // tablica z ofertami 
	active: false, // aktywna oferta
	carousel: false,
	cache: [],

	init: function (data) {
		if (data && data.length) {
			this.box = $("#dealerPromoBox");
			this.data = data;
			this.dataCount = data.length;
			this.cookieName = 'dpvi';
			var activeId = $.cookie(this.cookieName);
			var activeNr = false;
			if (activeId) {
				// wyswietlic nalezy nastepny elemnt, wiec zwiekszone i
				// nie moze przekroczyc wartosci this.dataCount
				for (var i = 0; i < this.dataCount-1; i++) {
					if (this.data[i]["vehicleId"] === activeId) {
						activeNr = i+1;
						break;
					}
				}
			}
			if (!activeNr) {
				activeNr = 0;
			}

			// tworzy caruselę
			this.carousel = new OM.Carousel({
				"boxId": "dealerPromoBox",
				"navId": "dealerPromoBoxNav",
				"itemsNumber": this.dataCount,
				"itemActive": activeNr,
				"rotate": 6, // 6 sekund
				"callback": $.proxy(this.listenToCarousel, this)
			});
			this.carousel.init();

			// wyświetla nagłówek
			$("#headDealerBox").show();
		}
	},

	show: function (nr) {
		// ukrywa widoczne divy
		if (this.cache[nr]) {
			this.cache[nr].show();
		}
		else {
			var tmp = [];
			tmp.push('<a href="' + this.data[nr]["url"] + '"><img src=' + this.data[nr]["photo"] + ' alt="" /></a>');
			tmp.push('<h4><a href="' + this.data[nr]["url"] + '">'+this.data[nr]["title"]+'</a> <span>' + this.data[nr]["buildYear"] + '</span></h4>');
			tmp.push('<p>' + this.data[nr]["price"] + '</p>');
			tmp.push('<p class="dealer">Oferta pochodzi ze strony dealera<br /><a href="' + this.data[nr]["url"].replace(/(^http:\/\/[a-z0-9-.]+).*/, "$1") + '">' + this.data[nr]["dealerName"] + '</a></p>');
			this.cache[nr] = $("<div>" + tmp.join("") + "</div>");
			
			$("#dealerPromoBox").append(this.cache[nr]);
		}
		// ukrywa widoczny div i wyświetla nowy 
		this.box.find("div:visible").hide();
		this.cache[nr].show();
		// ustawia ciasteczko
		$.cookie(this.cookieName, this.data[nr]["vehicleId"]);
	},

	listenToCarousel: function (i) {
		if (i || i === 0) {
			this.show(i);
			this.carousel.updateMe(i);
		}
	}
}
OM.dealerPromoBox.init(OM.dealerPromoBoxData);


// Obsługa zakładek
// zakładki są domyślnie ukryte cssami (oprócz pierwszej)
var tabs = $("#mainTabs").find("li");
var divs = $("#mainBoxes").find("div");
if (tabs.length && tabs.length === divs.length) {
	tabs
		//.show()
		.bind("click", function (e) {
			e.preventDefault();
			var a = $(this).find("a");
			tabs.removeClass("active");
			$(this).addClass("active");
			divs.hide();
			$(a.attr("href")).show();
			a.blur();
		});
}
//ostatno ogladane
lastWatchedArr = [];
lastWatchedTmp = [];
if($.cookie("lastWatched")) {
	lastWatchedTmp = $.cookie("lastWatched").split("|");
}
if(lastWatchedTmp.length > 0) {
	for (var i=0; i<lastWatchedTmp.length; i++) {
		lastWatchedArr[i] = lastWatchedTmp[i].split(";");
	}
}
if(lastWatchedArr.length > 0) {
	$("#lastViewTab").show();
	var tmp = $("#lastView").find("ul");
	for (var i=0; i<lastWatchedArr.length; i++) {
		photoSpan = lastWatchedArr[i][3] ? "<span class=\"zoomPhoto otoLegend legendZoom\" data-src=\"" + lastWatchedArr[i][3] + "\"></span>" : "";
		lastViewedLi = "<li><a href=\"" + lastWatchedArr[i][1] + "\"><span>" + lastWatchedArr[i][2] + "</span>" + photoSpan + "</a></li>";
		if (i<5) {
			tmp.eq(0).append(lastViewedLi);
		} else {
			tmp.eq(1).append(lastViewedLi);
		}
		//lastWatchedArr[i];
	}
}

// Powiększanie zdjęć
$("#mainBoxes").imagePreview({top: -84, left: -327});

// Przeładowanie modeli
OM.makeReload = function (makeId, model, value) {
	var url = location.protocol + "//" + location.hostname + "/index.php?sect=ajax&sub=model_list&makeId=";
	var modelEl = $("#"+ model);
	modelEl.empty();
	modelEl.append("<option value=\"0\">"+ modelEl.attr("data-text") +"</option>");
	if(makeId > 0) {
		var tab = "&nbsp;&nbsp;&nbsp;&nbsp;";
		$.getJSON(url + makeId, function(data) {
			if(data) {
				//alert("weszło "+ makeId);
				$.each(data, function(i,item) {
					if(item.children.length > 0) {
						modelEl.append("<option value=\""+ item.id +"\">"+ item.name +"</option>");
						$.each(item.children, function(j,child){
							modelEl.append("<option value=\""+ child.id +"\">"+ tab+child.name +"</option>");
						});
					}
					else {
						modelEl.append("<option value=\""+ item.id +"\">"+ item.name +"</option>");
					}
				});
				// pamiec formularza - zaznaczenie wybranego modelu (dodatkowy if dla chrome)
				if(value && $("option[value="+ value +"]", modelEl).val() == value) {
					modelEl.val(value);
				}
				else {
					modelEl.val(0);
				}
			}
		});
	}
}
$("#search_make_id").bind("change", function () {OM.makeReload($("#search_make_id").val(), "search_model_id"); })
});

