/*
* Autocomplete - jQuery plugin 1.1pre
*
* Copyright (c) 2007 Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, JÃ¶rn Zaefferer
*
* Dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
*
* Revision: $Id: jquery.autocomplete.js 5785 2008-07-12 10:37:33Z joern.zaefferer $
*
*/

(function($) {

    $.fn.extend({
        autocomplete: function(urlOrData, options) {
            var isUrl = typeof urlOrData == "string";
            options = $.extend({}, $.Autocompleter.defaults, {
                url: isUrl ? urlOrData : null,
                data: isUrl ? null : urlOrData,
                delay: isUrl ? $.Autocompleter.defaults.delay : 10,
                max: options && !options.scroll ? 10 : 150
            }, options);

            // if highlight is set to false, replace it with a do-nothing function
            options.highlight = options.highlight || function(value) { return value; };

            // if the formatMatch option is not specified, then use formatItem for backwards compatibility
            options.formatMatch = options.formatMatch || options.formatItem;

            return this.each(function() {
                new $.Autocompleter(this, options);
            });
        },
        result: function(handler) {
            return this.bind("result", handler);
        },
        search: function(handler) {
            return this.trigger("search", [handler]);
        },
        flushCache: function() {
            return this.trigger("flushCache");
        },
        setOptions: function(options) {
            return this.trigger("setOptions", [options]);
        },
        unautocomplete: function() {
            return this.trigger("unautocomplete");
        }
    });

    $.Autocompleter = function(input, options) {

        var KEY = {
            UP: 38,
            DOWN: 40,
            DEL: 46,
            TAB: 9,
            RETURN: 13,
            ESC: 27,
            COMMA: 188,
            PAGEUP: 33,
            PAGEDOWN: 34,
            BACKSPACE: 8
        };

        // Create $ object for input element
        var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);

        var timeout;
        var previousValue = "";
        var cache = $.Autocompleter.Cache(options);
        var hasFocus = 0;
        var lastKeyPressCode;
        var config = {
            mouseDownOnSelect: false
        };
        var select = $.Autocompleter.Select(options, input, selectCurrent, config);

        var blockSubmit;

        // prevent form submit in opera when selecting with return key
        $.browser.opera && $(input.form).bind("submit.autocomplete", function() {
            if (blockSubmit) {
                blockSubmit = false;
                return false;
            }
        });

        // only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
        $input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
            // track last key pressed
            lastKeyPressCode = event.keyCode;
            switch (event.keyCode) {

                case KEY.UP:
                    event.preventDefault();
                    if (select.visible()) {
                        select.prev();
                    } else {
                        onChange(0, true);
                    }
                    break;

                case KEY.DOWN:
                    event.preventDefault();
                    if (select.visible()) {
                        select.next();
                    } else {
                        onChange(0, true);
                    }
                    break;

                case KEY.PAGEUP:
                    event.preventDefault();
                    if (select.visible()) {
                        select.pageUp();
                    } else {
                        onChange(0, true);
                    }
                    break;

                case KEY.PAGEDOWN:
                    event.preventDefault();
                    if (select.visible()) {
                        select.pageDown();
                    } else {
                        onChange(0, true);
                    }
                    break;

                // matches also semicolon                                       
                case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
                case KEY.TAB:
                case KEY.RETURN:
                    if (selectCurrent()) {
                        // stop default to prevent a form submit, Opera needs special handling
                        event.preventDefault();
                        blockSubmit = true;
                        return false;
                    }
                    else {
                        select.hide();
                    }
                    break;

                case KEY.ESC:
                    select.hide();
                    break;

                default:
                    clearTimeout(timeout);
                    timeout = setTimeout(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++;
        }).blur(function() {
            hasFocus = 0;
            if (!config.mouseDownOnSelect) {
                hideResults();
            }
        }).click(function() {
            // show select when clicking in a focused field
            if (hasFocus++ > 1 && !select.visible()) {
                onChange(0, true);
            }
        }).bind("search", function() {
            // TODO why not just specifying both arguments?
            var fn = (arguments.length > 1) ? arguments[1] : null;
            function findValueCallback(q, data) {
                var result;
                if (data && data.length) {
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].result.toLowerCase() == q.toLowerCase()) {
                            result = data[i];
                            break;
                        }
                    }
                }
                if (typeof fn == "function") fn(result);
                else $input.trigger("result", result && [result.data, result.value]);
            }
            $.each(trimWords($input.val()), function(i, value) {
                request(value, findValueCallback, findValueCallback);
            });
        }).bind("flushCache", function() {
            cache.flush();
        }).bind("setOptions", function() {
            $.extend(options, arguments[1]);
            // if we've updated the data, repopulate
            if ("data" in arguments[1])
                cache.populate();
        }).bind("unautocomplete", function() {
            select.unbind();
            $input.unbind();
            $(input.form).unbind(".autocomplete");
        });


        function selectCurrent() {
            var selected = select.selected();
            if (!selected)
                return false;

            var v = selected.result;
            previousValue = v;

            if (options.multiple) {
                var words = trimWords($input.val());
                if (words.length > 1) {
                    v = words.slice(0, words.length - 1).join(options.multipleSeparator) + options.multipleSeparator + v;
                }
                v += options.multipleSeparator;
            }

            $input.val(v);
            hideResultsNow();
            $input.trigger("result", [selected.data, selected.value]);
            return true;
        }

        function onChange(crap, skipPrevCheck) {
            if (lastKeyPressCode == KEY.DEL) {
                select.hide();
                return;
            }

            var currentValue = $input.val();

            if (!skipPrevCheck && currentValue == previousValue)
                return;

            previousValue = currentValue;

            currentValue = lastWord(currentValue);
            if (currentValue.length >= options.minChars) {
                $input.addClass(options.loadingClass);
                if (!options.matchCase)
                    currentValue = currentValue.toLowerCase();
                request(currentValue, receiveData, hideResultsNow);
            } else {
                stopLoading();
                select.hide();
            }
        };

        function trimWords(value) {
            if (!value) {
                return [""];
            }
            var words = value.split(options.multipleSeparator);
            var result = [];
            $.each(words, function(i, value) {
                if ($.trim(value))
                    result[i] = $.trim(value);
            });
            return result;
        }

        function lastWord(value) {
            if (!options.multiple)
                return value;
            var words = trimWords(value);
            return words[words.length - 1];
        }

        // fills in the input box w/the first match (assumed to be the best match)
        // q: the term entered
        // sValue: the first matching result
        function autoFill(q, sValue) {
            // autofill in the complete box w/the first match as long as the user hasn't entered in more data
            // if the last user key pressed was backspace, don't autofill
            if (options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE) {
                // fill in the value (keep the case the user has typed)
                $input.val($input.val() + sValue.substring(lastWord(previousValue).length));
                // select the portion of the value not typed by the user (so the next character will erase)
                $.Autocompleter.Selection(input, previousValue.length, previousValue.length + sValue.length);
            }
        };

        function hideResults() {
            clearTimeout(timeout);
            timeout = setTimeout(hideResultsNow, 200);
        };

        function hideResultsNow() {
            var wasVisible = select.visible();
            select.hide();
            clearTimeout(timeout);
            stopLoading();
            if (options.mustMatch) {
                // call search and run callback
                $input.search(
				function(result) {
				    // if no value found, clear the input box
				    if (!result) {
				        if (options.multiple) {
				            var words = trimWords($input.val()).slice(0, -1);
				            $input.val(words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : ""));
				        }
				        else
				            $input.val("");
				    }
				}
			);
            }
            if (wasVisible)
            // position cursor at end of input field
                $.Autocompleter.Selection(input, input.value.length, input.value.length);
        };

        function receiveData(q, data) {
            if (data && data.length && hasFocus) {
                stopLoading();
                select.display(data, q);
                autoFill(q, data[0].value);
                select.show();
            } else {
                hideResultsNow();
            }
        };

        function request(term, success, failure) {
            if (!options.matchCase)
                term = term.toLowerCase();
            var data = cache.load(term);
            // recieve the cached data
            if (data && data.length) {
                success(term, data);
                // if an AJAX url has been supplied, try loading the data now
            } else if ((typeof options.url == "string") && (options.url.length > 0)) {

                var extraParams = {
                    timestamp: options.timeStamp ? +new Date() : ''
                };
                $.each(options.extraParams, function(key, param) {
                    extraParams[key] = typeof param == "function" ? param() : param;
                });

                $.ajax({
                    // try to leverage ajaxQueue plugin to abort previous requests
                    mode: "abort",
                    // limit abortion to this input
                    port: "autocomplete" + input.name,
                    dataType: options.dataType,
                    type: options.request,
                    url: options.url,
                    data: $.extend({
                        q: lastWord(term),
                        limit: options.max
                    }, extraParams),
                    success: function(data) {
                        var parsed = options.parse && options.parse(data) || parse(data);
                        if (parsed.length < options.max) {
                            cache.add(term, parsed);
                        }
                        success(term, parsed);
                    }
                });
            } else {
                // if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
                select.emptyList();
                failure(term);
            }
        };

        function parse(data) {
            var parsed = [];
            var rows = data.split("\n");
            for (var i = 0; i < rows.length; i++) {
                var row = $.trim(rows[i]);
                if (row) {
                    row = row.split("|");
                    parsed[parsed.length] = {
                        data: row,
                        value: row[0],
                        result: options.formatResult && options.formatResult(row, row[0]) || row[0]
                    };
                }
            }
            return parsed;
        };

        function stopLoading() {
            $input.removeClass(options.loadingClass);
        };
    };

    $.Autocompleter.defaults = {
        inputClass: "ac_input",
        resultsClass: "ac_results",
        loadingClass: "ac_loading",
        minChars: 1,
        delay: 400,
        matchCase: false,
        matchSubset: true,
        matchContains: false,
        cacheLength: 10,
        max: 100,
        mustMatch: false,
        extraParams: {},
        selectFirst: true,
        formatItem: function(row) { return row[0]; },
        formatMatch: null,
        autoFill: false,
        request: 'GET',
        width: 0,
        timeStamp: true,
        multiple: false,
        multipleSeparator: ", ",
        highlight: function(value, term) {
            return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
        },
        scroll: true,
        scrollHeight: 180
    };

    $.Autocompleter.Cache = function(options) {

        var data = {};
        var length = 0;

        function matchSubset(s, sub) {
            if (!options.matchCase)
                s = s.toLowerCase();
            var i = s.indexOf(sub);
            if (options.matchContains == "word") {
                i = s.toLowerCase().search("\\b" + sub.toLowerCase());
            }
            if (i == -1) return false;
            return i >= 0 || options.matchContains;
        };

        function add(q, value) {
            if (length > options.cacheLength) {
                flush();
            }
            if (!data[q]) {
                length++;
            }
            data[q] = value;
        }

        function populate() {
            if (!options.data) return false;
            // track the matches
            var stMatchSets = {},
			nullData = 0;

            // no url was specified, we need to adjust the cache length to make sure it fits the local data store
            if (!options.url) options.cacheLength = 1;

            // track all options for minChars = 0
            stMatchSets[""] = [];

            // loop through the array and create a lookup structure
            for (var i = 0, ol = options.data.length; i < ol; i++) {
                var rawValue = options.data[i];
                // if rawValue is a string, make an array otherwise just reference the array
                rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;

                var value = options.formatMatch(rawValue, i + 1, options.data.length);
                if (value === false)
                    continue;

                var firstChar = value.charAt(0).toLowerCase();
                // if no lookup array for this character exists, look it up now
                if (!stMatchSets[firstChar])
                    stMatchSets[firstChar] = [];

                // if the match is a string
                var row = {
                    value: value,
                    data: rawValue,
                    result: options.formatResult && options.formatResult(rawValue) || value
                };

                // push the current match into the set list
                stMatchSets[firstChar].push(row);

                // keep track of minChars zero items
                if (nullData++ < options.max) {
                    stMatchSets[""].push(row);
                }
            };

            // add the data items to the cache
            $.each(stMatchSets, function(i, value) {
                // increase the cache size
                options.cacheLength++;
                // add to the cache
                add(i, value);
            });
        }

        // populate any existing data
        setTimeout(populate, 25);

        function flush() {
            data = {};
            length = 0;
        }

        return {
            flush: flush,
            add: add,
            populate: populate,
            load: function(q) {
                if (!options.cacheLength || !length)
                    return null;
                /* 
                * if dealing w/local data and matchContains than we must make sure
                * to loop through all the data collections looking for matches
                */
                if (!options.url && options.matchContains) {
                    // track all matches
                    var csub = [];
                    // loop through all the data grids for matches
                    for (var k in data) {
                        // don't search through the stMatchSets[""] (minChars: 0) cache
                        // this prevents duplicates
                        if (k.length > 0) {
                            var c = data[k];
                            $.each(c, function(i, x) {
                                // if we've got a match, add it to the array
                                if (matchSubset(x.value, q)) {
                                    csub.push(x);
                                }
                            });
                        }
                    }
                    return csub;
                } else
                // if the exact item exists, use it
                    if (data[q]) {
                    return data[q];
                } else
                    if (options.matchSubset) {
                    for (var i = q.length - 1; i >= options.minChars; i--) {
                        var c = data[q.substr(0, i)];
                        if (c) {
                            var csub = [];
                            $.each(c, function(i, x) {
                                if (matchSubset(x.value, q)) {
                                    csub[csub.length] = x;
                                }
                            });
                            return csub;
                        }
                    }
                }
                return null;
            }
        };
    };

    $.Autocompleter.Select = function(options, input, select, config) {
        var CLASSES = {
            ACTIVE: "ac_over"
        };

        var listItems,
		active = -1,
		data,
		term = "",
		needsInit = true,
		element,
		list;

        // Create results
        function init() {
            if (!needsInit)
                return;
            element = $("<div/>")
		.hide()
		.addClass(options.resultsClass)
		.css("position", "absolute")
		.appendTo(document.body);

            list = $("<ul/>").appendTo(element).mouseover(function(event) {
                if (target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
                    active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
                    $(target(event)).addClass(CLASSES.ACTIVE);
                }
            }).click(function(event) {
                $(target(event)).addClass(CLASSES.ACTIVE);
                select();
                // TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
                input.focus();
                return false;

            }).mousedown(function() {
                config.mouseDownOnSelect = true;
            }).mouseup(function() {
                config.mouseDownOnSelect = false;
            });

            if (options.width > 0)
                element.css("width", options.width);

            needsInit = false;
        }

        function target(event) {
            var element = event.target;
            while (element && element.tagName != "LI")
                element = element.parentNode;
            // more fun with IE, sometimes event.target is empty, just ignore it then
            if (!element)
                return [];
            return element;
        }

        function moveSelect(step) {
            listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
            movePosition(step);
            var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
            if (options.scroll) {
                var offset = 0;
                listItems.slice(0, active).each(function() {
                    offset += this.offsetHeight;
                });
                if ((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
                    list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
                } else if (offset < list.scrollTop()) {
                    list.scrollTop(offset);
                }
            }
        };

        function movePosition(step) {
            active += step;
            if (active < 0) {
                active = listItems.size() - 1;
            } else if (active >= listItems.size()) {
                active = 0;
            }
        }

        function limitNumberOfItems(available) {
            return options.max && options.max < available
			? options.max
			: available;
        }

        function fillList() {
            list.empty();
            var max = limitNumberOfItems(data.length);
            for (var i = 0; i < max; i++) {
                if (!data[i])
                    continue;
                var formatted = options.formatItem(data[i].data, i + 1, max, data[i].value, term);
                if (formatted === false)
                    continue;
                var li = $("<li/>").html(options.highlight(formatted, term)).addClass(i % 2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
                $.data(li, "ac_data", data[i]);
            }
            listItems = list.find("li");
            if (options.selectFirst) {
                listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
                active = 0;
            }
            // apply bgiframe if available
            if ($.fn.bgiframe)
                list.bgiframe();
        }

        return {
            display: function(d, q) {
                init();
                data = d;
                term = q;
                fillList();
            },
            next: function() {
                moveSelect(1);
            },
            prev: function() {
                moveSelect(-1);
            },
            pageUp: function() {
                if (active != 0 && active - 8 < 0) {
                    moveSelect(-active);
                } else {
                    moveSelect(-8);
                }
            },
            pageDown: function() {
                if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
                    moveSelect(listItems.size() - 1 - active);
                } else {
                    moveSelect(8);
                }
            },
            hide: function() {
                element && element.hide();
                listItems && listItems.removeClass(CLASSES.ACTIVE);
                active = -1;
            },
            visible: function() {
                return element && element.is(":visible");
            },
            current: function() {
                return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
            },
            show: function() {
                var offset = $(input).offset();
                element.css({
                    width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
                    top: offset.top + input.offsetHeight,
                    left: offset.left
                }).show();
                if (options.scroll) {
                    list.scrollTop(0);
                    list.css({
                        maxHeight: options.scrollHeight,
                        overflow: 'auto'
                    });

                    if ($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
                        var listHeight = 0;
                        listItems.each(function() {
                            listHeight += this.offsetHeight;
                        });
                        var scrollbarsVisible = listHeight > options.scrollHeight;
                        list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight);
                        if (!scrollbarsVisible) {
                            // IE doesn't recalculate width when scrollbar disappears
                            listItems.width(list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")));
                        }
                    }

                }
            },
            selected: function() {
                var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
                return selected && selected.length && $.data(selected[0], "ac_data");
            },
            emptyList: function() {
                list && list.empty();
            },
            unbind: function() {
                element && element.remove();
            }
        };
    };

    $.Autocompleter.Selection = function(field, start, end) {
        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();
    };

})(jQuery);

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};(function() {
    $.extend($.fn, {

        ddMenu: function(o, callback) {
            // Defaults
            if (o.menu == undefined) return false;
            if (o.inSpeed == undefined) o.inSpeed = 150;
            if (o.outSpeed == undefined) o.outSpeed = 75;
            if (o.leftButton == undefined) o.leftButton = true;
            // 0 needs to be -1 for expected results (no fade)
            if (o.inSpeed == 0) o.inSpeed = -1;
            if (o.outSpeed == 0) o.outSpeed = -1;
            if (o.ajax == undefined) o.ajax = null;
            if (o.scrollHeight == undefined) o.scrollHeight = 250;
            if (o.expandDirection == undefined) o.expandDirection = 'left';
            if (o.elementOffsetWidth == undefined) o.elementOffsetWidth = 0;
            if (o.elementOffsetHeight == undefined) o.elementOffsetHeight = 0;
            // Loop each context menu
            $(this).each(function() {
                var el = $(this);
                // Add ddMenu class
                $('#' + o.menu).addClass('ddMenu');

                // Simulate a true right click
                $(el).mousedown(function(e) {
                    var evt = e;
                    $(el).mouseup(function(e) {
                        var srcElement = this;
                        $(srcElement).addClass("click");
                        $(el).unbind('mouseup');
                        if (evt.button == 2 || o.leftButton == true) {
                            // Hide context menus that may be showing
                            $(".ddMenu").hide().removeClass('scroll');
                            // Get this context menu
                            var menu = $('#' + o.menu);

                            if ($(el).hasClass('disabled')) return false;
                            // Show the menu
                            $('body').unbind('click');
                            adjustSize(menu, srcElement);
                            $(menu).fadeIn(o.inSpeed);
                            // Get data if ajax is defined
                            if (o.ajax) {
                                $(menu).html("<li><a href='#'>Loading</a></li>");
                                adjustSize(menu, srcElement);
                                var field = el.attr("id").substr(el.attr("id").lastIndexOf("_") + 1).toLowerCase()
                                $.getJSON(o.ajax, { field: field, requesttime: new Date().getTime() },
                                    function(data) {

                                        var li = ""
                                        for (var i = 0; i < data.length; i++) {
                                            li += "<li><a href='#" + data[i].ValueField + "'>" + data[i].TextField + "</a></li>"
                                        }
                                        $(menu).html(li);
                                        adjustSize(menu, srcElement);
                                        $(menu).find('A').unbind('click');
                                        $(menu).find('LI:not(.disabled) A').click(function() {
                                            $('body').unbind('click').unbind('keypress');
                                            $(".ddMenu").hide()
                                            // Callback
                                            var value = $(this).attr('href');
                                            value = value.substring(value.indexOf("#") + 1);
                                            if (callback) callback(value, $(this).html().replace(/^(\s|\n|\r)*((.|\n|\r)*?)(\s|\n|\r)*$/g, "$2"), $(srcElement));
                                            return false;
                                        });

                                    }
                                    );
                            }
                            else {
                                $('#' + o.menu).find('A').unbind('click');
                                $('#' + o.menu).find('LI:not(.disabled) A').click(function() {
                                    $('body').unbind('click').unbind('keypress');
                                    $(".ddMenu").hide();
                                    // Callback
                                    var value = $(this).attr('href');
                                    value = value.substring(value.indexOf("#") + 1);
                                    if (callback) callback(value, $(this).html().replace(/^(\s|\n|\r)*((.|\n|\r)*?)(\s|\n|\r)*$/g, "$2"), $(srcElement));
                                    return false;
                                });
                            }

                            // Hide bindings
                            setTimeout(function() { // Delay for Mozilla
                                $('body').click(function() {
                                    $('body').unbind('click').unbind('keypress');
                                    $(menu).fadeOut(o.outSpeed);
                                    return false;
                                });
                            }, 0);
                        }
                    });
                });
            });
            return $(this);
            function adjustSize(ddmenu, element) {
                var pos = getAbsolutePos(element);
                var elementwidth = $(element).width() + o.elementOffsetWidth;
                var elementheight = $(element).height();
                var scroll = false
                $(ddmenu).width('auto');
                $(ddmenu).width($(ddmenu).height() > o.scrollHeight ? $(ddmenu).width() + 17 > elementwidth ? $(ddmenu).width() + 17 : elementwidth : $(ddmenu).width() > elementwidth ? $(ddmenu).width() : elementwidth);
                $(ddmenu).height($(ddmenu).height() > o.scrollHeight ? o.scrollHeight : 'auto');
                if (o.expandDirection == 'left') {
                    $(ddmenu).css({ top: pos.y + elementheight + o.elementOffsetHeight, left: pos.x + elementwidth - $(ddmenu).width() });
                }
                else {
                    $(ddmenu).css({ top: pos.y + elementheight + o.elementOffsetHeight, left: pos.x });
                }
            };
        }
    });

})(jQuery);/* JQuery RC4 encryption/decryption
* Copyright (c) 2009 by Tony Simek.
* released under the terms of the Gnu Public License.
* Email: tony.simek@gmail.com
*/
(function($) {
    $.fn.rc4 = function(settings) {
        var defaults = { key: null, method: "encrypt", callback: null };
        var options = $.extend(defaults, settings);
        if ($.fn.rc4.ctrlrInst == null) { $.fn.rc4.ctrlrInst = new $.fn.rc4.ctrlr(options); }
        return this.each(function() {
            $.fn.rc4.ctrlrInst.settings = options;
            $.fn.rc4.ctrlrInst.container = this; $.fn.rc4.ctrlrInst.initialise(this);
        });
    }
    $.extend({ hexEncode: function(data) {
        var b16D = '0123456789abcdef'; var b16M = new Array();
        for (var i = 0; i < 256; i++) { b16M[i] = b16D.charAt(i >> 4) + b16D.charAt(i & 15); }
        var result = new Array(); for (var i = 0; i < data.length; i++) { result[i] = b16M[data.charCodeAt(i)]; }
        return result.join('');
    }, hexDecode: function(data) {
        var b16D = '0123456789abcdef'; var b16M = new Array();
        for (var i = 0; i < 256; i++) { b16M[b16D.charAt(i >> 4) + b16D.charAt(i & 15)] = String.fromCharCode(i); }
        if (!data.match(/^[a-f0-9]*$/i)) return false; if (data.length % 2) data = '0' + data;
        var result = new Array(); var j = 0; for (var i = 0; i < data.length; i += 2) { result[j++] = b16M[data.substr(i, 2)]; }
        return result.join('');
    }, rc4Encrypt: function(key, pt) {
        s = new Array(); for (var i = 0; i < 256; i++) { s[i] = i; }; var j = 0; var x;
        for (i = 0; i < 256; i++) { j = (j + s[i] + key.charCodeAt(i % key.length)) % 256; x = s[i]; s[i] = s[j]; s[j] = x; }
        i = 0; j = 0; var ct = ''; for (var y = 0; y < pt.length; y++) {
            i = (i + 1) % 256; j = (j + s[i]) % 256; x = s[i]; s[i] = s[j]; s[j] = x;
            ct += String.fromCharCode(pt.charCodeAt(y) ^ s[(s[i] + s[j]) % 256]);
        } return ct;
    }, rc4Decrypt: function(key, ct) {
        return $.rc4Encrypt(key, ct);
    }, rc4EncryptStr: function(str, key) {
        return $.hexEncode($.rc4Encrypt(key, unescape(encodeURIComponent(str))));
    }, rc4DecryptStr: function(hexStr, key) { return decodeURIComponent(escape($.rc4Decrypt(key, $.hexDecode(hexStr)))); }
    });
    $.rc4 = {}; $.fn.rc4.ctrlrInst = null; $.fn.rc4.ctrlr = function(settings) { this.settings = settings; }; var ctrlr = $.fn.rc4.ctrlr;
    ctrlr.prototype.initialise = function() {
        if (this.settings.key) {
            if (this.settings.method) {
                if ($.trim(this.settings.method.toUpperCase()) == "ENCRYPT") {
                    this.setObjectValue($.hexEncode($.rc4Encrypt(this.settings.key, this.getObjectValue())))
                }
                if ($.trim(this.settings.method.toUpperCase()) == "DECRYPT") {
                    this.setObjectValue($.rc4Decrypt(this.settings.key, $.hexDecode(this.getObjectValue())));
                } 
            } 
        };
    }
    ctrlr.prototype.getObjectValue = function() {
        if ($.fn.rc4.ctrlrInst.container.innerHTML) { return $.fn.rc4.ctrlrInst.container.innerHTML; }
        if ($.fn.rc4.ctrlrInst.container.value) { return $.fn.rc4.ctrlrInst.container.value; } 
    }
    ctrlr.prototype.setObjectValue = function(data) {
        if ($.fn.rc4.ctrlrInst.container.innerHTML) { $.fn.rc4.ctrlrInst.container.innerHTML = data; }
        if ($.fn.rc4.ctrlrInst.container.value) { $.fn.rc4.ctrlrInst.container.value = data; } 
    }
})(jQuery);
/* Copyright (c) 2009 Alvaro A. Lima Jr http://alvarojunior.com/jquery/joverlay.html
* Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* Version: 0.7.1 (JUN 15, 2009)
* Requires: jQuery 1.3+
*/

(function($) {

    // Global vars
    var isIE6 = $.browser.msie && $.browser.version == 6.0; // =(
    var JOVERLAY_TIMER = null;
    var JOVERLAY_ELEMENT_PREV = null;

    $.fn.jOverlay = function(options) {

        // Element exist?
        if ($('#jOverlay').length) { $.closeOverlay(); }

        // Clear Element Prev
        JOVERLAY_ELEMENT_PREV = null;

        // Clear Timer
        if (JOVERLAY_TIMER !== null) {
            clearTimeout(JOVERLAY_TIMER);
        }
    
        // Set Options
        var options = $.extend({}, $.fn.jOverlay.options, options);

        // private function
        function center(id) {
            if (options.center) {
                $.center(id);
            }
        }

        var overlayCss = {
            height: function() {
                // handle IE 6
                if ($.browser.msie && $.browser.version < 7) {
                    var scrollHeight = Math.max(
			        document.documentElement.scrollHeight,
			        document.body.scrollHeight
			        );
                    var offsetHeight = Math.max(
			        document.documentElement.offsetHeight,
			        document.body.offsetHeight
			        );

                    if (scrollHeight < offsetHeight) {
                        return $(window).height() + 'px';
                    } else {
                        return scrollHeight + 'px';
                    }
                    // handle "good" browsers
                } else {
                    return $(document).height() + 'px';
                }
            },

            width: function() {
                // handle IE 6
                if ($.browser.msie && $.browser.version < 7) {
                    var scrollWidth = Math.max(
				    document.documentElement.scrollWidth,
				    document.body.scrollWidth
			        );
                    var offsetWidth = Math.max(
				    document.documentElement.offsetWidth,
				        document.body.offsetWidth
			        );

                    if (scrollWidth < offsetWidth) {
                        return $(window).width() + 'px';
                    } else {
                        return scrollWidth + 'px';
                    }
                    // handle "good" browsers
                } else {
                    return $(document).width() + 'px';
                }
            }
        }

        var element = this.is('*') ? this : '#jOverlayContent';
        var position = isIE6 ? 'absolute' : 'fixed';
        var isImage = /([^\/\\]+)\.(png|gif|jpeg|jpg|bmp)$/i.test(options.url);

        var imgLoading = options.imgLoading ? "<img id='jOverlayLoading' src='" + options.imgLoading + "' style='position:" + position + "; z-index:" + (options.zIndex + 9) + "; background-color: white;'/>" : '';

        $('body').prepend(imgLoading + "<div id='jOverlay' />"
			+ "<div id='jOverlayContent' style='position:" + position + "; z-index:" + (options.zIndex + 5) + "; display:none;'/>"
		);
        // Loading Centered

        center('#jOverlayLoading');


        //IE 6 FIX
        if (isIE6) {
            $('select').hide();
            $('#jOverlayContent select').show();
        }


        // Overlay Style
        $('#jOverlay').css({
            backgroundColor: options.color,
            position: position,
            top: '0px',
            left: '0px',
            filter: 'alpha(opacity=' + (options.opacity * 100) + ')', // IE =(
            opacity: options.opacity, // Good Browser =D
            zIndex: options.zIndex,
            width: overlayCss.width,
            height: overlayCss.height
        }).show();

        // ELEMENT
        if (this.is('*')) {

            JOVERLAY_ELEMENT_PREV = this.prev();

            $('#jOverlayContent').html(
				this.show().attr('display', options.autoHide ? 'none' : this.css('display'))
			);

            if (!isImage) {

                center('#jOverlayContent');

                $('#jOverlayContent').show();

                // Execute callback
                if (!options.url && $.isFunction(options.success)) {
                    options.success(this);
                }

            }

        }

        // IMAGE
        if (isImage) {

            $('<img/>').load(function() {
                var resize = $.resize(this.width, this.height);

                $(this).css({
                    width: resize.width,
                    height: resize.height
                });

                $(element).html(this);

                center('#jOverlayContent');

                $('#jOverlayLoading').fadeOut(500);
                $('#jOverlayContent').show();

                // Execute callback
                if ($.isFunction(options.success)) {
                    options.success(this);
                }

            }).error(function() {
                alert('Image (' + options.url + ') not found.');
                $.closeOverlay();
            }).attr({ 'src': options.url, 'alt': options.url });

        }

        // AJAX
        if (options.url && !isImage) {

            $.ajax({
                type: options.method,
                data: options.data,
                url: options.url,
                success: function(responseText) {

                    $('#jOverlayLoading').fadeOut(500);

                    $(element).html(responseText).show();

                    center('#jOverlayContent');

                    // Execute callback
                    if ($.isFunction(options.success)) {
                        options.success(responseText);
                    }

                },
                error: function() {
                    alert('URL (' + options.url + ') not found.');
                    $.closeOverlay();
                }
            });

        }

        // :(
        if (isIE6) {

            // Window scroll
            $(window).scroll(function() {
                center('#jOverlayContent');
            });

            // Window resize
            $(window).resize(function() {

                $('#jOverlay').css({
                    width: overlayCss.width,
                    height: overlayCss.height
                });
                center('#jOverlayContent');
            });

        }

        // Press ESC to close
        $(document).keydown(function(event) {
            if (event.keyCode == 27) {
                $.closeOverlay();
            }
        });

        // Click to close
        if (options.bgClickToClose) {
            $('#jOverlay').click($.closeOverlay);
        }

        // Timeout (auto-close)
        // time in millis to wait before auto-close
        // set to 0 to disable
        if (Number(options.timeout) > 0) {
            jOverlayTimer = setTimeout($.closeOverlay, Number(options.timeout));
        }

        // ADD CSS
        $('#jOverlayContent').css(options.css || {});
    };

    // Resizing large images - orginal by Christian Montoya.
    // Edited by - Cody Lindley (http://www.codylindley.com) (Thickbox 3.1)
    $.resize = function(imageWidth, imageHeight) {
        var x = $(window).width() - 150;
        var y = $(window).height() - 150;
        if (imageWidth > x) {
            imageHeight = imageHeight * (x / imageWidth);
            imageWidth = x;
            if (imageHeight > y) {
                imageWidth = imageWidth * (y / imageHeight);
                imageHeight = y;
            }
        } else if (imageHeight > y) {
            imageWidth = imageWidth * (y / imageHeight);
            imageHeight = y;
            if (imageWidth > x) {
                imageHeight = imageHeight * (x / imageWidth);
                imageWidth = x;
            }
        }
        return { width: imageWidth, height: imageHeight };
    };

    // Centered Element
    $.center = function(element) {
        var element = $(element);
        var elemWidth = element.width();

        element.css({
            width: elemWidth + 'px',
            marginLeft: '-' + (elemWidth / 2) + 'px',
            marginTop: '-' + element.height() / 2 + 'px',
            height: 'auto',
            top: !isIE6 ? '50%' : $(window).scrollTop() + ($(window).height() / 2) + 'px',
            left: '50%'
        });
    };

    // Options default
    $.fn.jOverlay.options = {
        method: 'GET',
        data: '',
        url: '',
        color: '#4B594A',
        opacity: '0.4',
        zIndex: 9999,
        center: true,
        imgLoading: '',
        bgClickToClose: true,
        success: null,
        timeout: 0,
        autoHide: true,
        css: {}
    };

    // Close
    $.closeOverlay = function() {

        if (isIE6) { $("select").show(); }

        if (JOVERLAY_ELEMENT_PREV !== null) {
            if (JOVERLAY_ELEMENT_PREV !== null) {
                var element = $('#jOverlayContent').children();
                JOVERLAY_ELEMENT_PREV.after(element.css('display', element.attr('display')));
                element.removeAttr('display');
            }
        }

        $('#jOverlayLoading, #jOverlayContent, #jOverlay').remove();

    };

})(jQuery);/**
*
*	simpleTooltip jQuery plugin, by Marius ILIE
*	visit http://dev.mariusilie.net for details
*
**/
(function($) {
    $.fn.simpletooltip = function() {
        return this.each(function() {
            var text = $(this).attr("title");
            $(this).attr("title", "");
            if (text != undefined) {
                $(this).hover(function(e) {
                    var tipX = e.pageX + 12;
                    var tipY = e.pageY + 12;
                    $(this).attr("title", "");
                    $("body").append("<div id='simpleTooltip' style='position: absolute; z-index: 10000; display: none;'>" + text + "</div>");
                    if ($.browser.msie) var tipWidth = $("#simpleTooltip").outerWidth(true)
                    else var tipWidth = $("#simpleTooltip").width()
                    $("#simpleTooltip").width(tipWidth);
                    $("#simpleTooltip").css("left", tipX).css("top", tipY).fadeIn("medium");
                }, function() {
                    $("#simpleTooltip").remove();
                    $(this).attr("title", text);
                });
                $(this).mousemove(function(e) {
                    var tipX = e.pageX + 12;
                    var tipY = e.pageY + 12;
                    var tipWidth = $("#simpleTooltip").outerWidth(true);
                    var tipHeight = $("#simpleTooltip").outerHeight(true);
                    if (tipX + tipWidth > $(window).scrollLeft() + $(window).width()) tipX = e.pageX - tipWidth;
                    if ($(window).height() + $(window).scrollTop() < tipY + tipHeight) tipY = e.pageY - tipHeight;
                    $("#simpleTooltip").css("left", tipX).css("top", tipY).fadeIn("medium");
                });
            }
        });
    }
})(jQuery);/*
* @alias Muhammad Hussein Fattahizadeh < muhammad [AT] semnanweb [DOT] com >
* @link http://www.semnanweb.com/jquery-plugin/sha1.html
* @see http://www.webtoolkit.info/
* @license http://www.gnu.org/licenses/gpl.html [GNU General Public License]
* @param {jQuery} {sha1:function(string))
* @return string
*/

(function($) {

    var rotateLeft = function(lValue, iShiftBits) {
        return (lValue << iShiftBits) | (lValue >>> (32 - iShiftBits));
    }

    var lsbHex = function(value) {
        var string = "";
        var i;
        var vh;
        var vl;
        for (i = 0; i <= 6; i += 2) {
            vh = (value >>> (i * 4 + 4)) & 0x0f;
            vl = (value >>> (i * 4)) & 0x0f;
            string += vh.toString(16) + vl.toString(16);
        }
        return string;
    };

    var cvtHex = function(value) {
        var string = "";
        var i;
        var v;
        for (i = 7; i >= 0; i--) {
            v = (value >>> (i * 4)) & 0x0f;
            string += v.toString(16);
        }
        return string;
    };

    var uTF8Encode = function(string) {
        string = string.replace(/\x0d\x0a/g, "\x0a");
        var output = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                output += String.fromCharCode(c);
            } else if ((c > 127) && (c < 2048)) {
                output += String.fromCharCode((c >> 6) | 192);
                output += String.fromCharCode((c & 63) | 128);
            } else {
                output += String.fromCharCode((c >> 12) | 224);
                output += String.fromCharCode(((c >> 6) & 63) | 128);
                output += String.fromCharCode((c & 63) | 128);
            }
        }
        return output;
    };

    $.extend({
        sha1: function(string) {
            var blockstart;
            var i, j;
            var W = new Array(80);
            var H0 = 0x67452301;
            var H1 = 0xEFCDAB89;
            var H2 = 0x98BADCFE;
            var H3 = 0x10325476;
            var H4 = 0xC3D2E1F0;
            var A, B, C, D, E;
            var tempValue;
            string = uTF8Encode(string);
            var stringLength = string.length;
            var wordArray = new Array();
            for (i = 0; i < stringLength - 3; i += 4) {
                j = string.charCodeAt(i) << 24 | string.charCodeAt(i + 1) << 16 | string.charCodeAt(i + 2) << 8 | string.charCodeAt(i + 3);
                wordArray.push(j);
            }
            switch (stringLength % 4) {
                case 0:
                    i = 0x080000000;
                    break;
                case 1:
                    i = string.charCodeAt(stringLength - 1) << 24 | 0x0800000;
                    break;
                case 2:
                    i = string.charCodeAt(stringLength - 2) << 24 | string.charCodeAt(stringLength - 1) << 16 | 0x08000;
                    break;
                case 3:
                    i = string.charCodeAt(stringLength - 3) << 24 | string.charCodeAt(stringLength - 2) << 16 | string.charCodeAt(stringLength - 1) << 8 | 0x80;
                    break;
            }
            wordArray.push(i);
            while ((wordArray.length % 16) != 14) wordArray.push(0);
            wordArray.push(stringLength >>> 29);
            wordArray.push((stringLength << 3) & 0x0ffffffff);
            for (blockstart = 0; blockstart < wordArray.length; blockstart += 16) {
                for (i = 0; i < 16; i++) W[i] = wordArray[blockstart + i];
                for (i = 16; i <= 79; i++) W[i] = rotateLeft(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
                A = H0;
                B = H1;
                C = H2;
                D = H3;
                E = H4;
                for (i = 0; i <= 19; i++) {
                    tempValue = (rotateLeft(A, 5) + ((B & C) | (~B & D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
                    E = D;
                    D = C;
                    C = rotateLeft(B, 30);
                    B = A;
                    A = tempValue;
                }
                for (i = 20; i <= 39; i++) {
                    tempValue = (rotateLeft(A, 5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
                    E = D;
                    D = C;
                    C = rotateLeft(B, 30);
                    B = A;
                    A = tempValue;
                }
                for (i = 40; i <= 59; i++) {
                    tempValue = (rotateLeft(A, 5) + ((B & C) | (B & D) | (C & D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
                    E = D;
                    D = C;
                    C = rotateLeft(B, 30);
                    B = A;
                    A = tempValue;
                }
                for (i = 60; i <= 79; i++) {
                    tempValue = (rotateLeft(A, 5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
                    E = D;
                    D = C;
                    C = rotateLeft(B, 30);
                    B = A;
                    A = tempValue;
                }
                H0 = (H0 + A) & 0x0ffffffff;
                H1 = (H1 + B) & 0x0ffffffff;
                H2 = (H2 + C) & 0x0ffffffff;
                H3 = (H3 + D) & 0x0ffffffff;
                H4 = (H4 + E) & 0x0ffffffff;
            }
            var tempValue = cvtHex(H0) + cvtHex(H1) + cvtHex(H2) + cvtHex(H3) + cvtHex(H4);
            return tempValue.toUpperCase();
        }
    });
})(jQuery);/*
 *
 * Copyright (c) 2010 C. F., Wong (<a href="http://cloudgen.w0ng.hk">Cloudgen Examplet Store</a>)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
﻿(function(k,e,i,j){k.fn.caret=function(b,l){var a,d,f=this[0],m=k.browser.msie;if(typeof b==="object"&&typeof b.start==="number"&&typeof b.end==="number"){a=b.start;d=b.end}else if(typeof b==="number"&&typeof l==="number"){a=b;d=l}else if(typeof b==="string")if((a=f.value.indexOf(b))>-1)d=a+b[e];else a=null;else if(Object.prototype.toString.call(b)==="[object RegExp]"){b=b.exec(f.value);if(b!=null){a=b.index;d=a+b[0][e]}}if(typeof a!="undefined"){if(m){var c=this[0].createTextRange();c.collapse(true); c.moveStart("character",a);c.moveEnd("character",d-a);c.select()}else{this[0].selectionStart=a;this[0].selectionEnd=d}this[0].focus();return this}else{if(m)if(this[0].tagName.toLowerCase()!="textarea"){d=this.val();c=document.selection;a=c[i]()[j]();a.moveEnd("character",d[e]);var g=a.text==""?d[e]:d.lastIndexOf(a.text);a=c[i]()[j]();a.moveStart("character",-d[e]);var h=a.text[e]}else{a=c[i]();c=a[j]();c.moveToElementText(this[0]);c.setEndPsoint("EndToEnd",a);g=c.text[e]-a.text[e];h=g+a.text[e]}else{g= f.selectionStart;h=f.selectionEnd}c=f.value.substring(g,h);return{start:g,end:h,text:c,replace:function(n){return f.value.substring(0,g)+n+f.value.substring(h,f.value[e])}}}}})(jQuery,"length","createRange","duplicate");(function($) {

    $.fn.imgLoading = function(options) {
        var el = this
        var options = $.extend({}, $.fn.jOverlay.options, options);
        var offset = el.offset();

        var imgLoading = "<img id='" + options.id + "' src='" + options.url + "' style='position: absolute; z-index: 1000000; siplay:none; background-color: " + options.backgroundColour + ";'/>"

        $('body').prepend(imgLoading);
        var img = $('img#' + options.id)
        $(img).css("top", offset.top + ($(el).height() / 2) - ($(img).height() / 2)).css("left", offset.left + ($(el).width() / 2) - ($(img).width() / 2)).show();
        setTimeout("$.imgLoadingClose('" + options.id + "')", 5000);
    };

    // Options default
    $.fn.imgLoading.options = {
        overlay: false,
        url: '',
        backgroundColour: 'white',
        id: 'img_loading'
    };

    $.imgLoadingClose = function(id) {
        img = $('img#' + id);
        if (img != undefined) {
            img.fadeOut(500, function() { $(this).remove() });
        }
    };

})(jQuery);
(function($) {

    $.fn.favourite = function(options) {

        // Element exist?
        if ($('#favourite').length) { $.closeFavourite(); }

        // Set Options
        var options = $.extend({}, $.fn.favourite.options, options);

        return this.each(function() {
            $(this).click(function(e) {
                var tipX = e.pageX + 12;
                var tipY = e.pageY + 12;
                var fav = "<span style='float:left'><label style='padding-right: 5px'>" + options.label + "</span>";
                fav += "<input id='bookmark' name='bookmark' type='text' maxlength='100' class='textbox_wht'/></span>";
                fav += "<span id='favButtons'><a id='favSave' href='javascript:void(0);' class='btnSml'><span>Save</span></a>";
                fav += "<a id='favCancel' href='javascript:$.closeFavourite()' class='btnSml'><span>Cancel</span></a></span>";
                fav += "<span id='favSaved'>" + options.successText + "</span>";
                fav += "<span class='favText' style='clear:both; display: block'>" + options.text + "</span>";
                $("<div id='favourite'></div>").appendTo("body").append(fav);
                if ($.browser.msie) var tipWidth = $("#favourite").outerWidth(true)
                else var tipWidth = $("#favourite").width()
                $("#favourite").width(tipWidth);
                var tipHeight = $("#favourite").outerHeight(true);
                if (tipX + tipWidth > $(window).scrollLeft() + $(window).width()) tipX = e.pageX - tipWidth;
                if ($(window).height() + $(window).scrollTop() < tipY + tipHeight) tipY = e.pageY - tipHeight;
                $("#favourite").css("left", tipX).css("top", tipY).css(options.css).fadeIn("medium");
                $("#favourite #favSave").click(function() {
                    options.type = 'Search' ? options.data.SearchId = map.util.searchId : options.data.Adid = 12;
                    options.data.BookmarkName = $("#favourite #bookmark").val();
                    $.ajax({
                        url: options.url,
                        type: 'POST',
                        data: options.data,
                        success: function(data) {
                            $("#favourite #favButtons").hide();
                            $("#favourite #favSaved").show();
                        },
                        complete: function() {
                            setTimeout("$.closeFavourite()", 1000);
                        }
                    });
                });
            });
        });

        // Press ESC to close
        $(document).keydown(function(event) {
            if (event.keyCode == 27) {
                $.closeFavourite();
            }
        });
    };
    // Options default
    $.fn.favourite.options = {
        url: '',
        label: 'Bookmark Name: ',
        text: 'Save this search in your favourites. You can access your favourites under the favourites tab',
        successText: 'Saved',
        data: {},
        type: 'Search',
        css: { "border": "solid 1px #3b9628", "background-color": "#DBF3D6", "padding": "5px 5px 5px 5px" }
    };

    // Close
    $.closeFavourite = function() {
        $("#favourite *").unbind();
        $("#favourite").fadeOut("medium", function() {
            $("#favourite").remove();
        });
    };
    $.fn.unFavourite = function() {
        this.each(function() {
            $(this).unbind("click");
        });
    }
})(jQuery);
(function($) {

    $.fn.addressIssue = function(options) {

        // Element exist?
        if ($('#daIssue').length) { $.closeAddressIssue(); }

        // Set Options
        var options = $.extend({}, $.fn.addressIssue.options, options);

        return this.each(function() {
            $(this).click(function(e) {
                var tipX = e.pageX + 12;
                var tipY = e.pageY + 12;
                var comment = "<div style='padding-bottom: 5px'><span class='commentText'>" + options.text + "</span>";
                comment += "<span id='commentButtons'><a id='sendIssue' href='javascript:void(0);' class='btnSml' style='float:none; margin-left:100px'><span>Send</span></a>";
                comment += "<a id='commentCancel' href='javascript:$.closeAddressIssue()' class='btnSml' style='float:none'><span>Cancel</span></a></span>";
                comment += "<span id='commentSaved'>" + options.successText + "</span></div>";
                comment += "<span style='float:left; vertical-align:top'><label style='padding-right: 5px'>" + options.label + "</label>";
                comment += "<textarea rows='3'  id='addressComment' name='addressComment' class='textbox_wht'/></span>";
                $("<div id='daIssue'></div>").appendTo("body").append(comment);
                if ($.browser.msie) var tipWidth = $("#daIssue").outerWidth(true)
                else var tipWidth = $("#daIssue").width()
                $("#daIssue").width(tipWidth);
                var tipHeight = $("#daIssue").outerHeight(true);
                if (tipX + tipWidth > $(window).scrollLeft() + $(window).width()) tipX = e.pageX - tipWidth;
                if ($(window).height() + $(window).scrollTop() < tipY + tipHeight) tipY = e.pageY - tipHeight;
                $("#daIssue").css("left", tipX).css("top", tipY).css(options.css).fadeIn("medium");
                $("#daIssue #sendIssue").click(function() {
                options.data.AddressComment = $("#daIssue #addressComment").val();
                    $.ajax({
                        url: options.url,
                        type: 'POST',
                        data: options.data,
                        success: function(data) {
                            $("#daIssue #commentButtons").hide();
                            $("#daIssue #commentSaved").show();
                        },
                        complete: function() {
                            setTimeout("$.closeAddressIssue()", 1000);
                        }
                    });
                });
            });
        });

        // Press ESC to close
        $(document).keydown(function(event) {
            if (event.keyCode == 27) {
                $.closeAddressIssue();
            }
        });
    };
    // Options default
    $.fn.addressIssue.options = {
        url: '',
        label: 'Additional Comments: ',
        text: "Let us know if this address is located in the wrong place.",
        successText: 'Thank you.',
        data: {},
        css: { "border": "solid 1px #3b9628", "background-color": "#DBF3D6", "padding": "5px 5px 5px 5px" }
    };

    // Close
    $.closeAddressIssue = function() {
        $("#daIssue *").unbind();
        $("#daIssue").fadeOut("medium", function() {
            $("#daIssue").remove();
        });
    };
    $.fn.unAddressIssue = function() {
        this.each(function() {
            $(this).unbind("click");
        });
    }
})(jQuery);
(function($) {
    $.fn.watermark = function(text, blur) {
        return this.each(function() {
            var i = $(this), w;
            i.bind('focus.watermark', function() {
                w && !(w = 0) && i.removeClass('wMark').data('w', 0).val('');
            })
			.bind('blur.watermark', function() {
			    !i.val() && (w = 1) && i.addClass('wMark').data('w', 1).val(text);
			});
            if (blur == true) { i.blur(); }
        });
    };
    $.fn.removeWatermark = function() {
        return this.each(function() {
            $(this).data('w') && $(this).val('');
            $(this).removeData('w').removeClass('wMark').unbind('focus.watermark').unbind('blur.watermark');
        });
    };
})(jQuery);
