var iDOMLoaded = false;
var bDTrackInit = false;
var ocformAnc = false;
var str_counters_html = '';

function initCounters() { $("#footer .counters").html(str_counters_html); }

function makeRowsClickable() {
	var $allClickable = $(".clickable");
	$allClickable.each(function () {
		var $row = $(this);
		var $link = $row.find("a.clickTarget");
		if ($link) {
			var url = $link.attr("href");
			if (url) {
				$row
					.find("td:not(.end):not(.nonclickable)")
					.filter(function () { return $(this).find("a").length == 0 })
					.click(function () {
						document.location = url;
					});
			}
		}
	});
}

function enableToggleLinks(args) {
	args = args || {};
	args.updateTextOnly = args.updateTextOnly || false;
	
	var $allToggleLinks = $(".toggle");
	$allToggleLinks.each(function () {
		var $link = $(this);
		var $target = $($link.attr("data-toggle-target"));
		var $focus = $($link.attr("data-toggle-focus"));

		var updateLinkText = function () {
			$link.text($link.attr(($target.css("display") != "none") ? "data-toggle-collapse-text" : "data-toggle-expand-text"));
			if ($link.text() == "")
				$link.hide();
			else
				$link.show();
		};

		updateLinkText();
		if ($target && !args.updateTextOnly) {
			$link.click(function () {
				$target.toggle();
				updateLinkText();
				if ($focus)
					$focus.focus();
				return false;
			});
		}
	});
}

function enableWatermarks() {
	var $allWatermarked = $(".watermark");
	$allWatermarked.each(function () {
		var $textbox = $(this);
		if ($textbox) {
			var text = $textbox.attr("data-watermark-text");
			if (text) {
				$textbox.watermark(text, { color: "#aaa", left: 0, top: 2, fallback: false, minOpacity: 0 });
			}
		}
	});
}

function addHandlers() {
    //---------------------

    makeRowsClickable();
    enableToggleLinks();
    enableWatermarks();
    //----------------------

    $("#header .r fieldset input:not(.btn)").focus(function () {
        if (!this.oldValue) this.oldValue = this.value;
        if (this.oldValue == this.value) {
            this.value = "";
            $(this).addClass("clc");
        }
    });
    $("#header .r fieldset input:not(.btn)").blur(function () {
        if (this.value == "") {
            this.value = this.oldValue;
            $(this).removeClass("clc");
        }
    });

    //----------------------

    $(".col_tabs a").each(function () { if (!$(this).parent("li").hasClass("ui-tabs-selected") && this.hash && this.hash != "#") $(this.hash).hide(); });
    $(".col_tabs a").click(function () {
        if (this.hash && this.hash != "#") {
            var id = this.hash;
            var old_id = $(this).parent("li").siblings(".ui-tabs-selected").children("a")[0].hash;
            $(this).parent("li").siblings(".ui-tabs-selected").removeClass("ui-tabs-selected");
            $(this).parent("li").addClass("ui-tabs-selected");
            $(old_id).fadeOut(300, function () { $(id).fadeIn(300); })
        }
        return false;
    });

    $("#idxmainmenu > li").hover(
			function () { $(this).addClass("hover").children("table").show(); },
			function () { $(this).removeClass("hover").children("table").hide(); }
		);

    $(".col_best_list .best_item:not(.selected) .ct").hide();
    $(".col_best_list .best_item a.hd").click(function () {
        if (!$(this).parent(".best_item").hasClass("selected")) {
            $(".col_best_list .best_item.selected .ct").slideUp(500, function () { $(this).parent(".best_item").removeClass("selected"); });
            $(this).parent(".best_item").addClass("selected");
            $(this).siblings(".ct").slideDown(500);
        }
        return false;
    });

    $(".idx_cmenu td div.item").hover(
			function () { $(this).addClass("hover"); },
			function () { $(this).removeClass("hover"); }
		);
    $(".idx_cmenu .item").click(function () {
        window.location = $("h3 a", this).attr("href");
    });
    $(".conttopban td div.item").hover(
			function () { $(this).addClass("hover"); },
			function () { $(this).removeClass("hover"); }
		);

    $(".conttopban .item").click(function () {
        window.location = $("h3 a", this).attr("href");
    });

    //----------------------

    /* TrackBar */
    /*if ($("#DoubleTrack-2")[0]) {
    if ($("#DoubleTrack-2").parents(".cnt").is(":visible")) {
    dt_start();
    bDTrackInit = true;
    }
    }/**/

    /* Buble popup in form */
    if ($("#content .deposits .help_buble .icon")[0]) {
        $("#content .deposits .help_buble").hover(
		function () {
		    $(this).children(".buble").css("display", "block");
		    var r = getAbsolutePos(this);
		    var newtop = 0;
		    var newleft = 0;
		    if (window.XMLHttpRequest) {
		        newtop = r.y - $(this).children(".buble").attr("offsetHeight") + 16;
		        newleft = r.x - 288;
		    } else {
		        newtop = 0 - $(this).children(".buble").attr("offsetHeight") + 45;
		        newleft = 0 - 285;
		    }
		    $(this).children(".buble").css("top", newtop + "px");
		    $(this).children(".buble").css("left", newleft + "px");
		},
		function () {
		    $(this).children(".buble").css("display", "none");
		}
	);
    }


    /* Content rows hover */
    if ($("#content table tr")[0]) {
        $("#content table:not(.nohover) tr:not(.nohover)").hover(
		function () {
		    $(this).addClass("hover");
		},
		function () {
		    $(this).removeClass("hover");
		}
	);
    }

    /* Tabs on card pages */
    if ($("#content ul.card_tabs")[0]) {
        if (typeof (predef_cardTabsSel) != 'undefined') {
            $("#content ul.card_tabs").tabs({ selected: predef_cardTabsSel });
        } else {
            $("#content ul.card_tabs").tabs({ selected: 0 });
        }
    }
    /* Tabs on card pages */
    if ($("#content ul.inner_tabs")[0]) {
        $("#content ul.inner_tabs").tabs({ fx: { opacity: 'toggle' }, selected: 0 });
    }

    /* Filial list hover */
    if ($("#content .filial_map .filial_list p")[0]) {
        $("#content .filial_map .filial_list p").hover(
		function () {
		    $("#content .filial_map .filial_list p").removeClass("hover");
		    $(this).addClass("hover");
		    $("#content .filial_map .map img").attr("src", $(this).attr("src"));
		},
		function () {
		}
	);
    }


    /* Main menu */
    if ($("#mainmenu")[0]) {
        $("#openmenu").mouseover(function () { $(this).siblings("ul").show(); });
        $("#mainmenu").mouseleave(function () { $(this).children("ul").slideUp(); });

        $("#mainmenu > ul > li").hover(
		function () {
		    $(this).children("table").get(0).style.display = "block";
		    $(this).addClass("hover");
		},
		function () {
		    $(this).children("table").get(0).style.display = "none";
		    $(this).removeClass("hover");
		}
	);
    }

    /* Wizard Info buble (help) */
    var ibTmOt = false;
    if ($(".help .info")[0] && $(".help a")[0]) {
        $(".help a.help").mouseover(
		function () {
		    if (ibTmOt) clearTimeout(ibTmOt);
		    $(".help .info:visible").hide();
		    if (this.bubleHeight == undefined) {
		        $(this).siblings(".info").css("top", "-500px");
		        $(this).siblings(".info").show();
		        this.bubleHeight = $(this).siblings(".info").attr("offsetHeight");
		        $(this).siblings(".info").hide();
		    }
		    pos = getAbsolutePos(this);
		    $(this).siblings(".info").css("top", (pos.y - this.bubleHeight + 20) + "px");
		    $(this).siblings(".info").css("left", (pos.x - 75) + "px");
		    $(this).siblings(".info").show();
		}
		);
        $(".help a.help").click(function () { return false; });

        $(".help .info").mouseleave(
			function () {
			    ibTmOt = setTimeout(function () { $(".help .info:visible").hide(); }, 100);
			}
		);
        $(".help .info").mouseover(function () { clearTimeout(ibTmOt); });
    }
}

jQuery(document).ready(function () {
    iDOMLoaded = true;
    setTimeout("init()", 100);

    addHandlers();
});

function init() {
	if ($("#container h2 a:not(.small):not(.help):not(.priority-product-limiter)")[0]) {
		$("#container h2 a:not(.small):not(.help):not(.priority-product-limiter)").each(function () {
			var lnktxt = $(this).html();
			var idx = lnktxt.lastIndexOf(" ");
			lnktxt = lnktxt.substring(0, idx + 1) + "<nobr>" + lnktxt.substring(idx + 1) + "</nobr>";
			$(this).html(lnktxt);
			$(this).parent().append("<img src='http://f.sravni.ru/images/h2_arrow.gif' />");
		});

		$("#container h2 a:not(.small):not(.help):not(.priority-product-limiter)").hover(
				function () {
					$(this).queue("fx", []);
					$(this).children("nobr").children("img").animate({ marginLeft: "20px" }, 200);
				},
				function () {
					$(this).parent().queue("fx", []);
					$(this).children("nobr").children("img").animate({ marginLeft: "10px" }, 200);
				}
		);
	}
		if ($(".head2 a:not(.small):not(.help):not(.priority-product-limiter)")[0]) {
				$("#.head2 a:not(.small):not(.help):not(.priority-product-limiter)").append('<img src="http://f.sravni.ru/images/h2_arrow.gif" />');

				$(".head2 a:not(.small):not(.help):not(.priority-product-limiter)").hover(
				function () {
					$(this).queue("fx", []);
					$(this).children("img").animate({ marginLeft: "20px" }, 200);
				},
				function () {
					$(this).parent().queue("fx", []);
					$(this).children("img").animate({ marginLeft: "10px" }, 200);
				}
		);
	} /**/

	/* Red content banners on index page */
	if ($("#content .ban:not(.ins) input")[0]) {
		$("#content .ban input").hover(
			function () {
				this.className = "over";
				var pcn = this.parentNode.parentNode.className;
				$(this).parent().css("backgroundImage", "url('http://f.sravni.ru/images/cbb_" + pcn + "_over.jpg')");
			},
			function () {
				this.className = "";
				var pcn = this.parentNode.parentNode.className;
				$(this).parent().css("backgroundImage", "url('http://f.sravni.ru/images/cbb_" + pcn + ".jpg')");
			}
		);
	}


	/* Vote popup show */
	if ($("#content input.votebut")[0]) {
		$("#content input.votebut").click(
			function () {
				if ($("#votepopup").css("display") == "block" && $("#votepopup #curid").attr("value") == $(this).attr("id")) {
					$("#votepopup").css("display", "none");
				} else {
					$("#votepopup #curid").attr("value", $(this).attr("id"));
					var pos = getAbsolutePos(this);
					$("#votepopup").css("top", pos.y + "px");
					$("#votepopup").css("left", pos.x + "px");
					$("#votepopup").css("display", "block");
				}
				return false;
			}
		);
		if ($("#content .vote label input")[0]) {
			$("#content .vote input.but").attr("value", $("#content .vote label input:checked").attr("value"));
			$("#content .vote label input").change(
					function () {
						$("#content .vote input.but").attr("value", $(this).attr("value"));
					}
				);
			$("#content .vote label input").focus(
					function () {
						$("#content .vote input.but").attr("value", $(this).attr("value"));
					}
				);
		}
	}

	initCounters();
}

function getAbsolutePos(el) {
	var r = { x: el.offsetLeft, y: el.offsetTop };
	if (el.offsetParent) {
		var tmp = getAbsolutePos(el.offsetParent);
		r.x += tmp.x;
		r.y += tmp.y;
	}
	return r;
}

/**********************************************************/
/******************* VALIDATION ***************************/
/**********************************************************/

var validFieds = new Array();
function addFieldToValidator(fieldID, types) {
	validFieds[fieldID] = types;
}
function clearValidators() {
	validFieds = [];
}

function validate() {
	var is_valid = true;
	for (var fid in validFieds) {
		for (var t in validFieds[fid]) {
			hideError(fid);
			if (validFieds[fid][t] == "require" && $("#" + fid).attr("value").length == 0) {
				is_valid = false;
				showError(fid, "Поле обязательно для заполнения.");
				break;
			}
			if (validFieds[fid][t] == "email") {
				var reg = /[0-9a-z_]+@[0-9a-z_^.]+\.[a-z]{2,3}/i;
				if (!reg.test($("#" + fid).attr("value"))) {
					is_valid = false;
					showError(fid, "Не верный формат email.");
					break;
				}
			}

			if (validFieds[fid][t] == "date") {
				var reg = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/

				if (!reg.test($("#" + fid).attr("value"))) {
					is_valid = false;
					showError(fid, "Неверный формат даты.");
					break;
				}
			}

			if (validFieds[fid][t] == "number") {
				var reg = /^\d+$/

				if (!reg.test($("#" + fid).attr("value"))) {
					is_valid = false;
					showError(fid, "Неверный формат числа.");
					break;
				}
			}


		}
	}
	return is_valid;
}
function showError(fid, err) {
	var prnt = $("#" + fid).parent();

	prnt.addClass("err");
	if (prnt.children("dt")[0]) {
		prnt.children("dt:last").before("<p class='errmsg'>" + err + "</p>");
	} else prnt.append("<p class='errmsg'>" + err + "</p>");
}
function hideError(fid) {
	var prnt = $("#" + fid).parent();

	prnt.removeClass("err");
	prnt.children().remove("p.errmsg");
}

