if(window.attachEvent)
	window.attachEvent("onload",setListeners);

function setListeners(){
	inputList = document.getElementsByTagName("INPUT");
	for(i=0;i<inputList.length;i++){
		inputList[i].attachEvent("onpropertychange",restoreStyles);
		inputList[i].style.backgroundColor = "";
	}
	selectList = document.getElementsByTagName("SELECT");
	for(i=0;i<selectList.length;i++){
		selectList[i].attachEvent("onpropertychange",restoreStyles);
		selectList[i].style.backgroundColor = "";
	}
}

function restoreStyles(){
	if(event.srcElement.style.backgroundColor != "")
		event.srcElement.style.backgroundColor = "";
}

// Site init #######################################################
$(function(){
	$.cookie('cxt_' + CONTEXT, 1, {path: '/', domain: DOMAIN_BASE});
	
	// Scroll to top action
	if ($("#arr_top").length) {
		var to_top = false;
		$("#arr_top").click(function(){
			to_top = true;
			$(window).scrollTo(0, 300, {axis: 'y', onAfter: function(){ to_top = false; }});
			$(this).hide();
		});
		
		if ( $.browser.msie && parseInt($.browser.version) === 6 ) {
			$(window).bind("scroll", function(){
				if (!to_top) {
					if (($(this).height() + $(this).scrollTop()) > ($("body").height() - 299)) {
						$("#arr_top").hide();
					}
					else {
						$("#arr_top").hide();
					}
				}
			});
		}
		else {
			$(window).bind("scroll", function(){
				if (!to_top) {
					if (($(this).height() + $(this).scrollTop()) > ($("body").height() - 299)) {
						$("#arr_top").css({position: "absolute", top: $("body").height() - 399 + "px", bottom: "auto"});
					}
					else if ($(this).scrollTop() > 600) {
						$("#arr_top").css({position: "fixed", left: $("#bd").offset().left + $("#bd").width() + 30, top: "auto", bottom: "100px"}).show();
						
					}
					else {
						$("#arr_top").hide();
					}
				}
			});
		}
	}
	
	$("body").keydown(function(e){
		if(e.which == 27){
			$("#user_toolbar_layer > .toolbar_ajax_box, #custom_modal").hide();
			$("#user_toolbar a").removeClass("on");
			$("div.tooltip").hide();
			$("div.top_nav_submenu").hide();
			$("div.left_nav_submenu").hide();
		}
	});
	
	$("body").click(function(){
		$("div.tooltip").hide();
	});

	
	// Move title after ads
	if ($("#wide_ad_unit_1").length && $("h1.h1_list").length) {
		$("h1.h1_list").detach().css({position: "relative"}).insertAfter("#wide_ad_unit_1").prepend("<span class=\"f_right mt_05\"><a href=\"http://www.facebook.com/sharer.php?u=" + escape(document.location) + "\" target=\"_blank\" class=\"i_facebook\">&nbsp;</a> <a href=\"http://twitter.com/home?status=" + escape(document.location) + "\" target=\"_blank\" class=\"i_twitter\">&nbsp;</a></span>");
	}
	
	// Init actions for top site navigation
	main_nav_actions();
	search_actions("input.top_search_input", 1);
	
	// Assign actions to top cat navigation layer
	var categories_container = $("div.top_categories_container").eq(0);
	var categories_layer = $("ul.top_categories_layer").eq(0);
	if ( (categories_container.length > 0) && (categories_container.length > 0) ) {
		categories_layer.css({left: categories_container.position().left});
		menu_actions(categories_container, categories_layer);
	}
	
	var login_container = $("#top_bar_login_actions").eq(0);
	if (login_container.length > 0) {
		var login_layer = login_container.next("ul").eq(0);
		if (login_layer.length > 0) {
			if (login_layer.width() < login_container.width()) {
				login_layer.width(login_container.width());
			}
			menu_actions(login_container, login_layer);
		}
	}
	
	// Search in category layer
	var cat_container = $("#top_search_filter").find("> li:not('.module_off,.ico_clear')").eq(0);
	if (cat_container.length > 0) {
		menu_actions(cat_container.find("> a"), cat_container.find("> ul"));
		cat_container.find("> a").click(function(){return false;});
		cat_container.find("ul a").click(function(){
			var jThis = $(this);
			jThis.closest("ul").hide().siblings("a").attr("title", jThis.text()).find("span").text(jThis.text());
			
			var href = (jThis.data("link") ? jThis.data("link") : jThis.attr("href"));
			$("#top_search").find("form").attr("action", href);
			
			if (jThis.data("key") == "-1") {
				$("#top_search").find("form").data("key", "-1");
			}
			
			return false;
		});
	}
	
	if (jQuery.cookie('prod_search_cat') > 0) {
		jQuery("#top_search_filter").find(".module_site li a").each(function(){
			if (jQuery(this).data("key") == "-1") {
				jQuery(this).triggerHandler("click");
				return false;
			}
		});
	}
	
	// Add carousel functionality
	auto_carousel();
	
	// Add close button functionality
	$("a.error_msg_close").live("click", function(e){
		$(this).closest("div[class^='box']").remove();
		$(this).closest("div[class^='error_block']").remove(); return false;
	});
	
	// Add functionality for links with 'remote_action' class
	assign_remote_action();
	// Add functionality for links with 'overlay_page' class
	assign_overlay_action(); 
	
	replace_redirect();
	
	// Run main js from current page
	if (typeof(js_init) == "function") {
		js_init();
	}
	// Run other js from current page
	if (typeof(js_init2) == "function") {
		js_init2();
	}
	// Run js from left menu
	if (typeof(js_init_left) == "function") {
		js_init_left();
	}
	// Run js from right menu
	if (typeof(js_init_right) == "function") {
		js_init_right();
	}
	
	// Add toggle boxes functionality
	autobox();
	
	// Add target='_blank' for links with rel='_blank' (for strict xhtml validation)
	$("a[rel='_blank']").click(function(e){
		this.target = "_blank";
	});
	
	// Simulate filter checkbox click
	$("#filter_box dl.filters li em").live("click", function(){
		document.location = $(this).closest("li").find("a:first").attr("href");
	});
	
	// Toolbar actions
	user_toolbar_actions();
	
	$(".direct_links").hover(function(){
		$(this).find(".row_otions").css({visibility: "visible"});
	}, function(){
		$(this).find(".row_otions").css({visibility: "hidden"});
	});
	
	// Assign print actions
	$("a.print_link").click(function(){window.print(); return false;});
	
	if ($("#search_cat_container").length) {
		if ($("#search_in_cat", "#search_cat_container").is(":checked")) {
			$(".i_unchecked", "#search_cat_container").addClass("i_checked");
		}
		
		$("#search_cat_container").click(function(){
			$(".i_unchecked", this).toggleClass("i_checked");
			if ($(".i_unchecked", this).is(".i_checked")) {
				$("#search_in_cat", "#search_cat_container").attr("checked", "checked");
			}
			else {
				$("#search_in_cat", "#search_cat_container").removeAttr("checked");
			}
			return false;
		});
	}
	
	$("#top_banner_right_slider").find("> li:first").show();
	$("#top_banner_right_slider").newsTicker();
	
	$(window).bind("resize", function(){
		$("#btm_ads > div").each(function(i, v){
			var jThis = jQuery(this);
			var id = jThis.attr("id").substr(1);
			var target = jQuery("#" + id);
			if (target.length == 0) {
				id = jThis.attr("id").substr(2);
				target = jQuery("#" + id);
			}
			if ((jThis.height() > 0) && (jThis.width() > 0)) {
				if (target.length > 0) {
					var offset = jQuery("#" + id).offset();
					jThis.css({left: offset.left});
				}
			}
			else {
				target.remove();
			}
		});
		
	}).triggerHandler("resize");
	
	$("#top_nav").find("a").each(function(){
		var jThis = $(this), section, key;
		if ( (section = jThis.metadata().section) && (key = jThis.metadata().key) ) {
			new MyNav(this, {remote_url: do_link("site.remote", "request=top_nav_submenu&section=" + section + "&key=" + key)});
		}
	});
	
	if ($("#left_nav").length) {
		$("#left_nav").find("dt a").each(function(){
			var jThis = $(this), section, key;
			if ( (section = jThis.data().section) && (key = jThis.data().key) ) {
				new MyNav(this, {remote_url: do_link("site.remote", "request=left_nav_submenu&section=" + section + "&key=" + key), submenu_class: "left_nav_submenu", position: "top_right" });
			}
		});
	}
	
	if (!(USR_profile_key > 0)) {
		// Init tooltip
		jQuery("a.i_fav_save").unbind("click").click(function(e){
			var jThis = $(this);
			$("div.tooltip_yel").remove();
			var tip = $("<div class=\"tooltip tooltip_yel\" style=\"width: 340px!important;\">" + TXT_login_add_fav + "</div>")
			.appendTo("body").css({top: jThis.offset().top, left: jThis.offset().left + 20}).click(function(){
				$(this).remove();
			});
			
			setTimeout(function(){tip.hide();}, 2000);
			return false;
		});
		
		$("#fav_ajax_tab").unbind("click").click(function(){
			var jThis = $(this);
			$("div.tooltip_yel").remove();
			var tip = $("<div class=\"tooltip tooltip_yel\" style=\"width: 340px!important;\">" + TXT_login_add_fav + "</div>")
			.appendTo("body").css({top: jThis.offset().top - 60, left: jThis.offset().left}).click(function(){
				$(this).remove();
			});
			setTimeout(function(){tip.hide();}, 2000);
			return false;
		});
	}
});

function MyNav(elem, options) {
	this.options = $.extend({}, {
		timer_show: 0,
		timer_hide: 0,
		delay_show: 200,
		delay_hide: 200,
		submenu_class: "top_nav_submenu",
		position: "bottom_left"
	}, options);
	this.is_appended = false;
	this.init(elem);
}
MyNav.prototype = {
	init: function(elem){
		this.elem = $(elem);
		this.submenu = $("<div class=\"" + this.options.submenu_class + "\"></div>");
		$.data(this.elem[0], "MyNav", this);
		$.data(this.submenu[0], "MyNav", this);
		this.elem.hover(this.elemEnter, this.elemLeave);
		this.submenu.hover(this.submenuEnter, this.submenuLeave);
	},
	elemEnter: function(e){
		var self = $.data(this, "MyNav");
		if (!self.is_appended) {
			self.submenu.html("<img style=\"width: 66px; height: 66px; margin: 5em 10em;\" src=\"" + PATH_STATIC + "/img/site/ajax_loader.gif\" />").appendTo("body");
			self.is_appended = true;
			$.get(self.options.remote_url, function(data){
				if (data) {
					self.submenu.html("<div class=\"p_1\">" + data + "</div>");
				}
			});
		}
		
		clearTimeout(self.options.timer_hide);
		self.options.timer_show = setTimeout(function(){
			self.elem.addClass("hover");
			self.submenu.show();
			
			if (self.options.position == "bottom_left") {
				if ( (self.elem.offset().left - 1 + self.submenu.width()) > ($("#bd").offset().left + $("#bd").width()) ) {
					self.submenu.css({top: self.elem.offset().top + self.elem.height() - 1, left: $("#bd").offset().left + $("#bd").width() - self.submenu.width()});
				}
				else {
					self.submenu.css({top: self.elem.offset().top + self.elem.height() - 1, left: self.elem.offset().left - 1});
				}
			}
			else if (self.options.position == "top_right") {
				if (self.submenu.outerHeight() > $(window).height()) {
					self.submenu.css({top: $(document).scrollTop(), left: self.elem.offset().left + self.elem.width() + 17});
				}
				else if ( (self.elem.offset().top + self.submenu.outerHeight()) > ($(document).scrollTop() + $(window).height()) ) {
					self.submenu.css({top: $(document).scrollTop() + $(window).height() - self.submenu.outerHeight(), left: self.elem.offset().left + self.elem.width() + 17});
				}
				else {
					self.submenu.css({top: self.elem.offset().top - 40, left: self.elem.offset().left + self.elem.width() + 17});
				}
				self.submenu.append("<em class=\"left_nav_fade\">&nbsp;</em>");
				self.submenu.find("em.left_nav_fade").css({top: self.elem.offset().top - self.submenu.offset().top});
			}
		}, self.options.delay_show);
	},
	elemLeave: function(e){
		var self = $.data(this, "MyNav");
		clearTimeout(self.options.timer_show);
		self.options.timer_hide = setTimeout(function(){
			self.elem.removeClass("hover");
			self.submenu.hide();
		}, self.options.delay_hide);
	},
	submenuEnter: function(e){
		var self = $.data(this, "MyNav");
		clearTimeout(self.options.timer_hide);
	},
	submenuLeave: function(e){
		var self = $.data(this, "MyNav");
		clearTimeout(self.options.timer_show);
		self.options.timer_hide = setTimeout(function(){
			self.elem.removeClass("hover");
			self.submenu.hide();
		}, self.options.delay_hide);
	}
}

function refresh_comp_layer(){
	// Total compare counter
	$("#comp_ajax_tab em").text("(" + comps['all'] + ")");
	
	// Build tabs and empty boxes for each category
	var comp_tabs = "<div class=\"nav_container top_off top\" style=\"visibility: hidden; width: 45px; float: right !important; margin-right: 0; top: 2px;\"><span style=\"\"><a href=\"#\" class=\"arr_left\">&nbsp;</a>&nbsp; &nbsp;<a href=\"#\" class=\"arr_right\">&nbsp;</a></span></div><div class=\"tabs_container p_rel\" style=\"overflow: hidden; height: 33px; margin-bottom: -2px;\"><ul class=\"p_rel cfix autobox {on_class: 'top', callback: function(){$(this).closest('ul.autobox').css('top', '-' + $(this).closest('li').position().top + 'px');}}\" style=\"margin-top: -2px;\">";
	var comp_boxes = "";
	
	for (var v in comps_cat_titles) {
		comp_tabs += "<li id=\"t_comp_prod_" + v + "\" class=\"top_off f_left {box: 'b_comp_prod_" + v + "'}\" style=\"margin-top: 4px;\"><span class=\"f_left\"><a class=\"f_left\" href=\"#\">" + comps_cat_titles[v] + " <em>(" + comps[v] + ")</em></a></span></li>"
		comp_boxes += "<div class=\"a_center {cat: '" + v + "'}\" id=\"b_comp_prod_" + v + "\" style=\"display: none;\"><img style=\"width: 66px; height: 66px; margin: 4em auto 0pt; text-align: center;\" src=\"" + PATH_STATIC + "/img/site/ajax_loader.gif\" /></div>";
	}
	comp_tabs += "</ul></div>";
	
	// Replace old compare tabs
	$("#comp_ajax_box").find("> div.tabs_container, > div.top_off").remove();
	$("#comp_ajax_box").prepend(comp_tabs);
	
	// Replace old compare boxes
	$("#comp_ajax_box .bxd").find("> div").remove();
	$("#comp_ajax_box .bxd").append(comp_boxes);
	
	// Add toggle actions for new tabs and boxes
	autobox("#comp_ajax_box");
	
	// Get content from remote on box open event
	$("#comp_ajax_box [id^='b_comp_prod_']").bind("box.open", function(){
		// Set cookie with last viewed category
		$.cookie('comp_section', "prod_" + $(this).metadata().cat, {path: '/', domain: DOMAIN_BASE});
		
		refresh_comp_navigation();
		
		if (!$(this).find("ul.result_list").length) {
			$.get(do_link("site.remote", "request=comp_prod_get&c=" + $(this).metadata().cat.substr(1)), function(data){}, "script");
		}
	});
}

function refresh_comp_navigation(){
	
	if ($("#comp_ajax_box ul.autobox").height() > 33) {
		$("#comp_ajax_box .arr_left").removeClass("arr_left_disabled");
		$("#comp_ajax_box .arr_right").removeClass("arr_right_disabled");
		var top = $("#comp_ajax_box ul.autobox").css("top");
		top = parseInt(top.substr(0, top.length - 2));

		if (top >= 0) {
			$("#comp_ajax_box .arr_left").addClass("arr_left_disabled");
		}
		
		if (top <= -($("#comp_ajax_box ul.autobox").height() - 33)) {
			$("#comp_ajax_box .arr_right").addClass("arr_right_disabled");
		}
		
		$("#comp_ajax_box div.nav_container").css("visibility", "visible");
		$("#comp_ajax_box .arr_left").die("click").live("click", function(){
			var old_top = $("#comp_ajax_box ul.autobox").css("top");
			var new_top = 33 + parseInt(old_top.substr(0, old_top.length - 2));
			if (new_top >= 0) {
				$(this).addClass("arr_left_disabled");
			}
			
			if (new_top > -($("#comp_ajax_box ul.autobox").height() - 33)) {
				$("#comp_ajax_box .arr_right").removeClass("arr_right_disabled");
			}
			if (new_top > 0) {
				return false;
			}
			$("#comp_ajax_box ul.autobox").css("top", new_top + "px");
			return false;
		});
		
		$("#comp_ajax_box .arr_right").die("click").live("click", function(){
			var old_top = $("#comp_ajax_box ul.autobox").css("top");
			var new_top = -33 + parseInt(old_top.substr(0, old_top.length - 2));
			if (new_top < 0) {
				$("#comp_ajax_box .arr_left").removeClass("arr_left_disabled");
			}
			if (new_top <= -($("#comp_ajax_box ul.autobox").height() - 33)) {
				$(this).addClass("arr_right_disabled");
			}
			if (new_top < -($("#comp_ajax_box ul.autobox").height() - 33)) {
				return false;
			}
			$("#comp_ajax_box ul.autobox").css("top", new_top + "px");
			return false;
		});
	}
	else {
		$("#comp_ajax_box div.nav_container").css("visibility", "hidden");
	}
}

function refresh_search_layer(type){
	if (typeof(type) == "undefined") {type = "";}
	
	$("#search_ajax_tab em").text("(" + search['all'] + ")");
	$("#t_search_prod em").text("(" + search['prod'] + ")");
	
	// Check for allowed type
	if ($.inArray(type, ["prod"]) != -1) {
		$("#b_saerch_" + type).html("<img style=\"width: 66px; height: 66px; margin: 4em auto 0pt; text-align: center;\" src=\"" + PATH_STATIC + "/img/site/ajax_loader.gif\">");
		// Force refresh if box is already open
		if ($("#b_search_" + type).is(":visible")) {
			$("#b_search_" + type).trigger("box.open");
		}
		// If tab is active and hidden, replace once focus event with open event
		else if ($("#b_search_" + type).css("display") == "block") {
			$("#b_search_" + type).bind("box.focus", function(){
				$(this).unbind("box.focus").trigger("box.open");
			});
		}
	}
}

function refresh_view_layer(type){
	if (typeof(type) == "undefined") {type = "";}
	// Update counters
	$("#view_ajax_tab em").text("(" + views['all'] + ")");
	$("#t_view_prod em").text("(" + views['prod'] + ")");
	$("#t_view_realestate em").text("(" + views['realestate'] + ")");
	
	// Check for allowed type
	if ($.inArray(type, ["prod", "realestate"]) != -1) {
		$("#b_view_" + type).html("<img style=\"width: 66px; height: 66px; margin: 4em auto 0pt; text-align: center;\" src=\"" + PATH_STATIC + "/img/site/ajax_loader.gif\">");
		// Force refresh if box is already open
		if ($("#b_view_" + type).is(":visible")) {
			$("#b_view_" + type).trigger("box.open");
		}
		// If tab is active and hidden, replace once focus event with open event
		else if ($("#b_view_" + type).css("display") == "block") {
			$("#b_view_" + type).bind("box.focus", function(){
				$(this).unbind("box.focus").trigger("box.open");
			});
		}
	}
}

function refresh_fav_layer(type){
	if (typeof(type) == "undefined") {type = "";}
	// Update counters
	$("#fav_ajax_tab em").text("(" + favs['all'] + ")");
	$("#t_fav_prod em").text("(" + favs['prod'] + ")");
	$("#t_fav_store em").text("(" + favs['store'] + ")");
	$("#t_fav_realestate em").text("(" + favs['realestate'] + ")");
	$("#t_fav_manuf em").text("(" + favs['manuf'] + ")");
	$("#t_fav_other em").text("(" + favs['other'] + ")");
	
	// Check for allowed type
	if ($.inArray(type, ["prod", "store", "realestate", "manuf", "other"]) != -1) {
		$("#b_fav_" + type).html("<img style=\"width: 66px; height: 66px; margin: 4em auto 0pt; text-align: center;\" src=\"" + PATH_STATIC + "/img/site/ajax_loader.gif\">");
		// Force refresh if box is already open
		if ($("#b_fav_" + type).is(":visible")) {
			$("#b_fav_" + type).trigger("box.open");
		}
		// If tab is active and hidden, replace once focus event with open event
		else if ($("#b_fav_" + type).css("display") == "block") {
			$("#b_fav_" + type).bind("box.focus", function(){
				$(this).unbind("box.focus").trigger("box.open");
			});
		}
	}
}

// Handle user toolbar actions #######################################################
function user_toolbar_actions(){
	
	if (!$("#user_toolbar").length) {return false;}

	var animating = false;
	
	// Compact toolbar
	if ($.cookie("user_toolbar") == "off") {
		$("#toggle_user_toolbar").html("&raquo;");
		$("#toggle_user_toolbar").addClass("user_toolbar_off");
		$("#user_toolbar_wide").css({left: - $(document).width() + 20});
	}
	
	// Set boxes widths
	$("#user_toolbar_layer > .toolbar_ajax_box").width($("#user_toolbar").innerWidth() - 12);
	$("#feedback_ajax_box").width(390).css({marginLeft: "500px"});
	
	// Init modal
	$("#custom_modal").css({opacity: 0.8, height: $(document).height() + "px"});
	
	// Hide modal layer and boxes
	$("#custom_modal, #user_toolbar_layer a.i_close").click(function(){
		$("#user_toolbar_layer > .toolbar_ajax_box, #custom_modal").hide();
		$("#user_toolbar a").removeClass("on");
		return false;
	});
	
	// Add actions on main left tabs
	$("#user_toolbar a").not(".direct").click(function(){
		var jThis = $(this);
		
		// Tab is on - hide modal layer and boxes
		if (jThis.is(".on")) {
			$("#user_toolbar_layer > .toolbar_ajax_box").hide();
			$("#user_toolbar li a").removeClass("on");
			$("#custom_modal").hide();
		}
		// Tab is off
		else {
			// On main tab click open last section
			// Get tab section
			var section = $(this).metadata().section;
			// Get last section id
			var tab = $("#t_" + section + "_" + $.cookie(section + "_section") + " a");
			
			// Return false if box doesn't exist for current tab
			if ($("#" + section + "_ajax_box .autobox li").length) {
				$("#" + section + "_ajax_box .bxd > span.light").hide();
			}
			
			// Hide all boxes
			$("#user_toolbar_layer > .toolbar_ajax_box").hide();
			// Show modal layer
			$("#custom_modal").show().css({height: $(document).height() + "px"});
			// Mark as off all tabs
			$("#user_toolbar li a").removeClass("on");
			// Mark as on current tab
			jThis.addClass("on");
			// Show box for current tab
			$("#" + section + "_ajax_box").show();
			
			// If found, open
			if (tab.length > 0) {
				tab.triggerHandler("click");
			}
			// If not found, open first section
			else {
				// Open first tab if no or invalid cookie
				$("#" + section + "_ajax_box .autobox a:first").triggerHandler("click");
			}
			
			// Add iframe container
			if (jThis.is("#feedback_ajax_tab")) {
				$("#feedback_container").html("<iframe src=\"" + do_link("site.feedback", "") + "\" style=\"width: 350px; height: 395px; border: 0; background-color: transparent;\" scrollbar=\"no\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\" frameborder=\"0\"></iframe>")
			}
		}
		
		return false;
	});
	
	// Add actions for toggle button
	$("#toggle_user_toolbar").click(function(){
		// If animation is in progress return false
		if (animating) {return false;}
		
		animating = true;
		
		$("#user_toolbar_layer > .toolbar_ajax_box, #custom_modal").hide();
		$("#user_toolbar a").removeClass("on");
		
		if ($("#user_toolbar_wide").position().left < 0) {
			$("#toggle_user_toolbar").removeClass("user_toolbar_off");
			$("#toggle_user_toolbar").html("&laquo;");
			
			$("#user_toolbar_wide").animate({left: 0}, 1000, "", function(){
				animating = false;
			});
		}
		else {
			$("#user_toolbar_wide").animate({left: - $(document).width() + 20}, 1000, "", function(){
				$("#toggle_user_toolbar").addClass("user_toolbar_off");
				$("#toggle_user_toolbar").html("&raquo;");
				animating = false;
			});
		}
		
		return false;
	});
	
	// Init counters and layers
	refresh_comp_layer();
	refresh_view_layer();
	refresh_fav_layer();
	refresh_search_layer();
	
	// Load data when subtab first opens and store subtab position in cookie
	$("#user_toolbar_layer .toolbar_ajax_box .bxd > div").bind("box.open", function(){
		var dat = $(this).attr("id").split("_");
		// Comp requests are handled separately
		if (dat[1] != "comp") {
			$.cookie(dat[1] + '_section', dat[2], {path: '/', domain: DOMAIN_BASE});
			
			if (!$(this).find("ul.result_list").length) {
				$.get(do_link((dat[1] == "fav" ? "my.remote" : "site.remote"), "request=" + dat[1] + "_" + dat[2] + "_get"), function(data){}, "script");
			}
		}
	});
	
	// $.live_remote_action("#user_toolbar .live_actions a");
	
	// Assign navigation actions
	$("#user_toolbar_layer a.med_arr_prev, #user_toolbar_layer a.med_arr_next").live("click", function(){
		$(this).closest("div").find("ul.result_list").replaceWith("<div class=\"a_center\"><img src=\"" + PATH_STATIC + "/img/site/ajax_loader.gif\" style=\"width: 66px; height: 66px; margin: 4em auto 0 auto; text-align: center;\" /></div>");
		do_remote_action($(this).metadata());
		return false;
	});
	// Disable inactive arrows
	$("#user_toolbar_layer a.med_arr_prev_off, #user_toolbar_layer a.med_arr_next_off").live("click", function(){return false;});
	
	// Handle item delete
	$("#user_toolbar_layer a.request_item_delete").live("click", function(){
		// Build request metadata
		var mdata = $(this).metadata();
		var section = mdata.section;
		var type = mdata.type;
		var new_mdata = $.extend({}, mdata);
		delete new_mdata.section;
		delete new_mdata.type;
		new_mdata.page = (section == "fav" ? "my.remote" : "site.remote");
		new_mdata.request = section + "_" + type + "_delete";
		new_mdata.datatype = "script";
		
		do_remote_action($.extend(new_mdata, {callback: function(data){
			// Call refresh layer for current section
			window["refresh_" + section + "_layer"](type);
			// If no subtabs left, hide all
			if (!$("#" + section + "_ajax_box .autobox li").length) {
				/*$("#user_toolbar_layer > .toolbar_ajax_box").hide();
				$("#user_toolbar li a").removeClass("on");
				$("#custom_modal").hide();*/
				$("#" + section + "_ajax_box .bxd > span.light").show();
			} 
			else {
				var tab = $("#t_" + section + "_" + $.cookie(section + "_section") + " a");
				if (tab.length > 0) {
					tab.triggerHandler("click");
				}
				else {
					// Open first tab if no or invalid cookie
					$("#" + section + "_ajax_box .autobox a:first").triggerHandler("click");
				}
			}
			
			// Callback function (defined locally)
			if (typeof(window["after_" + section + "_" + type + "_delete"]) == "function") {
				window["after_" + section + "_" + type + "_delete"](new_mdata);
			}
		}}));
		
		return false;
	});
	
	// Handle list delete
	$("#user_toolbar_layer").delegate(".request_delete_list", "click", function(){
		// Build request metadata
		var mdata = $(this).metadata();
		var section = mdata.section;
		var type = mdata.type;
		var texts = $.extend({}, {txt_ok: mdata.txt_ok, txt_cancel: mdata.txt_cancel, txt_confirm: mdata.txt_confirm});
		var new_mdata = $.extend({}, mdata);
		delete new_mdata.section;
		delete new_mdata.type;
		delete new_mdata.txt_ok;
		delete new_mdata.txt_cancel;
		delete new_mdata.txt_confirm;
		new_mdata.page = (section == "fav" ? "my.remote" : "site.remote");
		new_mdata.request = section + "_" + type + "_delete_list";
		new_mdata.datatype = "script";
		
		// Promt for confirmation
		Boxy.confirm("<b class=\"small\">" + texts.txt_confirm + "</b>", function(){
			do_remote_action($.extend(new_mdata, {callback: function(data){
				
				// Call refresh layer for current section
				window["refresh_" + section + "_layer"](type);
				// If no subtabs left, hide all
				if (!$("#" + section + "_ajax_box .autobox li").length) {
					/*$("#user_toolbar_layer > .toolbar_ajax_box").hide();
					$("#user_toolbar li a").removeClass("on");
					$("#custom_modal").hide();*/
					$("#" + section + "_ajax_box .bxd > span.light").show();
				} 
				else {
					var tab = $("#t_" + section + "_" + $.cookie(section + "_section") + " a");
					if (tab.length > 0) {
						tab.triggerHandler("click");
					}
					else {
						// Open first tab if no or invalid cookie
						$("#" + section + "_ajax_box .autobox a:first").triggerHandler("click");
					}
				}
				
				// Callback function (defined locally)
				if (typeof(window["after_" + section + "_" + type + "_delete_list"]) == "function") {
					window["after_" + section + "_" + type + "_delete_list"](new_mdata);
				}
			}}));
		}, texts);
		
		return false;
	});
	
}

// Handle main navigation actions #######################################################
// Generic function for submenu toggle
function menu_actions(_target, _submenu, instant){
	// Select main menu button
	var target = jQuery(_target);
	// Select submenu
	var submenu = jQuery(_submenu);
	// Define local timer
	var timer;
	// Select main menu button
	var parent = jQuery(_target).closest("div");
	var duration = ((instant > 0) ? 10 : 300);
	
	// Assign button actions
	target.hover(function(e){
		clearTimeout(timer);
		submenu.show();
		target.addClass("hover");
		parent.addClass("p_rel");
	}, function(e){
		timer = setTimeout(function(){
			submenu.hide();
			target.removeClass("hover");
			parent.removeClass("p_rel");
		}, duration);
	});
	
	// Assign submenu actions
	submenu.hover(function(e){
		clearTimeout(timer);
	}, function(e){
		timer = setTimeout(function(){
			submenu.hide();
			target.removeClass("hover");
			parent.removeClass("p_rel");
		}, duration);
	});
}


var main_nav_current_button;
var user_nav_current_button;

function main_nav_actions(){
	if (!$("#main_nav").length){return false}
	// Define local timer
	var timer;
	var duration = 300;
	var buttons = $("#main_nav > ul > li > a");
	var submenus = $("#main_nav > ul > li > ul");
	
	submenus.bgiframe();
	
	var user_buttons = $("ul.right_toolbar li.li_cont > a");
	var user_submenus = $("ul.right_toolbar li.li_cont > .li_cont_box");
	
	// Assign button actions
	buttons.hover(function(e){
		main_nav_current_button = $(this);
		clearTimeout(timer);
		$("#main_nav > ul > li").not(main_nav_current_button.closest("li")).removeClass("on");
		main_nav_current_button.closest("li").addClass("on");
	}, function(e){
		timer = setTimeout(function(){
			main_nav_current_button.closest("li").removeClass("on");
		}, duration);
	});
	
	// Assign submenu actions
	submenus.hover(function(e){
		clearTimeout(timer);
	}, function(e){
		timer = setTimeout(function(){
			main_nav_current_button.closest("li").removeClass("on");
		}, duration);
	});
	
	// Assign user button actions
	user_buttons.hover(function(e){
		user_nav_current_button = $(this);
		clearTimeout(timer);
		$("ul.right_toolbar li.li_cont").not(user_nav_current_button.closest("li")).removeClass("hover").find("> a").removeClass("on");
		user_nav_current_button.closest("li").addClass("hover").find("> a").addClass("on");
	}, function(e){
		timer = setTimeout(function(){
			user_nav_current_button.closest("li").removeClass("hover").find("> a").removeClass("on");
		}, duration);
	});
	
	// Assign submenu actions
	user_submenus.hover(function(e){
		clearTimeout(timer);
	}, function(e){
		timer = setTimeout(function(){
			user_nav_current_button.closest("li").removeClass("hover").find("> a").removeClass("on");
		}, duration);
	});
}

// Handle top search actions #######################################################
function search_actions(target, focus){
	// Select search input
	var input = $(target);
	
	if (!input.length){return false;}
	else {$("#top_search_filter").show();}
	
	if ((typeof(focus) == "undefined") || hasFocus) {
		focus = 0;
	}
	
	if ( ($.cookie('prod_search_cat') > 0) && ($("#search_in_cat").length > 0) && ($("#search_in_cat").metadata().cat == $.cookie('prod_search_cat')) ) {
		$("#search_in_cat").trigger("click");
	}
	
	if (input.length > 0) {
		// Default search text
		var txt = input.metadata().txt;
		var search_string = input.metadata().search_string;
		// Select closest parent form
		var par = input.closest("form");
		
		// No user input
		if (!search_is_focused) {
			// If input is empty add default text
			if ($.trim(search_string) == "") {
				input.css("color", "#AAAAAA");
				input.val(txt);
			}
			else {
				input.css("color", "#666666");
				input.val(search_string);
			}
		}
		
		var link = $("<a href=\"#\" style=\"display: inline-block; height: 43px;\"><img src=\"" + PATH_STATIC + "/img/img_map/top_search_clear.gif\" style=\"width: 10px; height: 10px; margin-top: 18px; vertical-align: top;\" /></a>").click(function(){
			input.val("");
			input.get(0).focus();
			link.addClass("hidden");
			search_string = "";
			txt = "";
			return false;
		});
		$("#top_search_filter").find(".ico_clear").html(link);
		
		// Assign input actions
		input.focus(function(e){
			// Remove default text on focus
			if (($.trim(input.val()) == "") || (input.val() == txt)) {
				input.val("");
				input.css("color", "#666666");
			} else {
				input.get(0).select();
			}
		}).blur(function(e){
			// Add default text on blur if input is empty
			if ($.trim(input.val()) == "") {
				// If input is empty add default text
				if ($.trim(search_string) == "") {
					input.css("color", "#AAAAAA");
					input.val(txt);
				}
				else {
					input.css("color", "#666666");
					input.val(search_string);
				}
			}
			else {
				link.removeClass("hidden");
			}
		});
		
		if (focus) {
			input.get(0).focus();
		}
		
		// If input is empty or has default text, disable form submision
		par.submit(function(e){
			if (($.trim(input.val()) == "") || (input.val() == txt)) {
				return false;
			}
			
			if (par.data("key") == "-1") {
				var date = new Date();
				date.setTime(date.getTime() + (20 * 1000));
				$.cookie('prod_search_cat', "1", {path: '/', domain: DOMAIN_BASE, expires: date});
			}
			else {
				$.cookie('prod_search_cat', "", {path: '/', domain: DOMAIN_BASE, expires: -1});
			}
		});
	}
}

function auto_carousel(){
	var carousel = $("div.auto_carousel");
	carousel.each(function(i, v){
		var thisCarousel = $(v);
		var opt = $.extend({loop: false, nextBtnInsert: 'prependTo', dispItems: 3, slideEasing: 'easeOutCubic', animSpeed: 'slow', combinedClasses: true, callback: function(data){
			if (thisCarousel.closest("#daily_deals").length) {
				if (thisCarousel.find("li:eq(" + data + ")").length && thisCarousel.find("li:eq(" + data + ")").metadata().offer) {
					$("#daily_deals .img_offer").html(thisCarousel.find("li:eq(" + data + ")").metadata().offer).show();
				}
				else {
					$("#daily_deals .img_offer").hide();
				}
			}
			
			if (thisCarousel.closest("#home_slider").length) {
				if (thisCarousel.find("li:eq(" + data + ")").length) {
					thisCarousel.closest("#home_slider").find(".links dl:eq(" + data + ")").siblings("dl").hide().end().show();
					thisCarousel.closest("#home_slider").find(".pics > div:eq(" + data + ")").siblings("div").hide().end().show();
					thisCarousel.closest("#home_slider").find("form.home_slider_search").attr("action", thisCarousel.closest("#home_slider").find(".links dl:eq(" + data + ")").find("dt a:first").attr("href"));
					thisCarousel.closest("#home_slider").find("form.home_slider_search input").focus(function(){
						console.log(thisCarousel);
					}).blur(function(){
					});
				}
			}
		}}, thisCarousel.metadata());
		thisCarousel.carousel(opt).removeClass("invisible").removeClass("stealth");
	});
}

function autobox(context){
	
	if (typeof(context) == "undefined") {
		context = "";
	}
	
	var autobox = $(context + " ul.autobox");
	autobox.each(function(i, v){
		var thisAutobox = $(v);
		var opt = $.extend({on_class: "on", auto_focus: 0, callback: function(){}}, thisAutobox.metadata());
		
		thisAutobox.find("a").click(function(){
			$(this)[0].blur();
			var jParent = $(this).closest("li");
			var jBox = $("#" + jParent.metadata().box);
			
			jParent.siblings().removeClass(opt.on_class);
			jParent.addClass(opt.on_class);
			
			// We have a callback function to call
			if (typeof(opt.callback) == "function") {
				opt.callback.call(this);
			}
			
			if (jBox.length) {
				jBox.siblings("div[id^='b_']").hide();
				if (!jBox.is(":visible")) {
					jBox.show();
					jBox.trigger("box.open");
				}
				else {
					jBox.show();
					jBox.trigger("box.focus");
				}
			}
			
			if ( (opt.use_hash == true) && (typeof(jParent.metadata().hash) != "undefined") && (jParent.metadata().hash != null) ) {
				document.location.hash = jParent.metadata().hash;
			}
			
			return false;
		});
		
		if ( (opt.use_hash == true) && (document.location.hash.length > 0) ) {
			thisAutobox.find("#t_" + document.location.hash.substr(1) + " a").trigger("click");
		}
		
		// Simulate click on first tab
		if (!thisAutobox.find("li." + opt.on_class).length && opt.auto_focus) {
			thisAutobox.find("a:first").trigger("click");
		}
	});
}

// Show specific details for every search tab
function show_details(category_select_value, context){
	if (typeof(context) == "undefined") {
		context = "";
	}
	
	jQuery(context + " [class^='input_']").hide();
	jQuery(context + " .input_" + category_select_value).show();
}

// Populate models select #######################################################
function populate_models(form_id, select_name_manufacturer, select_name_model, car_type, selected_model){
	
	if (car_type != "new") {
		car_type = "used";
	}
	
	var models_select = $("select[name='" + select_name_model + "']", "#" + form_id);
	
	models_select.empty();
	$("<option value=\"" + 0 + "\"></option>").html(txt_loading + "...").appendTo(models_select);
	$(models_select).attr("disabled", "disabled");
	
	var manufacturer_select = $("form#" + form_id + " select[name='" + select_name_manufacturer + "']");
	
	var manufacturer_select = $("select[name='" + select_name_manufacturer + "']", "#" + form_id);
	var manufacturer_selection = manufacturer_select.selectedValues()[0];
	
	if (manufacturer_selection != "") {
	
		var URL = do_link("site.remote", "request=models&fk_manufacturer=" + manufacturer_selection + "&car_type=" + car_type);

		models_select.load(URL, {}, function(){
		
			models_select.removeAttr("disabled");
			
			if ((selected_model != undefined) && (selected_model != "") && (selected_model != 0)) {
				
				/*var this_option = $("[value='" + selected_model + "']", $(models_select)).get(0);
				this_option.setAttribute('selected', true);*/
				
				models_select.selectOptions(selected_model, true);
			}
			else {
				/*var this_option = $("[value='0']", $(models_select)).get(0);
				this_option.setAttribute('selected', true);*/
				
				models_select.selectOptions("0", true);
			}
			
			if (typeof(return_models) == "function") {
				return_models();
			}
		});	
	}
	else {
		
	}
	
}

// ################################################################################
// Form functions #######################################################

// Focus on input
function jform_focus(form_id){
	$(":input[value='']:not(select):enabled:visible:first", "form#" + form_id).focus();
}

// Disable submit buttons
function jform_do_submit(form_id){
	
	var my_form = $("form#" + form_id);
	// var loading = $("<img src=\"" + PATH_STATIC + "/img/site/loading_small.gif\" align=\"absmiddle\" style=\"width: 16px; height: 16px;\">");
	var loading = $("<img src=\"" + PATH_STATIC + "/img/site/circle_loading2.gif\" style=\"position: absolute; top: 9px; right: 8px; width: 16px; height: 16px;\">");
	
	my_form.submit(function() {
		if (!form_is_submitted) {
			// Disable all buttons from my form
			$(":button, :submit", my_form).attr("disabled", "disabled");
			
			$(":submit", my_form).each(function(i, v){
				var jThis = $(v);
				jThis.addClass(jThis.hasClass("btn_small") ? "btn_disabled_small" : "btn_disabled");
				loading.appendTo(jThis);
			});
			
			form_is_submitted = 1;
			submitted_form = form_id;
		}
	});
}

function jform_set_select(sel_name, form_id, sel_value){
	$("form#" + form_id + " select[name='" + sel_name + "']:first").val(sel_value);
}

function jform_set_radio(radio_name, form_id, selected_value){
	var this_radio = $("form#" + form_id + " :radio[name='" + radio_name + "'][value='" + selected_value + "']:first");
	
	if ($(this_radio).length > 0) {
		$(this_radio).click();
	}
}

function jform_set_checked(check_name, form_id, checked_mode){
	if (checked_mode != "" && checked_mode != 0 && checked_mode != "off") {
		$("form#" + form_id + " :checkbox[name='" + check_name + "']:first").attr("checked", "checked");
	}
}

function jform_check_all(form_id){
	$("form#" + form_id + " :checkbox").attr("checked", "checked");
}

function jform_uncheck_all(form_id){
	$("form#" + form_id + " :checkbox").removeAttr("checked");
}

function form_set_select_id(sel_id, form_name, sel_index) {
	var obj = dom_get_element(sel_id);

	var sel_length = obj.length;

	for (optionCounter = 0; optionCounter < sel_length; optionCounter++) {
		if (obj.options[optionCounter].value == sel_index){
			obj.selectedIndex = optionCounter;
		}
	}
}

// ################################################################################


/*********** Products page functions ************/

function assign_filters_actions(){
	$("li.more_filters a").click(function(){
		var dl = $(this).closest("dl");
		$("dd", dl).toggle();
		
		$("dd", dl).each(function(){
			if ($(this).height() > 250) {
				$(this).height(250);
			}
		});
		
		return false;
		
	});
	
	// Resize stores box
	$("#prod_dd").height(Math.min($("#prod_dd").height(), 335)).removeClass("invisible");
	
	$("#filter_box dt").click(function(){
		$(this).closest("dl").toggleClass("closed");
		
		return false;
	});
	
	$("a.all_filters").unbind().click(function(e){
		var par = $(e.target).closest("dd");
		var more_div = $(e.target).closest(".more_filters");
		
		$(more_div).prepend("<img src=\"" + PATH_STATIC + "/img/site/aloader.gif\" class=\"f_right\" />");
		
		$(par).load($(this).metadata().expand, function(){
			par.prev("dt").find("img").hide();
			if ($(par).height() > 250) {
				$(par).height(250);
			}
		});
	
		return false;
	});
	
	$(".color_matrix li a").hover(function(e){
		$(this).addClass("on");
	}, function(e){
		$(this).removeClass("on");
	});
}

// Friend handling (in profile page)
function friend_handling(how){

	if (how == "no_friends_at_all") {
		jQuery("#no_friends_at_all").show();
		jQuery("#we_re_friends_status").hide();
		jQuery("#we_re_friends_action").hide();
		jQuery("#friend_request_sent").hide();
		jQuery("#friend_request_received").hide();
	}
	else if (how == "friend_request_sent") {
		jQuery("#no_friends_at_all").hide();
		jQuery("#we_re_friends_status").hide();
		jQuery("#we_re_friends_action").hide();
		jQuery("#friend_request_sent").show();
		jQuery("#friend_request_received").hide();
	}
	else if (how == "friend_request_received") {
		jQuery("#no_friends_at_all").hide();
		jQuery("#we_re_friends_status").hide();
		jQuery("#we_re_friends_action").hide();
		jQuery("#friend_request_sent").hide();
		jQuery("#friend_request_received").show();
	}
	else if (how == "we_re_friends") {
		jQuery("#no_friends_at_all").hide();
		jQuery("#we_re_friends_status").show();
		jQuery("#we_re_friends_action").show();
		jQuery("#friend_request_sent").hide();
		jQuery("#friend_request_received").hide();
	}
	else if (how == "blocking" || how == "no_permissions") {
		jQuery("#no_friends_at_all").hide();
		jQuery("#we_re_friends_status").hide();
		jQuery("#we_re_friends_action").hide();
		jQuery("#friend_request_sent").hide();
		jQuery("#friend_request_received").hide();
	}
	else if (how == "block") {
		jQuery("#no_friends_at_all").hide();
		jQuery("#we_re_friends_status").hide();
		jQuery("#we_re_friends_action").hide();
		jQuery("#friend_request_sent").hide();
		jQuery("#friend_request_received").hide();
		jQuery("#interest_main").hide();
		jQuery("#send_messages").hide();
		jQuery("#profile_add_fav").hide();
		jQuery("#profile_is_fav").hide();
		jQuery("#can_block").hide();
		jQuery("#can_unblock").show();
	}
	else if (how == "unblock") {
		jQuery("#can_unblock").hide();
		jQuery("#can_block").show();
		jQuery("#interest_main").show();
		jQuery("#send_messages").show();
		jQuery("#profile_add_fav").show();
		jQuery("#no_friends_at_all").show();
	}
}

// User action response
function return_profile_action(key, msg, _title){
	Boxy.alert("<b>" + msg + "</b><br /><br />", null, {});
	jQuery("> .f_right", "#row_" + key).remove();
	jQuery("#row_" + key).hide();
} 

$.fn.newsTicker = $.fn.newsticker = function(delay)
{
	delay = delay || 8000;
	initTicker = function(el)
	{
		$.newsticker.clear(el);
		el.items = $("li", el);
		// hide all items (except first one)
		el.items.not(":eq(0)").hide().end();
		// current item
		el.currentitem = 0;
		startTicker(el);
	};
	startTicker = function(el)
	{
		el.tickfn = setInterval(function() { doTick(el) }, delay)
	};
	doTick = function(el)
	{
		// don't run if paused
		if(el.pause) return;
		// pause until animation has finished
		$.newsticker.pause(el);
		// hide current item
		$(el.items[el.currentitem]).fadeOut("slow",
			function()
			{
				$(this).hide();
				// move to next item and show
				el.currentitem = ++el.currentitem % (el.items.size());
				$(el.items[el.currentitem]).fadeIn("slow",
					function()
					{
						$.newsticker.resume(el);
					}
				);
			}
		);
	};
	this.each(
		function()
		{
			if(this.nodeName.toLowerCase()!= "ul") return;
			initTicker(this);
		}
	)
	.addClass("newsticker")
	.hover(
		function()
		{
			// pause if hovered over
			$.newsticker.pause(this);
		},
		function()
		{
			// resume when not hovered over
			$.newsticker.resume(this);
		}
	);
	return this;
};


$.newsticker = $.newsTicker =
{
	pause: function(el)
	{
		(el.jquery ? el[0] : el).pause = true;
	},
	resume: function(el)
	{
		(el.jquery ? el[0] : el).pause = false;
	},
	clear: function(el)
	{
		el = (el.jquery ? el[0] : el);
		clearInterval(el.tickfn);
		el.tickfn = null;
		el.items = null;
		el.currentItem = null;
	}
}
