/// <reference path="jquery-1.3.2-vsdoc.js"/>

/*	sIFR v2.0.7
Copyright 2004 - 2008 Mark Wubben and Mike Davidson. Prior contributions by Shaun Inman and Tomas Jogin.
	
This software is licensed under the CC-GNU LGPL <http://creativecommons.org/licenses/LGPL/2.1/>
*/

var sifrSwfH2 = "javascripts/vesta.swf";

// Since IE doesn't support indexOf in arrays we put these values in a string instead. All languages shall be followed by a pipe (|).
var nonLatinLanguages = "ab|am|ar|as|av|ba|be|bg|bh|bn|bo|ce|cr|cu|cv|dz|ee|el|fa|gu|ha|he|hi|hy|ii|iu|ja|ka|kk|km|kn|ko|ks|kv|ky|lo|lu|mk|ml|mn|mr|ne|oj|or|os|pa|pi|ps|ru|sa|sd|si|sr|ta|te|tg|th|tt|ug|uk|uz|yi|za|zh|";

if (document.documentElement.lang.length > 0 && nonLatinLanguages.indexOf(document.documentElement.lang + "|") >= 0) {
    sifrSwfH2 = "";
}

if (sifrSwfH2 != "") {
    var hasFlash = function() { var a = 6; if (navigator.appVersion.indexOf("MSIE") != -1 && navigator.appVersion.indexOf("Windows") > -1) { document.write('<script language="VBScript"\> \non error resume next \nhasFlash = (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash." & ' + a + '))) \n</script\> \n'); if (window.hasFlash != null) return window.hasFlash } if (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"] && navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin) { var b = (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description; return parseInt(b.substr(b.indexOf(".") - 2, 2), 10) >= a } return false } (); String.prototype.normalize = function() { return this.replace(/\s+/g, " ") }; if (Array.prototype.push == null) { Array.prototype.push = function() { var i = 0, a = this.length, b = arguments.length; while (i < b) { this[a++] = arguments[i++] } return this.length } } if (!Function.prototype.apply) { Function.prototype.apply = function(a, b) { var c = []; var d, e; if (!a) a = window; if (!b) b = []; for (var i = 0; i < b.length; i++) { c[i] = "b[" + i + "]" } e = "a.__applyTemp__(" + c.join(",") + ");"; a.__applyTemp__ = this; d = eval(e); a.__applyTemp__ = null; return d } } function named(a) { return new named.Arguments(a) } named.Arguments = function(a) { this.oArgs = a }; named.Arguments.prototype.constructor = named.Arguments; named.extract = function(a, b) { var c, d; var i = a.length; while (i--) { d = a[i]; if (d != null && d.constructor != null && d.constructor == named.Arguments) { c = a[i].oArgs; break } } if (c == null) return; for (e in c) if (b[e] != null) b[e](c[e]); return }; var parseSelector = function() { var a = /^([^#.>`]*)(#|\.|\>|\`)(.+)$/; function r(s, t) { var u = s.split(/\s*\,\s*/); var v = []; for (var i = 0; i < u.length; i++) v = v.concat(b(u[i], t)); return v } function b(c, d, e) { c = c.normalize().replace(" ", "`"); var f = c.match(a); var g, h, i, j, k, n; var l = []; if (f == null) f = [c, c]; if (f[1] == "") f[1] = "*"; if (e == null) e = "`"; if (d == null) d = document; switch (f[2]) { case "#": k = f[3].match(a); if (k == null) k = [null, f[3]]; g = document.getElementById(k[1]); if (g == null || (f[1] != "*" && !o(g, f[1]))) return l; if (k.length == 2) { l.push(g); return l } return b(k[3], g, k[2]); case ".": if (e != ">") h = m(d, f[1]); else h = d.childNodes; for (i = 0, n = h.length; i < n; i++) { g = h[i]; if (g.nodeType != 1) continue; k = f[3].match(a); if (k != null) { if (g.className == null || g.className.match("(\\s|^)" + k[1] + "(\\s|$)") == null) continue; j = b(k[3], g, k[2]); l = l.concat(j) } else if (g.className != null && g.className.match("(\\s|^)" + f[3] + "(\\s|$)") != null) l.push(g) } return l; case ">": if (e != ">") h = m(d, f[1]); else h = d.childNodes; for (i = 0, n = h.length; i < n; i++) { g = h[i]; if (g.nodeType != 1) continue; if (!o(g, f[1])) continue; j = b(f[3], g, ">"); l = l.concat(j) } return l; case "`": h = m(d, f[1]); for (i = 0, n = h.length; i < n; i++) { g = h[i]; j = b(f[3], g, "`"); l = l.concat(j) } return l; default: if (e != ">") h = m(d, f[1]); else h = d.childNodes; for (i = 0, n = h.length; i < n; i++) { g = h[i]; if (g.nodeType != 1) continue; if (!o(g, f[1])) continue; l.push(g) } return l } } function m(d, o) { if (o == "*" && d.all != null) return d.all; return d.getElementsByTagName(o) } function o(p, q) { return q == "*" ? true : p.nodeName.toLowerCase().replace("html:", "") == q.toLowerCase() } return r } (); var sIFR = function() { var a = "http://www.w3.org/1999/xhtml"; var b = false; var c = false; var d; var ah = []; var al = document; var ak = al.documentElement; var am = window; var au = al.addEventListener; var av = am.addEventListener; var f = function() { var g = navigator.userAgent.toLowerCase(); var f = { a: g.indexOf("applewebkit") > -1, b: g.indexOf("safari") > -1, c: navigator.product != null && navigator.product.toLowerCase().indexOf("konqueror") > -1, d: g.indexOf("opera") > -1, e: al.contentType != null && al.contentType.indexOf("xml") > -1, f: true, g: true, h: null, i: null, j: null, k: null }; f.l = f.a || f.c; f.m = !f.a && navigator.product != null && navigator.product.toLowerCase() == "gecko"; if (f.m && g.match(/.*gecko\/(\d{8}).*/)) f.j = new Number(g.match(/.*gecko\/(\d{8}).*/)[1]); f.n = g.indexOf("msie") > -1 && !f.d && !f.l && !f.m; f.o = f.n && g.match(/.*mac.*/) != null; if (f.d && g.match(/.*opera(\s|\/)(\d+\.\d+)/)) f.i = new Number(g.match(/.*opera(\s|\/)(\d+\.\d+)/)[2]); if (f.n || (f.d && f.i < 7.6)) f.g = false; if (f.a && g.match(/.*applewebkit\/(\d+).*/)) f.k = new Number(g.match(/.*applewebkit\/(\d+).*/)[1]); if (am.hasFlash && (!f.n || f.o)) { var aj = (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description; f.h = parseInt(aj.substr(aj.indexOf(".") - 2, 2), 10) } if (g.match(/.*(windows|mac).*/) == null || f.o || f.c || (f.d && (g.match(/.*mac.*/) != null || f.i < 7.6)) || (f.b && f.h < 7) || (!f.b && f.a && f.k < 312) || (f.m && f.j < 20020523)) f.f = false; if (!f.o && !f.m && al.createElementNS) try { al.createElementNS(a, "i").innerHTML = "" } catch (e) { f.e = true } f.p = f.c || (f.a && f.k < 312); return f } (); function at() { return { bIsWebKit: f.a, bIsSafari: f.b, bIsKonq: f.c, bIsOpera: f.d, bIsXML: f.e, bHasTransparencySupport: f.f, bUseDOM: f.g, nFlashVersion: f.h, nOperaVersion: f.i, nGeckoBuildDate: f.j, nWebKitVersion: f.k, bIsKHTML: f.l, bIsGecko: f.m, bIsIE: f.n, bIsIEMac: f.o, bUseInnerHTMLHack: f.p} } if (am.hasFlash == false || !al.getElementsByTagName || !al.getElementById || (f.e && (f.p || f.n))) return { UA: at() }; function af(e) { if ((!k.bAutoInit && (am.event || e) != null) || !l(e)) return; b = true; for (var i = 0, h = ah.length; i < h; i++) j.apply(null, ah[i]); ah = [] } var k = af; function l(e) { if (c == false || k.bIsDisabled == true || ((f.e && f.m || f.l) && e == null && b == false) || al.getElementsByTagName("body").length == 0) return false; return true } function m(n) { if (f.n) return n.replace(new RegExp("%\d{0}", "g"), "%25"); return n.replace(new RegExp("%(?!\d)", "g"), "%25") } function as(p, q) { return q == "*" ? true : p.nodeName.toLowerCase().replace("html:", "") == q.toLowerCase() } function o(p, q, r, s, t) { var u = ""; var v = p.firstChild; var w, x, y, z; if (s == null) s = 0; if (t == null) t = ""; while (v) { if (v.nodeType == 3) { z = v.nodeValue.replace("<", "&lt;"); switch (r) { case "lower": u += z.toLowerCase(); break; case "upper": u += z.toUpperCase(); break; default: u += z } } else if (v.nodeType == 1) { if (as(v, "a") && !v.getAttribute("href") == false) { if (v.getAttribute("target")) t += "&sifr_url_" + s + "_target=" + v.getAttribute("target"); t += "&sifr_url_" + s + "=" + m(v.getAttribute("href")).replace(/&/g, "%26"); u += '<a href="asfunction:_root.launchURL,' + s + '">'; s++ } else if (as(v, "br")) u += "<br/>"; if (v.hasChildNodes()) { y = o(v, null, r, s, t); u += y.u; s = y.s; t = y.t } if (as(v, "a")) u += "</a>" } w = v; v = v.nextSibling; if (q != null) { x = w.parentNode.removeChild(w); q.appendChild(x) } } return { "u": u, "s": s, "t": t} } function A(B) { if (al.createElementNS && f.g) return al.createElementNS(a, B); return al.createElement(B) } function C(D, E, z) { var p = A("param"); p.setAttribute("name", E); p.setAttribute("value", z); D.appendChild(p) } function F(p, G) { var H = p.className; if (H == null) H = G; else H = H.normalize() + (H == "" ? "" : " ") + G; p.className = H } function aq(ar) { var a = ak; if (k.bHideBrowserText == false) a = al.getElementsByTagName("body")[0]; if ((k.bHideBrowserText == false || ar) && a) if (a.className == null || a.className.match(/\bsIFR\-hasFlash\b/) == null) F(a, "sIFR-hasFlash") } function j(I, J, K, L, M, N, O, P, Q, R, S, r, T) { if (!l()) return ah.push(arguments); aq(); named.extract(arguments, { sSelector: function(ap) { I = ap }, sFlashSrc: function(ap) { J = ap }, sColor: function(ap) { K = ap }, sLinkColor: function(ap) { L = ap }, sHoverColor: function(ap) { M = ap }, sBgColor: function(ap) { N = ap }, nPaddingTop: function(ap) { O = ap }, nPaddingRight: function(ap) { P = ap }, nPaddingBottom: function(ap) { Q = ap }, nPaddingLeft: function(ap) { R = ap }, sFlashVars: function(ap) { S = ap }, sCase: function(ap) { r = ap }, sWmode: function(ap) { T = ap } }); var U = parseSelector(I); if (U.length == 0) return false; if (S != null) S = "&" + S.normalize(); else S = ""; if (K != null) S += "&textcolor=" + K; if (M != null) S += "&hovercolor=" + M; if (M != null || L != null) S += "&linkcolor=" + (L || K); if (O == null) O = 0; if (P == null) P = 0; if (Q == null) Q = 0; if (R == null) R = 0; if (N == null) N = "#FFFFFF"; if (T == "transparent") if (!f.f) T = "opaque"; else N = "transparent"; if (T == null) T = ""; var p, V, W, X, Y, Z, aa, ab, ac; var ad = null; for (var i = 0, h = U.length; i < h; i++) { p = U[i]; if (p.className != null && p.className.match(/\bsIFR\-replaced\b/) != null) continue; V = p.offsetWidth - R - P; W = p.offsetHeight - O - Q; aa = A("span"); aa.className = "sIFR-alternate"; ac = o(p, aa, r); Z = "txt=" + m(ac.u).replace(/\+/g, "%2B").replace(/&/g, "%26").replace(/\"/g, "%22").normalize() + S + "&w=" + V + "&h=" + W + ac.t; F(p, "sIFR-replaced"); if (ad == null || !f.g) { if (!f.g) { if (!f.n) p.innerHTML = ['<embed class="sIFR-flash" type="application/x-shockwave-flash" src="', J, '" quality="best" wmode="', T, '" bgcolor="', N, '" flashvars="', Z, '" width="', V, '" height="', W, '" sifr="true"></embed>'].join(""); else p.innerHTML = ['<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" sifr="true" width="', V, '" height="', W, '" class="sIFR-flash"><param name="movie" value="', J, '"></param><param name="flashvars" value="', Z, '"></param><param name="quality" value="best"></param><param name="wmode" value="', T, '"></param><param name="bgcolor" value="', N, '"></param> </object>'].join('') } else { if (f.d) { ab = A("object"); ab.setAttribute("data", J); C(ab, "quality", "best"); C(ab, "wmode", T); C(ab, "bgcolor", N) } else { ab = A("embed"); ab.setAttribute("src", J); ab.setAttribute("quality", "best"); ab.setAttribute("flashvars", Z); ab.setAttribute("wmode", T); ab.setAttribute("bgcolor", N) } ab.setAttribute("sifr", "true"); ab.setAttribute("type", "application/x-shockwave-flash"); ab.className = "sIFR-flash"; if (!f.l || !f.e) ad = ab.cloneNode(true) } } else ab = ad.cloneNode(true); if (f.g) { if (f.d) C(ab, "flashvars", Z); else ab.setAttribute("flashvars", Z); ab.setAttribute("width", V); ab.setAttribute("height", W); ab.style.width = V + "px"; ab.style.height = W + "px"; p.appendChild(ab) } p.appendChild(aa); if (f.p) p.innerHTML += "" } if (f.n && k.bFixFragIdBug) setTimeout(function() { al.title = d }, 0) } function ai() { d = al.title } function ae() { if (k.bIsDisabled == true) return; c = true; if (k.bHideBrowserText) aq(true); if (am.attachEvent) am.attachEvent("onload", af); else if (!f.c && (al.addEventListener || am.addEventListener)) { if (f.a && f.k >= 132 && am.addEventListener) am.addEventListener("load", function() { setTimeout("sIFR({})", 1) }, false); else { if (al.addEventListener) al.addEventListener("load", af, false); if (am.addEventListener) am.addEventListener("load", af, false) } } else if (typeof am.onload == "function") { var ag = am.onload; am.onload = function() { ag(); af() } } else am.onload = af; if (!f.n || am.location.hash == "") k.bFixFragIdBug = false; else ai() } k.UA = at(); k.bAutoInit = true; k.bFixFragIdBug = true; k.replaceElement = j; k.updateDocumentTitle = ai; k.appendToClassName = F; k.setup = ae; k.debug = function() { aq(true) }; k.debug.replaceNow = function() { ae(); k() }; k.bIsDisabled = false; k.bHideBrowserText = true; return k } ();

    if (typeof sIFR == "function" && !sIFR.UA.bIsIEMac && (!sIFR.UA.bIsWebKit || sIFR.UA.nWebKitVersion >= 100)) {
        sIFR.setup();
        var template = named({ sFlashSrc: sifrSwfH2, sColor: sifrColorH2, sWmode: "transparent" });
        sIFR.replaceElement("#contentandnav h2", template);
    };
}

function showWindow(strURL, strTitle, iWidth, iHeight) {
    var sw = window.screen.availWidth;
    var sh = window.screen.availHeight;
    var xsize = screen.width
    var ysize = screen.height
    var xpos = (xsize - iWidth) / 2
    var ypos = (ysize - iHeight) / 2
    var win = window.open(strURL, null, "height=" + iHeight + ",width=" + iWidth + ",status=no,toolbar=no,menubar=no,location=no,screenX=" + xpos + ",screenY=" + ypos + ",top=" + ypos + ",left=" + xpos);
}


function pk_suggest(inputString) {
    if (inputString.length == 0) {
        $('#suggestions').fadeOut();
    } else {
        $('#pk_searchbox').addClass('load');
        $.post("index.php?key=produktkatalog&lang=de&typ=ajax", { queryString: "" + inputString + "" }, function(data) {
            if (data.length > 0) {
                $('#suggestions').fadeIn();
                $('#suggestionsList').html(data);
                $('#pk_searchbox').removeClass('load');
            }
        });
    }
}

function pk_fill(thisValue) {
    $('#pk_searchbox').val(thisValue);
    setTimeout("$('#suggestions').fadeOut();", 600);
}


$(document).ready(function() {
    $(function() {

        $("h4.jqopen").click(function(event) {

            if ($("div#div" + this.id + ":first").is(":hidden"))
                $("div#div" + this.id).show("1000");
            else
                $("div#div" + this.id).hide("100");

        });

        $("#pk_searchbox").autocomplete("index.php?key=produktkatalog&lang=" + $("#pk_searchbox").attr("lang") + "&typ=ajax",
        {
            delay: 10,
            minChars: 2,
            matchSubset: 1,
            matchContains: 1,
            cacheLength: 10,
            autoFill: true
        });

        // Lightboxes
        if ($("a[rel^='lightbox']").length > 0) {
            $('body').append('<div class="simple_overlay" id="lightbox" style="display:none;"><div class="info"></div><img class="progress" src="../images/lightbox/loading.gif" /></div>');
            $("a[rel^='lightbox']").overlay({ target: '#lightbox', expose: '#222222' }).gallery({ template: '${title}' });
        }

        // Galleries (azubi homepage)
        if ($("a[rel^='gallery']").length > 0) {
            $('body').append('<div class="simple_overlay" id="gallery" style="display:none;"><a class="prev">zur&uuml;ck</a><a class="next">weiter</a><div class="info"></div><img class="progress" src="../images/lightbox/loading.gif" /></div>');
            // Overlay zum Dokument hinzufügen
            $("a[rel^='gallery']").overlay({ target: '#gallery', expose: '#222222' }).gallery({
                template: '<strong>${title}</strong> <span>Bild ${index} von ${total}</span>',
                preload: true
            });
        }
    });
});

function adjustTabellen() {
    $('#content table.adjustable tr').each(function(e) {
        if ($(this).children().length == 2) {
            $(this).children().each(function(e) {
                if (e % 2 == 0) $(this).width(70);
                else $(this).width(422);
            });
        }
    });
}

// Applikationen
var app_toload = 0, app_total = 0;
var app_last = "";
$(document).ready(function() {
    if ($("#applikationprogress").length > 0) {
        $("#applikationprogress").bind("click", app_start);
        app_total = app_toload = $("img.image").length;
        $("img.image").each
	        (
	            function() {
	                $(this).bind("load", app_imageloaded);
	                $(this).bind("error", app_imageloaded);
	            }
            )

    }
});

function viewport() {
    return {
        x: $(window).scrollLeft(),
        y: $(window).scrollTop(),
        cx: $(window).width(),
        cy: $(window).height()
    };
}

function app_imageloaded() {

    app_toload--;
    if (app_toload == 0) {
        app_start();
    }
    else
        $("#todo").text("noch " + app_toload + " von " + app_total); // + " " + $(this).attr("src"));

    if ($(this).attr("main") == "true")
        $("#applikation").show();

}

function app_start() {
    $("#applikationprogress").hide();
    $("#applikation").show();
}

function app_over() {
    if (timeoutid != null)
        clearTimeout(timeoutid);
}

function app_view(id) {

    timeoutid = null;
    app_hidelast();

    var el = $("#description_" + id);
    var left = parseInt(el.css("left").substr(0, el.css("left").length - 2));
    var top = parseInt(el.css("top").substr(0, el.css("top").length - 2));

    //var v = viewport();
    //$("#debug").html("Element:" + id + " Left:" + left + " Top:" + top + " Height:" + el.height() + "--|||" + (top+el.height()) + "!" + v.cy);

    app_setPostion(el, left, top);
    el.show(); //fadeIn("slow");
    app_last = id;
    return false;
}

function app_setPostion(el, left, top) {
    var v = viewport();



    pos1 = (v.cx - el.width()) - 30;
    if (left + el.width() + 30 > v.cx)
        el.css("left", pos1);
    else
        el.css("left", left);

    pos2 = (v.cy - el.height()) - 30;
    if (top + el.height() + 30 > v.cy)
        el.css("top", pos2);
    else
        el.css("top", top);

}


var application;

function app_viewapplication(id) {
    if (application != null)
        app_hideapplication();

    if (app_last != "")
        app_hide(app_last);

    var el = $("#" + id);



    application = el;

    app_setPostion(el, 150, 10);
    el.fadeIn("slow");
    //$("#appback").fadeIn("slow");

    $("#appback").css({
        opacity: 0.8
    }).fadeIn();

    $("#appback").click(function() { app_hideapplication(); });

    return false;
}

function app_hideapplication() {
    if (application != null) {
        $("#appback").hide();
        application.fadeOut("slow");
        application = null;
        return false;
    }
}


function app_hidelast() {
    if (app_last != "")
        app_hide(app_last);

}

var timeoutid = null;

function app_hideme(el, id) {
    if (id != "")
        timeoutid = setTimeout("app_hide('" + id + "')", 1000);
}


function app_hide(id) {
    $("#description_" + id).fadeOut("fast");
}

$(document).ready(function() {
    $('#applikation div').not('.applikationpopup').css({ background:'white', opacity:0.01 });
});


function isMouseLeaveOrEnter(e, handler) { if (e.type != 'mouseout' && e.type != 'mouseover') return false; var reltg = e.relatedTarget ? e.relatedTarget : e.type == 'mouseout' ? e.toElement : e.fromElement; while (reltg && reltg != handler) reltg = reltg.parentNode; return (reltg != handler); }


jQuery.autocomplete = function(input, options) {
    // Create a link to self
    var me = this;

    // Create jQuery object for input element
    var $input = $(input).attr("autocomplete", "off");

    // Apply inputClass if necessary
    if (options.inputClass) $input.addClass(options.inputClass);

    // Create results
    var results = document.createElement("div");
    // Create jQuery object for results
    var $results = $(results);
    $results.hide().addClass(options.resultsClass).css("position", "absolute");
    if (options.width > 0) $results.css("width", options.width);

    // Add to body element
    $("#pk_search").append(results);

    input.autocompleter = me;

    var timeout = null;
    var prev = "";
    var active = -1;
    var cache = {};
    var keyb = false;
    var hasFocus = false;
    var lastKeyPressCode = null;

    // flush cache
    function flushCache() {
        cache = {};
        cache.data = {};
        cache.length = 0;
    };

    // flush cache
    flushCache();

    // if there is a data array supplied
    if (options.data != null) {
        var sFirstChar = "", stMatchSets = {}, row = [];

        // no url was specified, we need to adjust the cache length to make sure it fits the local data store
        if (typeof options.url != "string") options.cacheLength = 1;

        // loop through the array and create a lookup structure
        for (var i = 0; i < options.data.length; i++) {
            // if row is a string, make an array otherwise just reference the array
            row = ((typeof options.data[i] == "string") ? [options.data[i]] : options.data[i]);

            // if the length is zero, don't add to list
            if (row[0].length > 0) {
                // get the first character
                sFirstChar = row[0].substring(0, 1).toLowerCase();
                // if no lookup array for this character exists, look it up now
                if (!stMatchSets[sFirstChar]) stMatchSets[sFirstChar] = [];
                // if the match is a string
                stMatchSets[sFirstChar].push(row);
            }
        }

        // add the data items to the cache
        for (var k in stMatchSets) {
            // increase the cache size
            options.cacheLength++;
            // add to the cache
            addToCache(k, stMatchSets[k]);
        }
    }

    $input
	.keydown(function(e) {
	    // track last key pressed
	    lastKeyPressCode = e.keyCode;
	    switch (e.keyCode) {
	        case 38: // up
	            e.preventDefault();
	            moveSelect(-1);
	            break;
	        case 40: // down
	            e.preventDefault();
	            moveSelect(1);
	            break;
	        case 9:  // tab
	        case 13: // return
	            if (selectCurrent()) {
	                // make sure to blur off the current field
	                $input.get(0).blur();
	                e.preventDefault();
	            }
	            break;
	        default:
	            active = -1;
	            if (timeout) clearTimeout(timeout);
	            timeout = setTimeout(function() { onChange(); }, options.delay);
	            break;
	    }
	})
	.focus(function() {
	    // track whether the field has focus, we shouldn't process any results if the field no longer has focus
	    hasFocus = true;
	})
	.blur(function() {
	    // track whether the field has focus
	    hasFocus = false;
	    hideResults();
	});

    hideResultsNow();

    function onChange() {
        // ignore if the following keys are pressed: [del] [shift] [capslock]
        if (lastKeyPressCode == 46 || (lastKeyPressCode > 8 && lastKeyPressCode < 32)) return $results.hide();
        var v = $input.val();
        if (v == prev) return;
        prev = v;
        if (v.length >= options.minChars) {
            $input.addClass(options.loadingClass);
            requestData(v);
        } else {
            $input.removeClass(options.loadingClass);
            $results.hide();
        }
    };

    function moveSelect(step) {

        var lis = $("li", results);
        if (!lis) return;

        active += step;

        if (active < 0) {
            active = 0;
        } else if (active >= lis.size()) {
            active = lis.size() - 1;
        }

        lis.removeClass("ac_over");

        $(lis[active]).addClass("ac_over");

        // Weird behaviour in IE
        // if (lis[active] && lis[active].scrollIntoView) {
        // 	lis[active].scrollIntoView(false);
        // }

    };

    function selectCurrent() {
        var li = $("li.ac_over", results)[0];
        if (!li) {
            var $li = $("li", results);
            if (options.selectOnly) {
                if ($li.length == 1) li = $li[0];
            } else if (options.selectFirst) {
                li = $li[0];
            }
        }
        if (li) {
            selectItem(li);
            return true;
        } else {
            return false;
        }
    };

    function selectItem(li) {
        if (!li) {
            li = document.createElement("li");
            li.extra = [];
            li.selectValue = "";
        }
        var v = $.trim(li.selectValue ? li.selectValue : li.innerHTML);
        input.lastSelected = v;
        prev = v;
        $results.html("");
        $input.val(v);
        hideResultsNow();
        if (options.onItemSelect) setTimeout(function() { options.onItemSelect(li) }, 1);
    };

    // selects a portion of the input string
    function createSelection(start, end) {
        // get a reference to the input element
        var field = $input.get(0);
        if (field.createTextRange) {
            var selRange = field.createTextRange();
            selRange.collapse(true);
            selRange.moveStart("character", start);
            selRange.moveEnd("character", end);
            selRange.select();
        } else if (field.setSelectionRange) {
            field.setSelectionRange(start, end);
        } else {
            if (field.selectionStart) {
                field.selectionStart = start;
                field.selectionEnd = end;
            }
        }
        field.focus();
    };

    // fills in the input box w/the first match (assumed to be the best match)
    function autoFill(sValue) {
        // if the last user key pressed was backspace, don't autofill
        if (lastKeyPressCode != 8) {
            // fill in the value (keep the case the user has typed)
            $input.val($input.val() + sValue.substring(prev.length));
            // select the portion of the value not typed by the user (so the next character will erase)
            createSelection(prev.length, sValue.length);
        }
    };

    function showResults() {
        // get the position of the input field right now (in case the DOM is shifted)
        var pos = findPos(input);
        pos.x = 520;
        pos.y = -10;
        //alert(pos.x);
        // either use the specified width, or autocalculate based on form element
        var iWidth = (options.width > 0) ? options.width : $input.width();
        // reposition
        //alert($("pagewrapper").offsetHeight);
//        $results.css({
//            width: parseInt(iWidth) + "px",
//            top: (pos.y + input.offsetHeight) + "px",
//            left: pos.x + "px"
//        }).show();
        $results.css({
            width: parseInt(iWidth) + "px",
            top: "31px",
            left: "10px",
            zIndex:100
        }).show();
    };

    function hideResults() {
        if (timeout) clearTimeout(timeout);
        timeout = setTimeout(hideResultsNow, 200);
    };

    function hideResultsNow() {
        if (timeout) clearTimeout(timeout);
        $input.removeClass(options.loadingClass);
        if ($results.is(":visible")) {
            $results.hide();
        }
        if (options.mustMatch) {
            var v = $input.val();
            if (v != input.lastSelected) {
                selectItem(null);
            }
        }
    };

    function receiveData(q, data) {
        if (data) {
            $input.removeClass(options.loadingClass);
            results.innerHTML = "";

            // if the field no longer has focus or if there are no matches, do not display the drop down
            if (!hasFocus || data.length == 0) return hideResultsNow();

            if ($.browser.msie) {
                // we put a styled iframe behind the calendar so HTML SELECT elements don't show through
                $results.append(document.createElement('iframe'));
            }
            results.appendChild(dataToDom(data));
            // autofill in the complete box w/the first match as long as the user hasn't entered in more data
            if (options.autoFill && ($input.val().toLowerCase() == q.toLowerCase())) autoFill(data[0][0]);
            showResults();
        } else {
            hideResultsNow();
        }
    };

    function parseData(data) {
        if (!data) return null;
        var parsed = [];
        var rows = data.split(options.lineSeparator);
        for (var i = 0; i < rows.length; i++) {
            var row = $.trim(rows[i]);
            if (row) {
                parsed[parsed.length] = row.split(options.cellSeparator);
            }
        }
        return parsed;
    };

    function dataToDom(data) {
        var ul = document.createElement("ul");
        var num = data.length;

        // limited results to a max number
        if ((options.maxItemsToShow > 0) && (options.maxItemsToShow < num)) num = options.maxItemsToShow;

        for (var i = 0; i < num; i++) {
            var row = data[i];
            if (!row) continue;
            var li = document.createElement("li");
            if (options.formatItem) {
                li.innerHTML = options.formatItem(row, i, num);
                li.selectValue = row[0];
            } else {
                li.innerHTML = row[0];
                li.selectValue = row[0];
            }
            var extra = null;
            if (row.length > 1) {
                extra = [];
                for (var j = 1; j < row.length; j++) {
                    extra[extra.length] = row[j];
                }
            }
            li.extra = extra;
            ul.appendChild(li);
            $(li).hover(
				function() { $("li", ul).removeClass("ac_over"); $(this).addClass("ac_over"); active = $("li", ul).indexOf($(this).get(0)); },
				function() { $(this).removeClass("ac_over"); }
			).click(function(e) { e.preventDefault(); e.stopPropagation(); selectItem(this) });
        }
        return ul;
    };

    function requestData(q) {
        if (!options.matchCase) q = q.toLowerCase();
        var data = options.cacheLength ? loadFromCache(q) : null;
        // recieve the cached data
        if (data) {
            receiveData(q, data);
            // if an AJAX url has been supplied, try loading the data now
        } else if ((typeof options.url == "string") && (options.url.length > 0)) {
            $.get(makeUrl(q), function(data) {
                data = parseData(data);
                addToCache(q, data);
                receiveData(q, data);
            });
            // if there's been no data found, remove the loading class
        } else {
            $input.removeClass(options.loadingClass);
        }
    };

    function makeUrl(q) {
        var url = options.url + "&q=" + encodeURI(q);
        for (var i in options.extraParams) {
            url += "&" + i + "=" + encodeURI(options.extraParams[i]);
        }
        return url;
    };

    function loadFromCache(q) {
        if (!q) return null;
        if (cache.data[q]) return cache.data[q];
        if (options.matchSubset) {
            for (var i = q.length - 1; i >= options.minChars; i--) {
                var qs = q.substr(0, i);
                var c = cache.data[qs];
                if (c) {
                    var csub = [];
                    for (var j = 0; j < c.length; j++) {
                        var x = c[j];
                        var x0 = x[0];
                        if (matchSubset(x0, q)) {
                            csub[csub.length] = x;
                        }
                    }
                    return csub;
                }
            }
        }
        return null;
    };

    function matchSubset(s, sub) {
        if (!options.matchCase) s = s.toLowerCase();
        var i = s.indexOf(sub);
        if (i == -1) return false;
        return i == 0 || options.matchContains;
    };

    this.flushCache = function() {
        flushCache();
    };

    this.setExtraParams = function(p) {
        options.extraParams = p;
    };

    this.findValue = function() {
        var q = $input.val();

        if (!options.matchCase) q = q.toLowerCase();
        var data = options.cacheLength ? loadFromCache(q) : null;
        if (data) {
            findValueCallback(q, data);
        } else if ((typeof options.url == "string") && (options.url.length > 0)) {
            $.get(makeUrl(q), function(data) {
                data = parseData(data)
                addToCache(q, data);
                findValueCallback(q, data);
            });
        } else {
            // no matches
            findValueCallback(q, null);
        }
    }

    function findValueCallback(q, data) {
        if (data) $input.removeClass(options.loadingClass);

        var num = (data) ? data.length : 0;
        var li = null;

        for (var i = 0; i < num; i++) {
            var row = data[i];

            if (row[0].toLowerCase() == q.toLowerCase()) {
                li = document.createElement("li");
                if (options.formatItem) {
                    li.innerHTML = options.formatItem(row, i, num);
                    li.selectValue = row[0];
                } else {
                    li.innerHTML = row[0];
                    li.selectValue = row[0];
                }
                var extra = null;
                if (row.length > 1) {
                    extra = [];
                    for (var j = 1; j < row.length; j++) {
                        extra[extra.length] = row[j];
                    }
                }
                li.extra = extra;
            }
        }

        if (options.onFindValue) setTimeout(function() { options.onFindValue(li) }, 1);
    }

    function addToCache(q, data) {
        if (!data || !q || !options.cacheLength) return;
        if (!cache.length || cache.length > options.cacheLength) {
            flushCache();
            cache.length++;
        } else if (!cache[q]) {
            cache.length++;
        }
        cache.data[q] = data;
    };

    function findPos(obj) {
        var curleft = obj.offsetLeft || 0;
        var curtop = obj.offsetTop || 0;
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        }
        return { x: curleft, y: curtop };
    }
}

jQuery.fn.autocomplete = function(url, options, data) {
    // Make sure options exists
    options = options || {};
    // Set url as option
    options.url = url;
    // set some bulk local data
    options.data = ((typeof data == "object") && (data.constructor == Array)) ? data : null;

    // Set default values for required options
    options.inputClass = options.inputClass || "ac_input";
    options.resultsClass = options.resultsClass || "ac_results";
    options.lineSeparator = options.lineSeparator || "\n";
    options.cellSeparator = options.cellSeparator || "|";
    options.minChars = options.minChars || 1;
    options.delay = options.delay || 400;
    options.matchCase = options.matchCase || 0;
    options.matchSubset = options.matchSubset || 1;
    options.matchContains = options.matchContains || 0;
    options.cacheLength = options.cacheLength || 1;
    options.mustMatch = options.mustMatch || 0;
    options.extraParams = options.extraParams || {};
    options.loadingClass = options.loadingClass || "ac_loading";
    options.selectFirst = options.selectFirst || false;
    options.selectOnly = options.selectOnly || false;
    options.maxItemsToShow = options.maxItemsToShow || -1;
    options.autoFill = options.autoFill || false;
    options.width = parseInt(options.width, 10) || 0;

    this.each(function() {
        var input = this;
        new jQuery.autocomplete(input, options);
    });

    // Don't break the chain
    return this;
}

jQuery.fn.autocompleteArray = function(data, options) {
    return this.autocomplete(null, options, data);
}

jQuery.fn.indexOf = function(e) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == e) return i;
    }
    return -1;
};


function copytoclipboard(id) {
    var s = $("#" + id).html();
    alert(s);
    if (window.clipboardData && clipboardData.setData) {
        clipboardData.setData("text/html", s);
    }
    else {
    }
}

