function selectItem(li) {
	if (li.extra) {
		//alert("That's '" + li.extra[0] + "' you picked.")
	}
}
function formatItem(row) {
	return row[0] + "<br><i>" + row[1] + "</i>";
}
$(document).ready(function () {
    //show and hide tr
    $("div.info").hide();
    $(".header").click(function () {
        $(this).parent().next().find("div.info").slideToggle(100);
        if (!$("img", this).attr("src").match("hide")) {
            $("img", this).attr("src", "/ui/images/hide.expand.png");
        } else {
            $("img", this).attr("src", "/ui/images/show.expand.png");
        }
        return false;
    });

    //show and hide list	
    $(".sf-menu .current ul").hide();
    $(".sf-menu .current").click(function () {
        $(".sf-menu .current ul").show();
        return false;
    });

    //show and hide layer	
    $(".popupTip,.popupSave").hide();
    $(".popupTip a.close").click(function () {
        $(".popupTip").hide();
        return false;
    });
    $("li.tip a").click(function () {
        $(".popupTip").show();
        $(".popupSave").hide();
        return false;
    });
    $(".popupSave a.close").click(function () {
        $(".popupSave").hide();
        return false;
    });
    $("#save-comparison-link").click(function () {
        $(".popupSave").show();
        $(".popupTip").hide();
        return false;
    });

    var lc = {
        init: function () {
            $("td:last-child").addClass("last-child");
        }
    };
    if (navigator.userAgent.match(/MSIE\s[7|6|5]/)) {
        lc.init();
    }

    var tableFix = {
        init: function () {
            this.wideTable();
        },
        wideTable: function () {
            var t = $("table"), i, j, th, temp, am, store;
            for (i = 0; i < t.length; i += 1) {
                if (t[i].offsetWidth > 732) {
                    th = t[i].getElementsByTagName("th");
                    for (j = 0; j < th.length; j += 1) {
                        if (th[j].innerHTML.match(/(programmet|gymnasiet|gymnasium|utbildningen|[gG]ymnasiet,|tekniker)$/)) {
                            temp = th[j].innerHTML.toString().replace(/(programmet|gymnasiet|gymnasium|utbildningen|[gG]ymnasiet,|tekniker)$/, "-<br />" + "$1");
                            th[j].innerHTML = temp;
                        }
                    }

                    if (t[i].offsetWidth > 732) {
                        a = t[i].getElementsByTagName("a");

                        for (i = 0; i < a.length; i += 1) {
                            if (a[i].innerHTML.match(/(\/)/g)) {
                                store = a[i].innerHTML.toString().match(/http:\/{2}/) ? a[i].innerHTML.toString().match(/http:\/{2}/) : "";
                                temp = a[i].innerHTML.toString().replace(/http:\/{2}/, "").match(/([\w_\.]+)/g).toString().replace(/,/g, "/<br />");

                                a[i].innerHTML = store + temp;
                            }
                        }
                    }
                }
            }
        }
    };
    tableFix.init();

    /*var fourCheckBoxes = {
    init: function() {
    var cbCounter = document.getElementById("cbCounter");
    if (cbCounter) {
    $("#content input[type=checkbox]").click(fourCheckBoxes.check);

    cbCounter.value = $("#content input[type=checkbox]:checked").length;

    if (parseInt(cbCounter.value) >= 4) {
    fourCheckBoxes.dis();
    }
    }
    },
    check: function() {
    var cbCounter = document.getElementById("cbCounter");

    if (this.checked) {
    cbCounter.value = parseInt(cbCounter.value) + 1;
    //fourCheckBoxes.addSelection(this.value);
    } else if (!this.checked) {
    cbCounter.value = parseInt(cbCounter.value) - 1;
    }

    if (this.checked && parseInt(cbCounter.value) >= 4) {
    fourCheckBoxes.dis();
    } else {
    fourCheckBoxes.act();
    }
    },
    dis: function() {
    var cbs = $("#content input[type=checkbox]:not(:checked)"), i;

    for (i = 0; i < cbs.length; i += 1) {
    cbs[i].disabled = true;
    }
    },
    act: function() {
    var cbs = $("#content input[type=checkbox]:disabled"), i;

    for (i = 0; i < cbs.length; i += 1) {
    cbs[i].disabled = false;
    }
    },
    //        addSelection: function(cbValue) {
    //            $.ajax({
    //                type: "POST",
    //                url: "/UI/Pages/ProgramList.aspx/AddSelection",
    //                data: '{"cbValue":"' + cbValue + '"}',
    //                contentType: "application/json; charset=utf-8",
    //                dataType: "json",
    //                success: function(msg) {
    //                    //$("#cbCounter").text(msg.d);
    //                }
    //            });
    //        }
    };
    fourCheckBoxes.init();*/


    var apu = {
        init: function () {
            this.al = $("a.ajaxPopUp").click(apu.pu);
        },
        pu: function (evt) {

            apu.cb(this.toString());

            evt.preventDefault();
        },
        cb: function (href) {
            apu.ovly();
            apu.pop(href);
        },
        ovly: function () {
            var o, sel, i, temp;
            o = $("<div>").attr("id", "ovly").attr("style", "width: 100%; position: absolute; top: 0; left: 0; background: #000; opacity: .5; z-index: 10000;").appendTo("body");

            o = document.getElementById("ovly");
            o.style.height = "100%";

            if (navigator.userAgent.match(/MSIE\s\d+/)) {
                o.style.filter = "alpha(opacity=50)";

                apu.repSel = [];

                if (navigator.userAgent.match(/MSIE\s[6]/)) {
                    sel = $("select");

                    for (i = sel.length - 1; i > -1; i -= 1) {

                        temp = document.createElement("input");
                        temp.style.display = "block";
                        temp.className = "isReplacedSelect";

                        apu.repSel.push([temp, sel[i]]);

                        sel[i].parentNode.replaceChild(temp, sel[i]);
                    }
                }
            }

            if (o.offsetHeight < document.body.offsetHeight) {
                o.style.height = parseInt(document.body.offsetHeight + 20, 10) + "px";
            }

        },
        pop: function (href) {
            var close, ca, ap, h;
            $("<div>").attr("id", "ajaxPopUp").attr("style", "position: fixed; top: 15%; left: 30%; background: #fff; padding: 0; display: block; width: 40%; height: 50%; z-index: 20000; overflow: auto; padding: 40px;").appendTo("body");

            if (navigator.userAgent.match(/MSIE\s[6]/)) {

                document.getElementById("ajaxPopUp").style.position = "absolute";
                document.getElementById("ajaxPopUp").style.top = (parseInt(document.documentElement.scrollTop, 10) + 20) + "px";
                document.getElementById("ajaxPopUp").style.height = "300px";
                document.getElementById("ajaxPopUp").style.overflow = "scroll";
            }

            $("#ajaxPopUp").css("border", "solid 10px #ccc");

            $("#ajaxPopUp").load(href + " #content .article", apu.insertClose);
        },
        insertClose: function () {
            $("#ajaxPopUp .article").prepend("<a href='#' class='closeAjaxPopUp' style='font-size: larger; float: right;'>St&auml;ng</a>");

            $("#ajaxPopUp .article").append("<a href='#' class='closeAjaxPopUp' style='font-size: larger; float: right; padding-bottom: 30px;'>St&auml;ng</a>");

            $("#ajaxPopUp .article .closeAjaxPopUp").click(apu.closePop);
        },
        closePop: function (evt) {
            var i;
            $("#ajaxPopUp").remove();
            $("#ovly").remove();

            if (apu.repSel) {
                for (i = 0; i < apu.repSel.length; i += 1) {
                    apu.repSel[i][0].parentNode.replaceChild(apu.repSel[i][1], apu.repSel[i][0]);
                }
            }

            evt.preventDefault();
        }
    };
    apu.init();

    //autocomplete, needes autocomplete.js
    //$("#idCounty").autocomplete("/ui/services/listmunicipalities.aspx", { minChars:2, matchSubset:1, matchContains:1, cacheLength:10, onItemSelect:selectItem, formatItem:formatItem, selectOnly:1 });
    //$("#idSchool").autocomplete("/ui/services/listschools.aspx", { minChars: 2, matchSubset: 1, matchContains: 1, cacheLength: 10, onItemSelect: selectItem, formatItem: formatItem, selectOnly: 1 });

    // checkboxes
    //    checkCheck()
    //    $(".checkBox input[type=checkbox]").click(checkCheck); 

    // disable input if nothing is chosen from select   
    checkSelect();
    $(".search select").change(checkSelect);

    $("th[title]").css('cursor', 'pointer');
    $("th[title]").click(function () {
//        var tt = $(this).data("tooltip");
//        if (tt.isShown()) {
//            tt.hide();
//        }else {
            tt.show();
//        }
    });

    $("th[title]").tooltip({
        delay: 0,
        position: 'top right'
    }).dynamic();

    $("h3[title]").css('cursor', 'pointer');
    $("h3[title]").click(function () {
        var tt = $(this).data("tooltip");
//        if (tt.isShown()) {
//            tt.hide();
//        } else {
            tt.show();
//        }
    });
    
    $("h3[title]").tooltip({
        delay: 0,
        position: 'top center'
    }).dynamic();

    createDropDown();

    $('#gk-front-municipality-wrapper input.field').focus(function () {
        if ($(this).val() == "Kommun") {
            $(this).val("");
        }
    });

    $('#gk-front-municipality-wrapper input.field').blur(function () {
        if ($(this).val() == "") {
            $(this).val("Kommun");
        }
    });

    $('#gk-front-school-wrapper input.field').focus(function () {
        if ($(this).val() == "Skolans namn") {
            $(this).val("");
        }
    });

    $('#gk-front-school-wrapper input.field').blur(function () {
        if ($(this).val() == "") {
            $(this).val("Skolans namn");
        }
    });
});
/*
function checkCheck(){
    var n = $(".checkBox input:checked").length;
      $("span.textSchool").text("Du har valt " + n + (n <= 1 ? " skola. " : " skolor. "));
      $("span.textProgram").text("Du har valt " + n + " program. ");
    if (n >1 && n <=4) {
        $(".btn2").show();
    }
    else {
        $(".btn2").hide();
    }   
}
*/
function checkSelect(){
    if ($(".search select").val() !== "") {
        $(".search input").removeAttr('disabled');
        //$(".search input.field").removeClass("disabled");
    } else {
        $(".search input").attr("disabled", "disabled");
        $(".search input").val("");
        //$(".search input.field").addClass("disabled");
    }
}

function doSearch(e, button) {
    if (window.event && window.event.keyCode == 13 || e && e.keyCode == 13) {
        document.getElementById(button).click();
        return false;
    }

    return true;
}

function createDropDown() {
    var source = $("#gk-front-programs-dropdown-wrapper select");
    var selected = source.find("option[selected='selected']");  // get selected <option>
    //var selected = $("option[selected='selected']");  // get selected <option>
    var options = $("option", source);  // get all <option> elements
    // create <dl> and <dt> with selected value inside it
    $("#gk-front-programs-dropdown-wrapper").append('<dl id="target" class="dropdown"></dl>');
    $("#target").append('<dt><a href="#">' + selected.text() +
        '<span class="value">' + selected.val() +
        '</span></a></dt>');
    $("#target").append('<dd><ul></ul></dd>');
    // iterate through all the <option> elements and create UL
    options.each(function () {
        $("#target dd ul").append('<li><a href="#">' +
            $(this).text() + '<span class="value">' +
            $(this).val() + '</span></a></li>');
    });

    $(".dropdown dd ul li a").click(function () {
        var text = $(this).html();
        $(".dropdown dt a").html(text);
        $(".dropdown dd ul").hide();
        var val = $(this).find("span.value").html();
        source.val(val);
    });

    $(".dropdown dt a").click(function () {
        $(".dropdown dd ul").toggle();
    });
    
    $(document).bind('click', function (e) {
        var $clicked = $(e.target);
        if (!$clicked.parents().hasClass("dropdown"))
            $(".dropdown dd ul").hide();
    });
}

