// easing
jQuery.extend(jQuery.easing, {
	swap1: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
		}
	});
	
	
(function( $ ) {
	$.widget( "ui.combobox", {
		_create: function() {
			var self = this,
				select = this.element.hide(),
				selected = select.children( ":selected" ),
				value = selected.val() ? selected.text() : "";
			var input = this.input = $( "<input>" )
				.addClass("text")
				.insertAfter( select )
				.val( value )
				.autocomplete({
					delay: 0,
					minLength: 0,
					source: function( request, response ) {
						var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
						response( select.children( "option" ).map(function() {
							var text = $( this ).text();
							if ( this.value && ( !request.term || matcher.test(text) ) )
								return {
									label: text.replace(
										new RegExp(
											"(?![^&;]+;)(?!<[^<>]*)(" +
											$.ui.autocomplete.escapeRegex(request.term) +
											")(?![^<>]*>)(?![^&;]+;)", "gi"
										), "<strong>$1</strong>" ),
									value: text,
									option: this
								};
						}) );
					},
					select: function( event, ui ) {
						ui.item.option.selected = true;
						self._trigger( "selected", event, {
							item: ui.item.option
						});
					},
					change: function( event, ui ) {
						if ( !ui.item ) {
							var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" ),
								valid = false;
							select.children( "option" ).each(function() {
								if ( $( this ).text().match( matcher ) ) {
									this.selected = valid = true;
									return false;
								}
							});
							if ( !valid ) {
								// remove invalid value, as it didn't match anything
								$( this ).val( "" );
								select.val( "" );
								input.data( "autocomplete" ).term = "";
								return false;
							}
						}
					}
				})
				.addClass( "ui-widget ui-widget-content ui-corner-left" );

			input.data( "autocomplete" )._renderItem = function( ul, item ) {
				return $( "<li></li>" )
					.data( "item.autocomplete", item )
					.append( "<a>" + item.label + "</a>" )
					.appendTo( ul );
			};

			this.button = $( "<i>&nbsp;</i>" )
				.addClass("b-combo")
				.attr( "tabIndex", -1 )
				.attr( "title", "Show All Items" )
				.insertAfter( input )
				.removeClass( "ui-corner-all" )
				.addClass( "ui-corner-right ui-button-icon" )
				.click(function() {
					// close if already visible
					if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
						input.autocomplete( "close" );
						return;
					}

					// pass empty string as value to search for, displaying all results
					input.autocomplete( "search", "" );
					input.focus();
				});
		},

		destroy: function() {
			this.input.remove();
			this.button.remove();
			this.element.show();
			$.Widget.prototype.destroy.call( this );
		}
	});
})( jQuery );


$(document).ready(function () {

    // text inputs hints
    
    $(".text_hint[value!=]")
		.each(function () { this.hint = this.value })
		.bind("focus", function () { if (this.hint == this.value) { $(this).attr("value", "").removeClass("text_hint").parents(".search-input:eq(0)").removeClass("search-input_hint") } })
		.bind("blur", function () { if (this.value == "") { $(this).attr("value", this.hint).addClass("text_hint").parents(".search-input:eq(0)").addClass("search-input_hint") } })

    layout()
    $(window).bind("load resize", function () { layout() })


    // nav
    $(".b-nav LI").hover(function () { $(this).addClass("hover") }, function () { $(this).removeClass("hover") })

    // side
    $(".b-side__toggle").click(function () {
        var par = $(this).closest(".b-body")
        var animTime = 300
        if (par.hasClass("b-body_wide")) {
            par
				.find(".b-side__i").animate({ "margin-left": 0 }, animTime, "swap1").end()
				.find(".b-section__i").animate({ "margin-left": 230 }, animTime, "swap1").end()
				.find(".b-side__toggle").animate({ "margin-right": -5 }, animTime, "swap1").end()
				.removeClass("b-body_wide")
        }
        else {
            par
				.find(".b-side__i").animate({ "margin-left": -213 }, animTime, "swap1").end()
				.find(".b-section__i").animate({ "margin-left": 17 }, animTime, "swap1").end()
				.find(".b-side__toggle").animate({ "margin-right": -12 }, animTime, "swap1", function () { par.addClass("b-body_wide") })
        }


        //.toggleClass("b-body_wide")
        return false
    }) // side toggle

    // datepicker
    $(".text_date[type=text]").removeClass("text_hint").datepicker({
        // http://jqueryui.com/demos/datepicker/
        showOn: "both",
        buttonImage: "/Content/images/ico-cal.png",
        buttonImageOnly: true,
        nextText: "&rarr;",
        prevText: "&larr;",
        currentText: "",
        dateFormat: 'dd.mm.yy',
        minDate: -100000
    });


    // grid opts
    $(".b-grid .tr-head2 .link-more").click(function () {
        $(this).closest(".b-grid").addClass("b-grid_opts")
        return false
    })
    $(".b-grid .tr-head3 .link-more").click(function () {
        $(this).closest(".b-grid").removeClass("b-grid_opts")
        return false
    })

    // grid strip
    $(".b-grid TABLE TBODY TR:odd").addClass("tr-odd")
    $(".b-grid TBODY TD").hover(
		function () { $(this).closest("TR").addClass("tr-hover") },
		function () { $(this).closest("TR").removeClass("tr-hover") })

    $(".b-grid TBODY .td-chk INPUT[type=checkbox]").bind("click change", function (e) {
        if ($(this).attr("checked")) {
            $(this).closest("TR").addClass("tr-checked")
        }
        else {
            $(this).closest("TR").removeClass("tr-checked")
        }
        e.stopPropagation()
    })
    $(".b-grid TBODY TD").click(function () {
        var chk = $(this).closest("TR").find(".td-chk INPUT")
        if (chk.attr("checked")) {
            chk.attr("checked", "")
            $(this).closest("TR").removeClass("tr-checked")
        }
        else {
            chk.attr("checked", "checked")
            $(this).closest("TR").addClass("tr-checked")
        }
    })


    // idrop
    $(".b-idrop").hover(
		function () { $(this).closest(".b-idrop").find("UL").show() },
		function () { $(this).closest(".b-idrop").find("UL").hide() })
    $(".b-idrop .link-drop").click(function () {
        $(this).closest(".b-idrop").find("UL").toggle()
        return false
    })
    $(".b-idrop").click(function (e) {
        e.stopPropagation()
    })
    $(".b-idrop LI A").click(function () {
        $(this)
			.closest("LI").addClass("cur")
				.siblings().removeClass("cur").end()
				.end()
			.closest(".b-idrop")
				.find("UL").hide()
        return false
    })
    $(document).bind("click", function () {
        $(".b-idrop UL").hide()
    })


    // tabs	// class=".js-tabs .js-tabs_xxx" where xxx is tabs class // qty & order should be equal
    $(".js-tabs LI").click(function (e) {
        var t = $(this)
        t.addClass("cur").siblings(".cur").removeClass("cur")
        $("." + t.closest(".js-tabs").get(0).className.split("js-tabs_")[1].split(" ")[0]).hide().eq(t.prevAll("LI").length).show()
        layout()
        return false
    }).filter(".cur").removeClass("cur").click()


    // autocomplete // http://jqueryui.com/demos/autocomplete/
    var availableTags = [
			"ActionScript",
			"AppleScript",
			"Asp",
			"BASIC",
			"C",
			"C++",
			"Clojure",
			"COBOL",
			"ColdFusion",
			"Erlang",
			"Fortran",
			"Groovy",
			"Haskell",
			"Java",
			"JavaScript",
			"Lisp",
			"Perl",
			"PHP",
			"Python",
			"Ruby",
			"Scala",
			"Scheme"
		];
    $("INPUT[type=text].text_auto").autocomplete({
        source: availableTags
    });

    /*	
    $(".text_auto + .b-lookup").click(function(){
    var input = $(this).prev()
    if ( input.autocomplete( "widget" ).is( ":visible" ) ) {
    input.autocomplete( "close" );
    return;
    }
    input.autocomplete( "search", "" );
    input.focus();
    })
    */

    if (!$.browser.msie) {
        $(".sel-combo").combobox();
    }



    // popup
    $(".b-pop").dialog({
        modal: true,
        autoOpen: false,
        width: 800
    });

    $(".b-lookup").click(function () {
        $("#pop-lookup").dialog("open");
        return false
    })


    // popup button cancel
    $("body").delegate(".ui-dialog .b-toolbar .t9, .ui-dialog .b-pop__close", "click", function () {
        $(this).closest(".b-pop").dialog("close");
        return false
    })

    // popup button select 
    $("body").delegate(".ui-dialog .b-toolbar .t8", "click", function () {
        var s = ""
        $(this).closest(".b-pop").find(".b-grid TR:has(TD)").each(function (index) {
            if ($(this).hasClass("tr-checked")) { s = s + " " + index }
        })
        if (s) {
            alert("result:" + s)
            $(this).closest(".b-pop").dialog("close");
        }
        else {
            alert("empty")
        }
        return false
    })


});

function layout(){
	
	$(".b-side__i, .b-section__i").css({height:"auto"})
	
	var wh = $(window).height() - $(".b-header").height() - $(".b-footer").height()
	var bh = $(".b-body").height()
	var sih = $(".b-side__i").height()
	var seh = $(".b-section__i").height()
	
	bh < wh
		? $(".b-side__i, .b-section__i").height(wh - 66)
		: sih < seh
			? $(".b-side__i").height(seh)
			: $(".b-section__i").height(sih)
			
/*
	$(".b-combo").each(function(){
		if ($(this).prev().hasClass("ui-autocomplete-input")) {
			$(this).css({marginTop: $(this).css(marginTop) + $(this).offset().top - $(this).prev().offset().top })
		}
	})
*/

}
