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});
	
	$("#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({top: offset.top});
			}
		}
		else {
			target.remove();
		}
	});
	
	// Init actions for top site navigation
	main_nav_actions();
	search_actions("input.top_search_input", 1);
	
	// 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();
			}
		});
		
		if ($("#user_toolbar").length > 0) {
			$("#user_toolbar").css({left: ($("body > div.doc4:eq(0)").offset().left + (($.browser.msie && $.browser.version <= 6) ? 6 : 5) + "px"), visibility: "visible"});
		}
	}).triggerHandler("resize");
});

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_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=\"hide a_center {cat: '" + v + "'}\" id=\"b_comp_prod_" + v + "\"><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").remove().end().find("> div.top_off").remove().end().prepend(comp_tabs);
	// Replace old compare boxes
	$("#comp_ajax_box .bxd").find("> div").remove().end().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_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;
	var last_width = $("#user_toolbar_inner").width() - 5;
	$("#user_toolbar, #user_toolbar_inner").css({width: last_width + "px"});
	
	// Compact toolbar
	if ($.cookie("user_toolbar") == "off") {
		$("#user_toolbar").css({overflow: "hidden", width: "28px"});
		$("#toggle_user_toolbar span:first").html("&raquo;");
		$("#toggle_user_toolbar").addClass("imp");
	}
	
	// Set boxes widths
	$("#user_toolbar_slide > .toolbar_ajax_box").css("width", $("#user_toolbar_inner").width() + "px");
	
	// Init modal
	$("#custom_modal").css({opacity: 0.8, height: $(document).height() + "px"});
	
	// Hide modal layer and boxes
	$("#custom_modal, #user_toolbar a.i_close").click(function(){
		$("#user_toolbar_slide > .toolbar_ajax_box, #custom_modal").hide();
		$("#user_toolbar .left_toolbar a").removeClass("on");
		return false;
	});
	
	// Add actions on main left tabs
	$("#user_toolbar .left_toolbar a").click(function(){
		var jThis = $(this);
		
		// Tab is on - hide modal layer and boxes
		if (jThis.is(".on")) {
			$("#user_toolbar_slide > .toolbar_ajax_box").hide();
			$("#user_toolbar .left_toolbar li a").removeClass("on");
			$("#custom_modal").hide();
		}
		// Tab is off
		else {
			// Get tab position
			var index = $("#user_toolbar .left_toolbar li").index(jThis.closest("li"));
			// Return false if box doesn't exist for current tab
			if ($("#user_toolbar_slide > .toolbar_ajax_box:eq(" + index + ") .autobox li").length) {
				$("#user_toolbar_slide > .toolbar_ajax_box:eq(" + index + ") .bxd > span.light").hide();
			}
			
			// Hide all boxes
			$("#user_toolbar_slide > .toolbar_ajax_box").hide();
			// Show modal layer
			$("#custom_modal").show();
			// Mark as off all tabs
			$("#user_toolbar .left_toolbar li a").removeClass("on");
			// Mark as on current tab
			jThis.addClass("on");
			// Show box for current tab
			$("#user_toolbar_slide > .toolbar_ajax_box:eq(" + index + ")").show();
		}
		
		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;
		// Hide toolbar
		if ($("#user_toolbar").width() > 100) {
			// Set toolbar state in cookie
			$.cookie('user_toolbar', 'off', {path: '/', domain: DOMAIN_BASE});
			// Hide modal layer and boxes when toolbar is collapsing
			$("#user_toolbar_slide > .toolbar_ajax_box, #custom_modal").hide();
			$("#user_toolbar .left_toolbar a").removeClass("on");
			
			$("#user_toolbar").css({overflow: "hidden"});
			$("#user_toolbar").animate({width: "28px"}, 500, function(){
				$("#toggle_user_toolbar span:first").html("&raquo;");
				$("#toggle_user_toolbar").addClass("imp");
				animating = false;
			});
		}
		// Show toolbar
		else {
			// Set toolbar state in cookie
			$.cookie('user_toolbar', 'on', {path: '/', domain: DOMAIN_BASE});
			$("#toggle_user_toolbar").removeClass("imp");
			$("#user_toolbar").animate({width: last_width + "px"}, 500, function(){
				$("#user_toolbar").css({overflow: "visible"});
				$("#toggle_user_toolbar span:first").html("&laquo;");
				animating = false;
			});
		}
		return false;
	});
	
	// Init counters and layers
	refresh_comp_layer();
	refresh_view_layer();
	refresh_fav_layer();
	
	// On main tab click open last section
	$("#user_toolbar .left_toolbar a").click(function(){
		// Get tab section
		var section = $(this).metadata().section;
		// Get last section id
		var tab = $("#t_" + section + "_" + $.cookie(section + "_section") + " a");
		
		// 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");
		}
	});
	
	// Load data when subtab first opens and store subtab position in cookie
	$("#user_toolbar .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 a.med_arr_prev, #user_toolbar 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 a.med_arr_prev_off, #user_toolbar a.med_arr_next_off").live("click", function(){return false;});
	
	// Handle item delete
	$("#user_toolbar 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_slide > .toolbar_ajax_box").hide();
				$("#user_toolbar .left_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 a.request_delete_list").live("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_slide > .toolbar_ajax_box").hide();
					$("#user_toolbar .left_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 #######################################################
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);
	});
	
	// Append add to fav link
	$("#add2fav_cont").append("<a href=\"#\" id=\"add2fav\" class=\"gray\" rel=\"nofollow\">" + $("#add2fav_cont").metadata().text + "</a>");
	$("#add2fav").jFav();
}

// Handle top search actions #######################################################
function search_actions(target, focus){
	// Select search input
	var input = $(target);
	
	if (!input.length){return false;}
	
	if ((typeof(focus) == "undefined") || hasFocus) {
		focus = 0;
	}
	
	if (input.length) {
		// Default search text
		var txt = input.metadata().txt;
		var search_string = input.metadata().search_string;
		// Select closest parent form
		var par = input.closest("form");
		
		// 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);
		}
		
		// 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()) == "") {
				input.val(txt);
				input.css("color", "#AAAAAA");
			}
		});
		
		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;
			}
		});
	}
}

// Handle recent search layer #######################################################
function recent_search_actions(load_link, del_link){
	// Show recent search layer
	$(".btn_recent_search").click(function(){
		// Layer is hidden
		if ($("#saved_searches").css("visibility") == "hidden") {
			// Add loading class
			$("#autocomplete_prod").addClass("ac_loading");
			// Load layer content from remote
			$("#saved_searches").css("width", $(".btn_recent_search").closest("form").width() - 2 + "px").load(load_link, function(){
				// Remove loading class
				$("#autocomplete_prod").removeClass("ac_loading");
				
				var ul = $("ul", this);
				
				// Limit max height to 255px
				if (ul.height() > 255) {
					ul.height(255);
				}
				
				$(".btn_recent_search").addClass("btn_recent_search_on");
				$(this).css("visibility", "visible");
				
				// Clear recent searches
				$(".btn_recent_clear").click(function(){
					// Load empty message from remote
					$("#saved_searches").load(del_link, function(){});
					
					return false;
				});
			});
		}
		// Hide layer if visible
		else {
			$("#saved_searches").css("visibility", "hidden");
			$(".btn_recent_search").removeClass("btn_recent_search_on");
		}
	}).hover(function(){
		var jThis = $(this);
		if (jThis.is(".btn_recent_search_on")) {
			jThis.addClass("btn_recent_search_on_hover");
		}
		else {
			jThis.addClass("btn_recent_search_hover");
		}
	}, function(){
		$(this).removeClass("btn_recent_search_on_hover");
		$(this).removeClass("btn_recent_search_hover");
	});
	
	// Hide layer when you click outside
	$("body").click(function(e){
		if ($(e.target).attr("id") != "saved_searches") {
			$("#saved_searches").css("visibility", "hidden");
			$(".btn_recent_search").removeClass("btn_recent_search_on");
		}
	});
}

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.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.trigger("box.open");
				}
				else {
					jBox.trigger("box.focus");
				}
				jBox.show();
			}
			
			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).parents().get(2);
		var more_div = $(e.target).parents().get(0);
		
		$(more_div).prepend("<img src=\"" + PATH_STATIC + "/img/site/aloader.gif\" class=\"f_right\" />");
		
		$(par).load($(this).metadata().expand, function(){
			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;
	}
}