/** TABLE SORTER **/
/*
 * 
 * TableSorter 2.0 - Client-side table sorting with ease!
 * Version 2.0.5b
 * @requires jQuery v1.2.3
 * 
 * Copyright (c) 2007 Christian Bach
 * Examples and docs at: http://tablesorter.com
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * 
 */
/**
 * 
 * @description Create a sortable table with multi-column sorting capabilitys
 * 
 * @example $('table').tablesorter();
 * @desc Create a simple tablesorter interface.
 * 
 * @example $('table').tablesorter({ sortList:[[0,0],[1,0]] });
 * @desc Create a tablesorter interface and sort on the first and secound column column headers.
 * 
 * @example $('table').tablesorter({ headers: { 0: { sorter: false}, 1: {sorter: false} } });
 *          
 * @desc Create a tablesorter interface and disableing the first and second  column headers.
 *      
 * 
 * @example $('table').tablesorter({ headers: { 0: {sorter:"integer"}, 1: {sorter:"currency"} } });
 * 
 * @desc Create a tablesorter interface and set a column parser for the first
 *       and second column.
 * 
 * 
 * @param Object
 *            settings An object literal containing key/value pairs to provide
 *            optional settings.
 * 
 * 
 * @option String cssHeader (optional) A string of the class name to be appended
 *         to sortable tr elements in the thead of the table. Default value:
 *         "header"
 * 
 * @option String cssAsc (optional) A string of the class name to be appended to
 *         sortable tr elements in the thead on a ascending sort. Default value:
 *         "headerSortUp"
 * 
 * @option String cssDesc (optional) A string of the class name to be appended
 *         to sortable tr elements in the thead on a descending sort. Default
 *         value: "headerSortDown"
 * 
 * @option String sortInitialOrder (optional) A string of the inital sorting
 *         order can be asc or desc. Default value: "asc"
 * 
 * @option String sortMultisortKey (optional) A string of the multi-column sort
 *         key. Default value: "shiftKey"
 * 
 * @option String textExtraction (optional) A string of the text-extraction
 *         method to use. For complex html structures inside td cell set this
 *         option to "complex", on large tables the complex option can be slow.
 *         Default value: "simple"
 * 
 * @option Object headers (optional) An array containing the forces sorting
 *         rules. This option let's you specify a default sorting rule. Default
 *         value: null
 * 
 * @option Array sortList (optional) An array containing the forces sorting
 *         rules. This option let's you specify a default sorting rule. Default
 *         value: null
 * 
 * @option Array sortForce (optional) An array containing forced sorting rules.
 *         This option let's you specify a default sorting rule, which is
 *         prepended to user-selected rules. Default value: null
 * 
 * @option Boolean sortLocaleCompare (optional) Boolean flag indicating whatever
 *         to use String.localeCampare method or not. Default set to true.
 * 
 * 
 * @option Array sortAppend (optional) An array containing forced sorting rules.
 *         This option let's you specify a default sorting rule, which is
 *         appended to user-selected rules. Default value: null
 * 
 * @option Boolean widthFixed (optional) Boolean flag indicating if tablesorter
 *         should apply fixed widths to the table columns. This is usefull when
 *         using the pager companion plugin. This options requires the dimension
 *         jquery plugin. Default value: false
 * 
 * @option Boolean cancelSelection (optional) Boolean flag indicating if
 *         tablesorter should cancel selection of the table headers text.
 *         Default value: true
 * 
 * @option Boolean debug (optional) Boolean flag indicating if tablesorter
 *         should display debuging information usefull for development.
 * 
 * @type jQuery
 * 
 * @name tablesorter
 * 
 * @cat Plugins/Tablesorter
 * 
 * @author Christian Bach/christian.bach@polyester.se
 */

(function ($) {
    $.extend({
        tablesorter: new
        function () {

            var parsers = [],
                widgets = [];

            this.defaults = {
                cssHeader: "header",
                cssAsc: "headerSortUp",
                cssDesc: "headerSortDown",
                cssChildRow: "expand-child",
                sortInitialOrder: "asc",
                sortMultiSortKey: "shiftKey",
                sortForce: null,
                sortAppend: null,
                sortLocaleCompare: true,
                textExtraction: "simple",
                parsers: {}, widgets: [],
                widgetZebra: {
                    css: ["even", "odd"]
                }, headers: {}, widthFixed: false,
                cancelSelection: true,
                sortList: [],
                headerList: [],
                dateFormat: "us",
                decimal: '/\.|\,/g',
                onRenderHeader: null,
                selectorHeaders: 'thead th',
                debug: false
            };

            /* debuging utils */

            function benchmark(s, d) {
                log(s + "," + (new Date().getTime() - d.getTime()) + "ms");
            }

            this.benchmark = benchmark;

            function log(s) {
                if (typeof console != "undefined" && typeof console.debug != "undefined") {
                    console.log(s);
                } else {
                    alert(s);
                }
            }

            /* parsers utils */

            function buildParserCache(table, $headers) {

                if (table.config.debug) {
                    var parsersDebug = "";
                }

                if (table.tBodies.length == 0) return; // In the case of empty tables
                var rows = table.tBodies[0].rows;

                if (rows[0]) {

                    var list = [],
                        cells = rows[0].cells,
                        l = cells.length;

                    for (var i = 0; i < l; i++) {

                        var p = false;

                        if ($.metadata && ($($headers[i]).metadata() && $($headers[i]).metadata().sorter)) {

                            p = getParserById($($headers[i]).metadata().sorter);

                        } else if ((table.config.headers[i] && table.config.headers[i].sorter)) {

                            p = getParserById(table.config.headers[i].sorter);
                        }
                        if (!p) {

                            p = detectParserForColumn(table, rows, -1, i);
                        }

                        if (table.config.debug) {
                            parsersDebug += "column:" + i + " parser:" + p.id + "\n";
                        }

                        list.push(p);
                    }
                }

                if (table.config.debug) {
                    log(parsersDebug);
                }

                return list;
            };

            function detectParserForColumn(table, rows, rowIndex, cellIndex) {
                var l = parsers.length,
                    node = false,
                    nodeValue = false,
                    keepLooking = true;
                while (nodeValue == '' && keepLooking) {
                    rowIndex++;
                    if (rows[rowIndex]) {
                        node = getNodeFromRowAndCellIndex(rows, rowIndex, cellIndex);
                        nodeValue = trimAndGetNodeText(table.config, node);
                        if (table.config.debug) {
                            log('Checking if value was empty on row:' + rowIndex);
                        }
                    } else {
                        keepLooking = false;
                    }
                }
                for (var i = 1; i < l; i++) {
                    if (parsers[i].is(nodeValue, table, node)) {
                        return parsers[i];
                    }
                }
                // 0 is always the generic parser (text)
                return parsers[0];
            }

            function getNodeFromRowAndCellIndex(rows, rowIndex, cellIndex) {
                return rows[rowIndex].cells[cellIndex];
            }

            function trimAndGetNodeText(config, node) {
                return $.trim(getElementText(config, node));
            }

            function getParserById(name) {
                var l = parsers.length;
                for (var i = 0; i < l; i++) {
                    if (parsers[i].id.toLowerCase() == name.toLowerCase()) {
                        return parsers[i];
                    }
                }
                return false;
            }

            /* utils */

            function buildCache(table) {

                if (table.config.debug) {
                    var cacheTime = new Date();
                }

                var totalRows = (table.tBodies[0] && table.tBodies[0].rows.length) || 0,
                    totalCells = (table.tBodies[0].rows[0] && table.tBodies[0].rows[0].cells.length) || 0,
                    parsers = table.config.parsers,
                    cache = {
                        row: [],
                        normalized: []
                    };

                for (var i = 0; i < totalRows; ++i) {

                    /** Add the table data to main data array */
                    var c = $(table.tBodies[0].rows[i]),
                        cols = [];

                    // if this is a child row, add it to the last row's children and
                    // continue to the next row
                    if (c.hasClass(table.config.cssChildRow)) {
                        cache.row[cache.row.length - 1] = cache.row[cache.row.length - 1].add(c);
                        // go to the next for loop
                        continue;
                    }

                    cache.row.push(c);

                    for (var j = 0; j < totalCells; ++j) {
                        cols.push(parsers[j].format(getElementText(table.config, c[0].cells[j]), table, c[0].cells[j]));
                    }

                    cols.push(cache.normalized.length); // add position for rowCache
                    cache.normalized.push(cols);
                    cols = null;
                };

                if (table.config.debug) {
                    benchmark("Building cache for " + totalRows + " rows:", cacheTime);
                }

                return cache;
            };

            function getElementText(config, node) {

                var text = "";

                if (!node) return "";

                if (!config.supportsTextContent) config.supportsTextContent = node.textContent || false;

                if (config.textExtraction == "simple") {
                    if (config.supportsTextContent) {
                        text = node.textContent;
                    } else {
                        if (node.childNodes[0] && node.childNodes[0].hasChildNodes()) {
                            text = node.childNodes[0].innerHTML;
                        } else {
                            text = node.innerHTML;
                        }
                    }
                } else {
                    if (typeof(config.textExtraction) == "function") {
                        text = config.textExtraction(node);
                    } else {
                        text = $(node).text();
                    }
                }
                return text;
            }

            function appendToTable(table, cache) {

                if (table.config.debug) {
                    var appendTime = new Date();
                }

                var c = cache,
                    r = c.row,
                    n = c.normalized,
                    totalRows = n.length,
                    checkCell = (n[0].length - 1),
                    tableBody = $(table.tBodies[0]),
                    rows = [];


                for (var i = 0; i < totalRows; i++) {
                    var pos = n[i][checkCell];

                    rows.push(r[pos]);

                    if (!table.config.appender) {

                        //var o = ;
                        var l = r[pos].length;
                        for (var j = 0; j < l; j++) {
                            tableBody[0].appendChild(r[pos][j]);
                        }

                        // 
                    }
                }



                if (table.config.appender) {

                    table.config.appender(table, rows);
                }

                rows = null;

                if (table.config.debug) {
                    benchmark("Rebuilt table:", appendTime);
                }

                // apply table widgets
                applyWidget(table);

                // trigger sortend
                setTimeout(function () {
                    $(table).trigger("sortEnd");
                }, 0);

            };

            function buildHeaders(table) {

                if (table.config.debug) {
                    var time = new Date();
                }

                var meta = ($.metadata) ? true : false;
                
                var header_index = computeTableHeaderCellIndexes(table);

                $tableHeaders = $(table.config.selectorHeaders, table).each(function (index) {

                    this.column = header_index[this.parentNode.rowIndex + "-" + this.cellIndex];
                    // this.column = index;
                    this.order = formatSortingOrder(table.config.sortInitialOrder);
                    
					
					this.count = this.order;

                    if (checkHeaderMetadata(this) || checkHeaderOptions(table, index)) this.sortDisabled = true;
					if (checkHeaderOptionsSortingLocked(table, index)) this.order = this.lockedOrder = checkHeaderOptionsSortingLocked(table, index);

                    if (!this.sortDisabled) {
                        var $th = $(this).addClass(table.config.cssHeader);
                        if (table.config.onRenderHeader) table.config.onRenderHeader.apply($th);
                    }

                    // add cell to headerList
                    table.config.headerList[index] = this;
                });

                if (table.config.debug) {
                    benchmark("Built headers:", time);
                    log($tableHeaders);
                }

                return $tableHeaders;

            };

            // from:
            // http://www.javascripttoolbox.com/lib/table/examples.php
            // http://www.javascripttoolbox.com/temp/table_cellindex.html


            function computeTableHeaderCellIndexes(t) {
                var matrix = [];
                var lookup = {};
                var thead = t.getElementsByTagName('THEAD')[0];
                var trs = thead.getElementsByTagName('TR');

                for (var i = 0; i < trs.length; i++) {
                    var cells = trs[i].cells;
                    for (var j = 0; j < cells.length; j++) {
                        var c = cells[j];

                        var rowIndex = c.parentNode.rowIndex;
                        var cellId = rowIndex + "-" + c.cellIndex;
                        var rowSpan = c.rowSpan || 1;
                        var colSpan = c.colSpan || 1;
                        var firstAvailCol;
                        if (typeof(matrix[rowIndex]) == "undefined") {
                            matrix[rowIndex] = [];
                        }
                        // Find first available column in the first row
                        for (var k = 0; k < matrix[rowIndex].length + 1; k++) {
                            if (typeof(matrix[rowIndex][k]) == "undefined") {
                                firstAvailCol = k;
                                break;
                            }
                        }
                        lookup[cellId] = firstAvailCol;
                        for (var k = rowIndex; k < rowIndex + rowSpan; k++) {
                            if (typeof(matrix[k]) == "undefined") {
                                matrix[k] = [];
                            }
                            var matrixrow = matrix[k];
                            for (var l = firstAvailCol; l < firstAvailCol + colSpan; l++) {
                                matrixrow[l] = "x";
                            }
                        }
                    }
                }
                return lookup;
            }

            function checkCellColSpan(table, rows, row) {
                var arr = [],
                    r = table.tHead.rows,
                    c = r[row].cells;

                for (var i = 0; i < c.length; i++) {
                    var cell = c[i];

                    if (cell.colSpan > 1) {
                        arr = arr.concat(checkCellColSpan(table, headerArr, row++));
                    } else {
                        if (table.tHead.length == 1 || (cell.rowSpan > 1 || !r[row + 1])) {
                            arr.push(cell);
                        }
                        // headerArr[row] = (i+row);
                    }
                }
                return arr;
            };

            function checkHeaderMetadata(cell) {
                if (($.metadata) && ($(cell).metadata().sorter === false)) {
                    return true;
                };
                return false;
            }

            function checkHeaderOptions(table, i) {
                if ((table.config.headers[i]) && (table.config.headers[i].sorter === false)) {
                    return true;
                };
                return false;
            }
			
			 function checkHeaderOptionsSortingLocked(table, i) {
                if ((table.config.headers[i]) && (table.config.headers[i].lockedOrder)) return table.config.headers[i].lockedOrder;
                return false;
            }
			
            function applyWidget(table) {
                var c = table.config.widgets;
                var l = c.length;
                for (var i = 0; i < l; i++) {

                    getWidgetById(c[i]).format(table);
                }

            }

            function getWidgetById(name) {
                var l = widgets.length;
                for (var i = 0; i < l; i++) {
                    if (widgets[i].id.toLowerCase() == name.toLowerCase()) {
                        return widgets[i];
                    }
                }
            };

            function formatSortingOrder(v) {
                if (typeof(v) != "Number") {
                    return (v.toLowerCase() == "desc") ? 1 : 0;
                } else {
                    return (v == 1) ? 1 : 0;
                }
            }

            function isValueInArray(v, a) {
                var l = a.length;
                for (var i = 0; i < l; i++) {
                    if (a[i][0] == v) {
                        return true;
                    }
                }
                return false;
            }

            function setHeadersCss(table, $headers, list, css) {
                // remove all header information
                $headers.removeClass(css[0]).removeClass(css[1]);

                var h = [];
                $headers.each(function (offset) {
                    if (!this.sortDisabled) {
                        h[this.column] = $(this);
                    }
                });

                var l = list.length;
                for (var i = 0; i < l; i++) {
                    h[list[i][0]].addClass(css[list[i][1]]);
                }
            }

            function fixColumnWidth(table, $headers) {
                var c = table.config;
                if (c.widthFixed) {
                    var colgroup = $('<colgroup>');
                    $("tr:first td", table.tBodies[0]).each(function () {
                        colgroup.append($('<col>').css('width', $(this).width()));
                    });
                    $(table).prepend(colgroup);
                };
            }

            function updateHeaderSortCount(table, sortList) {
                var c = table.config,
                    l = sortList.length;
                for (var i = 0; i < l; i++) {
                    var s = sortList[i],
                        o = c.headerList[s[0]];
                    o.count = s[1];
                    o.count++;
                }
            }

            /* sorting methods */

            function multisort(table, sortList, cache) {

                if (table.config.debug) {
                    var sortTime = new Date();
                }

                var dynamicExp = "var sortWrapper = function(a,b) {",
                    l = sortList.length;

                // TODO: inline functions.
                for (var i = 0; i < l; i++) {

                    var c = sortList[i][0];
                    var order = sortList[i][1];
                    // var s = (getCachedSortType(table.config.parsers,c) == "text") ?
                    // ((order == 0) ? "sortText" : "sortTextDesc") : ((order == 0) ?
                    // "sortNumeric" : "sortNumericDesc");
                    // var s = (table.config.parsers[c].type == "text") ? ((order == 0)
                    // ? makeSortText(c) : makeSortTextDesc(c)) : ((order == 0) ?
                    // makeSortNumeric(c) : makeSortNumericDesc(c));
                    var s = (table.config.parsers[c].type == "text") ? ((order == 0) ? makeSortFunction("text", "asc", c) : makeSortFunction("text", "desc", c)) : ((order == 0) ? makeSortFunction("numeric", "asc", c) : makeSortFunction("numeric", "desc", c));
                    var e = "e" + i;

                    dynamicExp += "var " + e + " = " + s; // + "(a[" + c + "],b[" + c
                    // + "]); ";
                    dynamicExp += "if(" + e + ") { return " + e + "; } ";
                    dynamicExp += "else { ";

                }

                // if value is the same keep orignal order
                var orgOrderCol = cache.normalized[0].length - 1;
                dynamicExp += "return a[" + orgOrderCol + "]-b[" + orgOrderCol + "];";

                for (var i = 0; i < l; i++) {
                    dynamicExp += "}; ";
                }

                dynamicExp += "return 0; ";
                dynamicExp += "}; ";

                if (table.config.debug) {
                    benchmark("Evaling expression:" + dynamicExp, new Date());
                }

                eval(dynamicExp);

                cache.normalized.sort(sortWrapper);

                if (table.config.debug) {
                    benchmark("Sorting on " + sortList.toString() + " and dir " + order + " time:", sortTime);
                }

                return cache;
            };

            function makeSortFunction(type, direction, index) {
                var a = "a[" + index + "]",
                    b = "b[" + index + "]";
                if (type == 'text' && direction == 'asc') {
                    return "(" + a + " == " + b + " ? 0 : (" + a + " === null ? Number.POSITIVE_INFINITY : (" + b + " === null ? Number.NEGATIVE_INFINITY : (" + a + " < " + b + ") ? -1 : 1 )));";
                } else if (type == 'text' && direction == 'desc') {
                    return "(" + a + " == " + b + " ? 0 : (" + a + " === null ? Number.POSITIVE_INFINITY : (" + b + " === null ? Number.NEGATIVE_INFINITY : (" + b + " < " + a + ") ? -1 : 1 )));";
                } else if (type == 'numeric' && direction == 'asc') {
                    return "(" + a + " === null && " + b + " === null) ? 0 :(" + a + " === null ? Number.POSITIVE_INFINITY : (" + b + " === null ? Number.NEGATIVE_INFINITY : " + a + " - " + b + "));";
                } else if (type == 'numeric' && direction == 'desc') {
                    return "(" + a + " === null && " + b + " === null) ? 0 :(" + a + " === null ? Number.POSITIVE_INFINITY : (" + b + " === null ? Number.NEGATIVE_INFINITY : " + b + " - " + a + "));";
                }
            };

            function makeSortText(i) {
                return "((a[" + i + "] < b[" + i + "]) ? -1 : ((a[" + i + "] > b[" + i + "]) ? 1 : 0));";
            };

            function makeSortTextDesc(i) {
                return "((b[" + i + "] < a[" + i + "]) ? -1 : ((b[" + i + "] > a[" + i + "]) ? 1 : 0));";
            };

            function makeSortNumeric(i) {
                return "a[" + i + "]-b[" + i + "];";
            };

            function makeSortNumericDesc(i) {
                return "b[" + i + "]-a[" + i + "];";
            };

            function sortText(a, b) {
                if (table.config.sortLocaleCompare) return a.localeCompare(b);
                return ((a < b) ? -1 : ((a > b) ? 1 : 0));
            };

            function sortTextDesc(a, b) {
                if (table.config.sortLocaleCompare) return b.localeCompare(a);
                return ((b < a) ? -1 : ((b > a) ? 1 : 0));
            };

            function sortNumeric(a, b) {
                return a - b;
            };

            function sortNumericDesc(a, b) {
                return b - a;
            };

            function getCachedSortType(parsers, i) {
                return parsers[i].type;
            }; /* public methods */
            this.construct = function (settings) {
                return this.each(function () {
                    // if no thead or tbody quit.
                    if (!this.tHead || !this.tBodies) return;
                    // declare
                    var $this, $document, $headers, cache, config, shiftDown = 0,
                        sortOrder;
                    // new blank config object
                    this.config = {};
                    // merge and extend.
                    config = $.extend(this.config, $.tablesorter.defaults, settings);
                    // store common expression for speed
                    $this = $(this);
                    // save the settings where they read
                    $.data(this, "tablesorter", config);
                    // build headers
                    $headers = buildHeaders(this);
                    // try to auto detect column type, and store in tables config
                    this.config.parsers = buildParserCache(this, $headers);
                    // build the cache for the tbody cells
                    cache = buildCache(this);
                    // get the css class names, could be done else where.
                    var sortCSS = [config.cssDesc, config.cssAsc];
                    // fixate columns if the users supplies the fixedWidth option
                    fixColumnWidth(this);
                    // apply event handling to headers
                    // this is to big, perhaps break it out?
                    $headers.click(

                    function (e) {
                        var totalRows = ($this[0].tBodies[0] && $this[0].tBodies[0].rows.length) || 0;
                        if (!this.sortDisabled && totalRows > 0) {
                            // Only call sortStart if sorting is
                            // enabled.
                            $this.trigger("sortStart");
                            // store exp, for speed
                            var $cell = $(this);
                            // get current column index
                            var i = this.column;
                            // get current column sort order
                            this.order = this.count++ % 2;
							// always sort on the locked order.
							if(this.lockedOrder) this.order = this.lockedOrder;
							
							// user only whants to sort on one
                            // column
                            if (!e[config.sortMultiSortKey]) {
                                // flush the sort list
                                config.sortList = [];
                                if (config.sortForce != null) {
                                    var a = config.sortForce;
                                    for (var j = 0; j < a.length; j++) {
                                        if (a[j][0] != i) {
                                            config.sortList.push(a[j]);
                                        }
                                    }
                                }
                                // add column to sort list
                                config.sortList.push([i, this.order]);
                                // multi column sorting
                            } else {
                                // the user has clicked on an all
                                // ready sortet column.
                                if (isValueInArray(i, config.sortList)) {
                                    // revers the sorting direction
                                    // for all tables.
                                    for (var j = 0; j < config.sortList.length; j++) {
                                        var s = config.sortList[j],
                                            o = config.headerList[s[0]];
                                        if (s[0] == i) {
                                            o.count = s[1];
                                            o.count++;
                                            s[1] = o.count % 2;
                                        }
                                    }
                                } else {
                                    // add column to sort list array
                                    config.sortList.push([i, this.order]);
                                }
                            };
                            setTimeout(function () {
                                // set css for headers
                                setHeadersCss($this[0], $headers, config.sortList, sortCSS);
                                appendToTable(
	                                $this[0], multisort(
	                                $this[0], config.sortList, cache)
								);
                            }, 1);
                            // stop normal event by returning false
                            return false;
                        }
                        // cancel selection
                    }).mousedown(function () {
                        if (config.cancelSelection) {
                            this.onselectstart = function () {
                                return false;
                            };
                            return false;
                        }
                    });
                    // apply easy methods that trigger binded events
                    $this.bind("update", function () {
                        var me = this;
                        setTimeout(function () {
                            // rebuild parsers.
                            me.config.parsers = buildParserCache(
                            me, $headers);
                            // rebuild the cache map
                            cache = buildCache(me);
                        }, 1);
                    }).bind("updateCell", function (e, cell) {
                        var config = this.config;
                        // get position from the dom.
                        var pos = [(cell.parentNode.rowIndex - 1), cell.cellIndex];
                        // update cache
                        cache.normalized[pos[0]][pos[1]] = config.parsers[pos[1]].format(
                        getElementText(config, cell), cell);
                    }).bind("sorton", function (e, list) {
                        $(this).trigger("sortStart");
                        config.sortList = list;
                        // update and store the sortlist
                        var sortList = config.sortList;
                        // update header count index
                        updateHeaderSortCount(this, sortList);
                        // set css for headers
                        setHeadersCss(this, $headers, sortList, sortCSS);
                        // sort the table and append it to the dom
                        appendToTable(this, multisort(this, sortList, cache));
                    }).bind("appendCache", function () {
                        appendToTable(this, cache);
                    }).bind("applyWidgetId", function (e, id) {
                        getWidgetById(id).format(this);
                    }).bind("applyWidgets", function () {
                        // apply widgets
                        applyWidget(this);
                    });
                    if ($.metadata && ($(this).metadata() && $(this).metadata().sortlist)) {
                        config.sortList = $(this).metadata().sortlist;
                    }
                    // if user has supplied a sort list to constructor.
                    if (config.sortList.length > 0) {
                        $this.trigger("sorton", [config.sortList]);
                    }
                    // apply widgets
                    applyWidget(this);
                });
            };
            this.addParser = function (parser) {
                var l = parsers.length,
                    a = true;
                for (var i = 0; i < l; i++) {
                    if (parsers[i].id.toLowerCase() == parser.id.toLowerCase()) {
                        a = false;
                    }
                }
                if (a) {
                    parsers.push(parser);
                };
            };
            this.addWidget = function (widget) {
                widgets.push(widget);
            };
            this.formatFloat = function (s) {
                var i = parseFloat(s);
                return (isNaN(i)) ? 0 : i;
            };
            this.formatInt = function (s) {
                var i = parseInt(s);
                return (isNaN(i)) ? 0 : i;
            };
            this.isDigit = function (s, config) {
                // replace all an wanted chars and match.
                return /^[-+]?\d*$/.test($.trim(s.replace(/[,.']/g, '')));
            };
            this.clearTableBody = function (table) {
                if ($.browser.msie) {
                    function empty() {
                        while (this.firstChild)
                        this.removeChild(this.firstChild);
                    }
                    empty.apply(table.tBodies[0]);
                } else {
                    table.tBodies[0].innerHTML = "";
                }
            };
        }
    });

    // extend plugin scope
    $.fn.extend({
        tablesorter: $.tablesorter.construct
    });

    // make shortcut
    var ts = $.tablesorter;

    // add default parsers
    ts.addParser({
        id: "text",
        is: function (s) {
            return true;
        }, format: function (s) {
            return $.trim(s.toLocaleLowerCase());
        }, type: "text"
    });

    ts.addParser({
        id: "digit",
        is: function (s, table) {
            var c = table.config;
            return $.tablesorter.isDigit(s, c);
        }, format: function (s) {
            return $.tablesorter.formatFloat(s);
        }, type: "numeric"
    });

    ts.addParser({
        id: "currency",
        is: function (s) {
            return /^[£$€?.]/.test(s);
        }, format: function (s) {
            return $.tablesorter.formatFloat(s.replace(new RegExp(/[£$€]/g), ""));
        }, type: "numeric"
    });

    ts.addParser({
        id: "ipAddress",
        is: function (s) {
            return /^\d{2,3}[\.]\d{2,3}[\.]\d{2,3}[\.]\d{2,3}$/.test(s);
        }, format: function (s) {
            var a = s.split("."),
                r = "",
                l = a.length;
            for (var i = 0; i < l; i++) {
                var item = a[i];
                if (item.length == 2) {
                    r += "0" + item;
                } else {
                    r += item;
                }
            }
            return $.tablesorter.formatFloat(r);
        }, type: "numeric"
    });

    ts.addParser({
        id: "url",
        is: function (s) {
            return /^(https?|ftp|file):\/\/$/.test(s);
        }, format: function (s) {
            return jQuery.trim(s.replace(new RegExp(/(https?|ftp|file):\/\//), ''));
        }, type: "text"
    });

    ts.addParser({
        id: "isoDate",
        is: function (s) {
            return /^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(s);
        }, format: function (s) {
            return $.tablesorter.formatFloat((s != "") ? new Date(s.replace(
            new RegExp(/-/g), "/")).getTime() : "0");
        }, type: "numeric"
    });

    ts.addParser({
        id: "percent",
        is: function (s) {
            return /\%$/.test($.trim(s));
        }, format: function (s) {
            return $.tablesorter.formatFloat(s.replace(new RegExp(/%/g), ""));
        }, type: "numeric"
    });

    ts.addParser({
        id: "usLongDate",
        is: function (s) {
            return s.match(new RegExp(/^[A-Za-z]{3,10}\.? [0-9]{1,2}, ([0-9]{4}|'?[0-9]{2}) (([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(AM|PM)))$/));
        }, format: function (s) {
            return $.tablesorter.formatFloat(new Date(s).getTime());
        }, type: "numeric"
    });

    ts.addParser({
        id: "shortDate",
        is: function (s) {
            return /\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}/.test(s);
        }, format: function (s, table) {
            var c = table.config;
            s = s.replace(/\-/g, "/");
            if (c.dateFormat == "us") {
                // reformat the string in ISO format
                s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/, "$3/$1/$2");
            } else if (c.dateFormat == "uk") {
                // reformat the string in ISO format
                s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/, "$3/$2/$1");
            } else if (c.dateFormat == "dd/mm/yy" || c.dateFormat == "dd-mm-yy") {
                s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2})/, "$1/$2/$3");
            }
            return $.tablesorter.formatFloat(new Date(s).getTime());
        }, type: "numeric"
    });
    ts.addParser({
        id: "time",
        is: function (s) {
            return /^(([0-2]?[0-9]:[0-5][0-9])|([0-1]?[0-9]:[0-5][0-9]\s(am|pm)))$/.test(s);
        }, format: function (s) {
            return $.tablesorter.formatFloat(new Date("2000/01/01 " + s).getTime());
        }, type: "numeric"
    });
    ts.addParser({
        id: "metadata",
        is: function (s) {
            return false;
        }, format: function (s, table, cell) {
            var c = table.config,
                p = (!c.parserMetadataName) ? 'sortValue' : c.parserMetadataName;
            return $(cell).metadata()[p];
        }, type: "numeric"
    });
    // add default widgets
    ts.addWidget({
        id: "zebra",
        format: function (table) {
            if (table.config.debug) {
                var time = new Date();
            }
            var $tr, row = -1,
                odd;
            // loop through the visible rows
            $("tr:visible", table.tBodies[0]).each(function (i) {
                $tr = $(this);
                // style children rows the same way the parent
                // row was styled
                if (!$tr.hasClass(table.config.cssChildRow)) row++;
                odd = (row % 2 == 0);
                $tr.removeClass(
                table.config.widgetZebra.css[odd ? 0 : 1]).addClass(
                table.config.widgetZebra.css[odd ? 1 : 0]);
            });
            if (table.config.debug) {
                $.tablesorter.benchmark("Applying Zebra widget", time);
            }
        }
    });
})(jQuery);

/********************************** Version 5.2 Build 33 ********************************/
/********************************** Copyright arvato systems 2008-2010*******************/
/********************************** Part of BIc Media www.bic-media.com******************/

/********************************** a few constants *************************************/
var DEFAULT_URL = "http://www.bic-media.com/dmrs/";
var DEFAULT_CONFIG_URL = "http://www.bic-media.com/dmrs/widget/"; //Configurationsdateien.
var DEFAULT_SWF_URL = "http://www.bic-media.com/dmrs/widget/";//Parameter der Location des zu testenden SWF Films.
var DEFAULT_FILENAME = "DMRWidget.swf";
var DEFAULT_COVER_URL ="http://www.bic-media.com/dmrs/cover.do?isbn=";
var DEFAULT_WIDGET_URL = "http://www.bic-media.com/dmrs/widget.do";
var DEFAULT_WIDTH = 200;
var DEFAULT_HEIGHT = 375;
var DEFAULT_WIDTH_DOUBLEPAGE = 300;
var DEFAULT_HEIGHT_DOUBLEPAGE = 325;
var noshop=false;
var dontpost=true;
//we need to store the params in a global hashmap with the isbn as key to be able to have more than one widget on a page
if (typeof DMRParams == 'undefined') {
	DMRParams = new Array();
}


/********************************** callback method stubs - implement as needed *************************************/
function openDMRWidget(identifier, author, title) {
}
function closeDMRWidget(identifier, author, title) {
}


/********************************** Mustard Lab's detect flash methods start here *************************************/
var DMRUserAgent = navigator.userAgent.toLowerCase();
if ( (DMRUserAgent.indexOf('msie') != -1) && (DMRUserAgent.indexOf('win') != -1) && (DMRUserAgent.indexOf('opera') == -1) ) {
	document.writeln('<script language="VBscript">');
	document.writeln('Function detectActiveXControl(activeXControlName)');
	document.writeln('  on error resume next');
	document.writeln('  detectActiveXControl = False');
	document.writeln('  detectActiveXControl = IsObject(CreateObject(activeXControlName))');
	document.writeln('End Function');
	document.writeln('</scr' + 'ipt>');
}
function getFlashVersion(){
	var installedVersion = 0;
	if ( (DMRUserAgent.indexOf('msie') != -1) && (DMRUserAgent.indexOf('win') != -1) && (DMRUserAgent.indexOf('opera') == -1) ) {
		for (var i=3; i<10; i++){
			if(detectActiveXControl("ShockwaveFlash.ShockwaveFlash."+i) == true) installedVersion = i;
		}
	} else {
		if (navigator.plugins["Shockwave Flash"]) {
			var pluginDesc = navigator.plugins["Shockwave Flash"].description;
			// 16 is the length of the String "Shockwave Flash "; beginnig from there we search for the dot 
			installedVersion = parseInt( pluginDesc.substr (16 , ( pluginDesc.indexOf (".", 16) - 16) ) );
		}
		if(DMRUserAgent.indexOf("webtv") != -1) installedVersion = 3;  
	}
	return installedVersion;
}


/********************************** DMR Widget *************************************/
function DMRWidget(isbn, swfArgs){
	if (swfArgs == null || typeof swfArgs == 'undefined')  swfArgs = '';
	//we need to store the params in a global hashmap with the isbn as key to be able to have more than one widget on a page
	DMRParams[isbn]=swfArgs;
	flashInst = getFlashVersion();
	if(flashInst >= 8){
		var myOutput = writeSwf(isbn,false,'','','', true);
		myOutput=myOutput.replace(/&isbn=\w+-\w+-\w+-\w+-\w+&page=/g, "&page=");
		// alert(myOutput);
		return myOutput;
	  }else{
		var coverImg = DEFAULT_COVER_URL+isbn+"&width=200";
	    var ret="<div id='noflash' style='text-align: center;'>";
	    var ret="<img src='"+coverImg+"' /><br/><br/>To browse and search this book, <br/>please upgrade to the latest version <br/>of the free <a href='http://www.adobe.com/go/getflashplayer' target='_blank'>Adobe Flash Player</a>.</div>";
	  
	    return ret;
	  }
}

function writeSwf (isbn,large,searchStr,matchesStr,jumpTo, useTransparentWMode)
{
	var myIsbn = isbn;
	var isLarge = large;

	if (isParam('https', isbn)) { //if the https parameter was set - rewrite the urls to https
		DEFAULT_CONFIG_URL = replaceStr(DEFAULT_CONFIG_URL, "http://", "https://");
		DEFAULT_COVER_URL = replaceStr(DEFAULT_COVER_URL, "http://", "https://");
		DEFAULT_SWF_URL = replaceStr(DEFAULT_SWF_URL, "http://", "https://");
	}		
	var w = getParam('width', isbn);
	var h = getParam('height', isbn);
	var sUrl = getParam('serviceUrl', isbn);
	var cUrl = getParam('configUrl', isbn);
	
	var sPage = '';
	var mySearchStr = '';
	var myMatchesStr = '';
	var myJumpTo = '';	

	if (isLarge == true){
		sPage = largeStartingPage;
		mySearchStr = searchStr;
		myMatchesStr = matchesStr;
		myJumpTo = jumpTo;
	} else{
		sPage = getParam('startingPage', isbn);
	}
	var width = checkWidth(w, myIsbn);
	var height = checkHeight(h, myIsbn);
	//var serviceUrl = checkServiceUrl(sUrl);
	var configUrl = checkConfigUrl(cUrl);
	var startingPage = checkStartingPage(sPage);
	var myPageHost = document.location.hostname;	
	var myLocalHost = window.location.protocol;	
	if (isEmptyOrUndefined(myPageHost)) {myPageHost='local';}	
	if (isEmptyOrUndefined(myLocalHost)) {myLocalHost='';}			

	//must
	var must = [];
	//I have to add the prefix DMR to be able to differentiate my properties of this object from the ones assigned to Object.prototype
	must['DMRisbn'] = isbn;
	must['DMRwidth'] = width;			
	must['DMRheight'] = height;
	must['DMRpageHost'] = myPageHost;	
	must['DMRLocalHost'] = myLocalHost;	
	if(!isEmptyOrUndefined(myJumpTo)) must['DMRjumpTo'] = myJumpTo;						
	must['DMRconfigUrl'] = configUrl;
	must['DMRstartingPage'] = startingPage;
	must['DMRsearchStr'] = mySearchStr;
	must['DMRmatchesStr'] = myMatchesStr;	

	var swfParams = getSwfParams(must, isbn);
    var swfLocation = DEFAULT_SWF_URL+DEFAULT_FILENAME; 
	var myString = "";
	scale = "scale";
    if (isLarge){
		width = "100%";
		height = "100%";
		scale = "exactfit";
	}

	myString +=("<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'");
			myString +=("id='DMRWidget' width='"+width+"' height='"+height+"' align='left' ");
			myString +=("codebase='http" + (isParam('https', isbn)?"s":"") + "://www.adobe.com/go/getflashplayer'>");
			myString +=("<param name='movie' value='"+swfLocation+"' />"); 
			myString +=("<param name='quality' value='high' />");
			myString +=("<param name='FlashVars' value='"+swfParams+" '/>");
			myString +=("<param name='allowScriptAccess' value='always' />");
			myString +=("<param name='allowFullScreen' value='true' />");
			if (useTransparentWMode) myString +=("<param name='wmode' value='transparent' />");
			myString +=("<param name='scale' value='"+scale+"' />");
			myString +=("<param name='salign' value='lt' />");
			myString +=("<embed src='"+swfLocation+"?quality=high' bgcolor='#ffffff'");
			myString +=("width='"+width+"' height='"+height+"' name='DMRWidget' align='left' ");
			myString +=("play='true' ");
			myString +=("loop='false' ");
			myString +=("quality='high' ");
			myString +=("scale='"+scale+"'");
			myString +=("FlashVars='"+swfParams+"'");			
			myString +=("salign='lt' ");
			myString +=("allowScriptAccess='always' ");
			if (useTransparentWMode) myString +=("wmode='transparent' ");			
			myString +=("allowFullScreen='true' ");			
			myString +=("type='application/x-shockwave-flash' ");
			myString +=("pluginspage='http://www.adobe.com/go/getflashplayer'> ");
			myString +=("</embed>");
	myString +=("</object>");
	return myString;
}

/* Chrome-specific pop-up variant that may be the better pop-up solution also for other browsers */
function chromePopup(swf, varString) {
    var beginIdxString = "name='FlashVars' value='";
    var endIdxString = "'/>";
    var beginIdx = swf.indexOf(beginIdxString);
    var endIdx = swf.indexOf(endIdxString);
    var flashVars = swf.substring(beginIdx + 24, endIdx);

    var widgetParamUri = DEFAULT_WIDGET_URL + "?" + flashVars;
    var popup = window.open(widgetParamUri, "Preview", varString);
}

function openWin(startingPage,w,h,author,title,searchStr,matchesStr,isbn,jumpTo) {
	try {openDMRWidget(isbn,author,title);} catch (e) {}
	largeStartingPage = startingPage;
	
	
	//Extention for DMR-644 
	//Function ready for Calls from DMRCarousel Widget
	if (jumpTo=="bookCarousel"){
	    jumpTo = "book";
	}
	
	var swf = writeSwf(isbn,true,searchStr,matchesStr,jumpTo, false);
	var myLeft =  0;
	var myTop =  0;
	try {
  		myLeft =  (screen.availWidth-w)/2;
		myTop =  (screen.availHeight-h)/2;		
	} catch(e) {}       
	var varString = "height="+h+",width="+w+",top=" + myTop + ",left=" + myLeft + ",resizable=1,status=0";	
	if (navigator.userAgent.indexOf("Chrome") != -1) {
        chromePopup(swf, varString);
    } else {
    var parse=new String("myDMRWidgetWindow"+isbn);
    var OpenWindow = window.open("", "myDMRWidgetWindow", varString);
	OpenWindow.document.write("<HTML>");
	OpenWindow.document.write("<TITLE>"+author+" - "+title+"</TITLE>");
	OpenWindow.document.write("<link href='"+DEFAULT_COVER_URL+isbn+"&width=200' rel='image_src'/>");
	OpenWindow.document.write("<script type='text/javascript'>");
	OpenWindow.document.write("function closeDMRWidget() {try {opener.closeDMRWidget('"+isbn+"','"+author+"','"+title+"');} catch (e) {}}");	
	OpenWindow.document.write("</script>");		
	OpenWindow.document.write("<BODY onunload='closeDMRWidget()' BGCOLOR='ffffff' leftmargin='0' rightmargin='0' bottommargin='0' topmargin='0'>");
	OpenWindow.document.write("<CENTER>");
	OpenWindow.document.write(swf);
	OpenWindow.document.write("</CENTER>");
	OpenWindow.document.write("</BODY>");
	OpenWindow.document.write("</HTML>");
	OpenWindow.focus();
	}
}

function openWindow(url, target, myWidth, myHeight) {
	try {var myTop = screen.availHeight/2-myHeight/2; var myLeft = screen.availWidth/2-myWidth/2;} catch(e) {var myTop=0; var myLeft=0;}        
	var theWindow = window.open(url, target, "width=" + myWidth + ",height=" + myHeight + ",top=" + myTop + ",left="+ myLeft + ",status=no,toolbar=no,scrollbars=yes,menubar=no");				      
	theWindow.focus();
}

function checkWidth (width, isbn){
	var defaultWidth = DEFAULT_WIDTH;
	if (!isEmptyOrUndefined(isbn) && !isEmptyOrUndefined(getParam('layout', isbn)) && getParam('layout', isbn) == 'doublepage') {
		defaultWidth = DEFAULT_WIDTH_DOUBLEPAGE;		
	}

	var w = width;
	if (w == 0 || isNaN(w)) w = defaultWidth;
	return w;
}

function checkHeight (height, isbn){
	var defaultHeight = DEFAULT_HEIGHT;
	if (!isEmptyOrUndefined(isbn) && !isEmptyOrUndefined(getParam('layout', isbn)) && getParam('layout', isbn) == 'doublepage') {
		defaultHeight = DEFAULT_HEIGHT_DOUBLEPAGE;		
	}
	
	var h = height;
	if (h == 0 || isNaN(h)) h = defaultHeight;
	return h;
}

function checkConfigUrl (ConfigUrl){
	var cU = ConfigUrl;
	if (!cU) cU = DEFAULT_CONFIG_URL;
	
	return cU;
}

function checkStartingPage (startPage){
	var n = 1;
	if (isNaN(startPage) || startPage < 1) return n;
		return startPage;
}

function getParam (paramStr, isbn){
	var arg = DMRParams[isbn].split(',');
	var len = arg.length;
	var outputVar="";
	for (a=0;a<len;a++){
		var par = arg[a].split('=');
		if (par[0] == paramStr) return par[1];
	}
	return false;
}

//returns true if the parameter is set to true or yes
function isParam(paramStr, isbn) {
   try {
        return (getParam(paramStr, isbn)=='true' || getParam(paramStr, isbn)=='yes' || getParam(paramStr, isbn)=='True' || getParam(paramStr, isbn)=='Yes');
        } 
   catch(e) {
         return false;
   }
}

function getSwfParams (obj, isbn) {	
	var str = "";
	var alreadySetParameter = new Array();
	//split configured parameters at comma
	var arg = DMRParams[isbn].split(',');
	var len = arg.length;
	//iterate over all configured parameters
	for (a=0;a<len;a++){
		//split name-value pairs
		var par = arg[a].split('=');
		//get parameter name
		var parameterName = par[0];
		var parLen = par.length;
		//get the parameter value
		var parameterValue = par[1];
		//if there was one or more = in the value these will be splitted into further array elements, which we need to add these to the parameterValue
		if (parLen > 2){
			for (var i=2 ;i<parLen;i++){
				//replace possible & with ___ because they would crash the parameter string. Flash will later replace this again
				parameterValue += "="+replaceStr(par[i],'&','____');
			}
		}
		//check if there are default values in the must-Hash; Those will overwrite the configured ones
		for (var i in obj){
			//regard only properties of this object flagged with the prefix DMR
			if (i.length > 3 && i.indexOf("DMR")==0) {
				i = i.substring(3);		
				if (i==parameterName) {
					parameterValue = obj["DMR" + i];
				}
			}
		}
		alreadySetParameter[parameterName] = true;
		str += parameterName+"="+parameterValue+"&";
	}
	
	for (var i in obj){	
		//regard only properties of this object flagged with the prefix DMR
		if (i.length > 3 && i.indexOf("DMR")==0) {
			i = i.substring(3);
			if (!alreadySetParameter[i]) {
				str += i+"="+obj["DMR" + i]+"&";	
			}
		}
	}
	
	//Add own Adress
	//str = str + "myAdress=" + window.location + "&";
	
	return str;
}

/********************************** DMR Carousel *************************************/
function DMRCarousel(params){
	if (params == null || typeof params == 'undefined')  params = {};
	flashInst = getFlashVersion();
	if(flashInst >= 9){
		var flashVars = "";
		for (var param in params) {		
		    flashVars=flashVars + param + "=" + params[param] + "&";	
		}			    
		AC_FL_RunContent(
			"src", DEFAULT_SWF_URL + "DMRCarousel",
			"width", isEmptyOrUndefined(params['width'])?500:params['width'],
			"height", isEmptyOrUndefined(params['height'])?400:params['height'],
			"align", "left",
			"id", "DMRCarouselWidget",
			"quality", "high",
			"bgcolor", isEmptyOrUndefined(params['bgcolor'])?"#869ca7":params['bgcolor'],
			"name", "DMRCarouselWidget",
			"flashvars", flashVars,
			"allowScriptAccess","always",
			"type", "application/x-shockwave-flash",
			"pluginspage", "http://www.adobe.com/go/getflashplayer"
		);
	  }else{
	    document.write('<div id="noflash" style="text-align: center;">');
	    document.write("To browse these books, <br/>please upgrade to the latest version <br/>of the free <a href='http://www.adobe.com/go/getflashplayer' target='_blank'>Adobe Flash Player</a>.</div>");
	  }
}

/********************************** DMR FishEye *************************************/
function DMRFishEye(params){
	if (params == null || typeof params == 'undefined')  params = {};
	flashInst = getFlashVersion();
	if(flashInst >= 9){
		var flashVars = "";
		for (var param in params) {		
		    flashVars=flashVars + param + "=" + params[param] + "&";	
		}			    
		AC_FL_RunContent(
			"src", DEFAULT_URL + "widget/DMRFishEyeWidget",
			"width", isEmptyOrUndefined(params['width'])?650:params['width'],
			"height", isEmptyOrUndefined(params['height'])?200:params['height'],
			"align", "left",
			"id", "DMRFishEyeWidget",
			"quality", "high",
			"bgcolor", isEmptyOrUndefined(params['bgcolor'])?"#869ca7":params['bgcolor'],
			"name", "DMRFishEyeWidget",
			"flashvars", flashVars,
			"allowScriptAccess","always",
			"type", "application/x-shockwave-flash",
			"pluginspage", "http://www.adobe.com/go/getflashplayer"
		);
	  }else{
	    document.write('<div id="noflash" style="text-align: center;">');
	    document.write("To browse these books, <br/>please upgrade to the latest version <br/>of the free <a href='http://www.adobe.com/go/getflashplayer' target='_blank'>Adobe Flash Player</a>.</div>");
	  }
}


/********************************** utilities *************************************/
function replaceStr(str, oldStr, newStr) {
	regExp = new RegExp(oldStr, "gi");
	results = str.replace(regExp, newStr);
	return results;
}

function isEmptyOrUndefined(item) {
	if (item == null || typeof item == 'undefined' || item == '' || item == 'undefined') {return true;} else {return false;}
}

function getDMRCarousel() {
	var carousel;
	try {carousel = window.DMRCarouselWidget==null?document.DMRCarouselWidget:window.DMRCarouselWidget;} catch(e) {}
	return carousel;
}


function getDMRFishEye() {
	var fishEye;
	try {fishEye = window.DMRFishEyeWidget==null?document.DMRFishEyeWidget:window.DMRFishEyeWidget;} catch(e) {}
	return fishEye;
}
      
	

/********************************** AC_OETags.js *************************************/	
// Flash Player Version Detection - Rev 1.5
// Detect Client Browser type
// Copyright(c) 2005-2006 Adobe Macromedia Software, LLC. All rights reserved.
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion()
{
	var version;
	var axo;
	var e;

	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}

	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
			
			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful. 
			
			// default to the first public version
			version = "WIN 6,0,21,0";

			// throws if AllowScripAccess does not exist (introduced in 6.0r47)		
			axo.AllowScriptAccess = "always";

			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");

		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}
	
	return version;
}

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;
	
	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;			
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			if ( descArray[3] != "" ) {
				tempArrayMinor = descArray[3].split("r");
			} else {
				tempArrayMinor = descArray[4].split("r");
			}
			var versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}	
	return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];

        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}

function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?'); 
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs) 
{ 
    var str = '';
    if (isIE && isWin && !isOpera)
    {
  		str += '<object ';
  		for (var i in objAttrs)
  			str += i + '="' + objAttrs[i] + '" ';
  		for (var i in params)
  			str += '><param name="' + i + '" value="' + params[i] + '" /> ';
  		str += '></object>';
    } else {
  		str += '<embed ';
  		for (var i in embedAttrs)
  			str += i + '="' + embedAttrs[i] + '" ';
  		str += '> </embed>';
    }

    document.write(str);
}

function AC_FL_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    

    switch (currArg){	
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblClick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "id":
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}

/*!
 * Galleria v 1.1.4 2010-05-30
 * http://galleria.aino.se
 *
 * Copyright (c) 2010, Aino
 * Licensed under the MIT license.
 */

(function() {

var initializing = false,
    fnTest = /xyz/.test(function(){xyz;}) ? /\b__super\b/ : /.*/,
    Class = function(){},
    window = this;

Class.extend = function(prop) {
    var __super = this.prototype;
    initializing = true;
    var proto = new this();
    initializing = false;
    for (var name in prop) {
        if (name) {
            proto[name] = typeof prop[name] == "function" && 
                typeof __super[name] == "function" && fnTest.test(prop[name]) ? 
                (function(name, fn) { 
                    return function() { 
                        var tmp = this.__super; 
                        this.__super = __super[name]; 
                        var ret = fn.apply(this, arguments);       
                        this.__super = tmp; 
                        return ret; 
                    }; 
                })(name, prop[name]) : prop[name]; 
        } 
    }

    function Class() {
        if ( !initializing && this.__constructor ) {
            this.__constructor.apply(this, arguments);
        }
    }
    Class.prototype = proto;
    Class.constructor = Class;
    Class.extend = arguments.callee;
    return Class;
};

var Base = Class.extend({
    loop : function( elem, fn) {
        var scope = this;
        if (typeof elem == 'number') {
            elem = new Array(elem);
        }
        jQuery.each(elem, function() {
            fn.call(scope, arguments[1], arguments[0]);
        });
        return elem;
    },
    create : function( elem, className ) {
        elem = elem || 'div';
        var el = document.createElement(elem);
        if (className) {
            el.className = className;
        }
        return el;
    },
    getElements : function( selector ) {
        var elems = {};
        this.loop( jQuery(selector), this.proxy(function( elem ) {
            this.push(elem, elems);
        }));
        return elems;
    },
    setStyle : function( elem, css ) {
        jQuery(elem).css(css);
        return this;
    },
    cssText : function( string ) {
        var style = document.createElement('style');
        this.getElements('head')[0].appendChild(style);
        if (style.styleSheet) { // IE
            style.styleSheet.cssText = string;
        } else {
            var cssText = document.createTextNode(string);
            style.appendChild(cssText);
        }
        return this;
    },
    cssFile : function(src) {
        var link = document.createElement('link');
        link.media = 'all';
        link.rel = 'stylesheet';
        link.href = src;
        document.getElementsByTagName('head')[0].appendChild(link);
    },
    moveOut : function( elem ) {
        return this.setStyle(elem, {
            position: 'absolute',
            left: '-10000px'
        });
    },
    moveIn : function( elem ) {
        return this.setStyle(elem, {
            left: '0'
        }); 
    },
    reveal : function( elem ) {
        return jQuery( elem ).show();
    },
    hide : function( elem ) {
        return jQuery( elem ).hide();
    },
    mix : function( obj, ext ) {
        return jQuery.extend(obj, ext);
    },
    proxy : function( fn, scope ) {
        if ( typeof fn !== 'function' ) {
            return function() {};
        }
        scope = scope || this;
        return function() {
            return fn.apply( scope, Array.prototype.slice.call(arguments) );
        };
    },
    listen : function( elem, type, fn ) {
        jQuery(elem).bind( type, fn );
    },
    forget : function( elem, type ) {
        jQuery(elem).unbind(type);
    },
    dispatch : function( elem, type ) {
        jQuery(elem).trigger(type);
    },
    clone : function( elem, keepEvents ) {
        keepEvents = keepEvents || false;
        return jQuery(elem).clone(keepEvents)[0];
    },
    removeAttr : function( elem, attributes ) {
        this.loop( attributes.split(' '), function(attr) {
            jQuery(elem).removeAttr(attr);
        });
    },
    push : function( elem, obj ) {
        if (typeof obj.length == 'undefined') {
            obj.length = 0;
        }
        Array.prototype.push.call( obj, elem );
        return elem;
    },
    width : function( elem, outer ) {
        return this.meassure(elem, outer, 'Width');
    },
    height : function( elem, outer ) {
        return this.meassure(elem, outer, 'Height');
    },
    meassure : function(el, outer, meassure) {
        var elem = jQuery( el );
        var ret = outer ? elem['outer'+meassure](true) : elem[meassure.toLowerCase()]();
        // fix quirks mode
        if (G.QUIRK) {
            var which = meassure == "Width" ? [ "left", "right" ] : [ "top", "bottom" ];
            this.loop(which, function(s) {
                ret += elem.css('border-' + s + '-width').replace(/[^\d]/g,'') * 1;
                ret += elem.css('padding-' + s).replace(/[^\d]/g,'') * 1;
            });
        }
        return ret;
    },
    toggleClass : function( elem, className, arg ) {
        if (typeof arg !== 'undefined') {
            var fn = arg ? 'addClass' : 'removeClass';
            jQuery(elem)[fn](className);
            return this;
        }
        jQuery(elem).toggleClass(className);
        return this;
    },
    hideAll : function( el ) {
        jQuery(el).find('*').hide();
    },
    animate : function( el, options ) {
        var elem = jQuery(el);
        if (!elem.length) {
            return;
        }
        if (options.from) {
            elem.css(from);
        }
        elem.animate(options.to, {
            duration: options.duration || 400,
            complete: options.complete || function(){}
        });
    },
    wait : function(fn, callback, err, max) {
        fn = this.proxy(fn);
        callback = this.proxy(callback);
        err = this.proxy(err);
        var ts = new Date().getTime() + (max || 3000);
        window.setTimeout(function() {
            if (fn()) {
                callback();
                return false;
            }
            if (new Date().getTime() >= ts) {
                err();
                callback();
                return false;
            }
            window.setTimeout(arguments.callee, 1);
        }, 1);
        return this;
    },
    getScript: function(url, callback) {
       var script = document.createElement('script');
       script.src = url;
       script.async = true; // HTML5
       callback = this.proxy(callback);

       // Handle Script loading
       {
          var done = false;

          // Attach handlers for all browsers
          script.onload = script.onreadystatechange = function(){
             if ( !done && (!this.readyState ||
                   this.readyState == "loaded" || this.readyState == "complete") ) {
                done = true;
                callback();

                // Handle memory leak in IE
                script.onload = script.onreadystatechange = null;
             }
          };
       }
       
       var ex = document.getElementsByTagName('script');
       ex = ex[ex.length-1];
       ex.parentNode.insertBefore(script, ex.nextSibling);
       return this;
    }
});

var Picture = Base.extend({
    __constructor : function(order) {
        this.image = null;
        this.elem = this.create('div', 'galleria-image');
        this.setStyle( this.elem, {
            overflow: 'hidden',
            position: 'relative' // for IE Standards mode
        } );
        this.order = order;
        this.orig = { w:0, h:0, r:1 };
    },
    
    cache: {},
    
    add: function(src) {
        if (this.cache[src]) {
            return this.cache[src];
        }
        var image = new Image();
        image.src = src;
        this.setStyle(image, {display: 'block'});
        if (image.complete && image.width) {
            this.cache[src] = image;
            return image;
        }
        image.onload = (function(scope) {
            return function() {
                scope.cache[src] = image;
            };
        })(this);
        return image;
    },
    
    isCached: function(src) {
        return this.cache[src] ? this.cache[src].complete : false;
    },
    
    make: function(src) {
        var i = this.cache[src] || this.add(src);
        return this.clone(i);
    },
    
    load: function(src, callback) {
        callback = this.proxy( callback );
        this.elem.innerHTML = '';
        this.image = this.make( src );
        this.moveOut( this.image );
        this.elem.appendChild( this.image );
        this.wait(function() {
            return (this.image.complete && this.image.width);
        }, function() {
            this.orig = {
                h: this.image.height,
                w: this.image.width
            };
            callback( {target: this.image, scope: this} );
        }, function() {
            G.raise('image not loaded in 10 seconds: '+ src);
        }, 10000);
        return this;
    },
    
    scale: function(w, h, crop, max, margin, complete) {
        margin = margin || 0;
        complete = complete || function() {};
        if (!this.image) {
            return this;
        }
        this.wait(function() {
            width  = w || this.width(this.elem);
            height = h || this.height(this.elem);
            return width && height;
        }, function() {
            var ratio = Math[ (crop ? 'max' : 'min') ](width / this.orig.w, height / this.orig.h);
            if (max) {
                ratio = Math.min(max, ratio);
            }
            this.setStyle(this.elem, {
                width: width,
                height: height
            });
            this.image.width = Math.ceil(this.orig.w * ratio) - margin*2;
            this.image.height = Math.ceil(this.orig.h * ratio) - margin*2;
            this.setStyle(this.image, {
                position : 'relative',
                top :  Math.round(this.image.height * -1 / 2 + (height / 2)) - margin,
                left : Math.round(this.image.width * -1 / 2 + (width / 2)) - margin
            });
            complete.call(this);
        });
        return this;
    }
});

var tID; // the private timeout handler

var G = window.Galleria = Base.extend({
    
    __constructor : function(options) {
        if (typeof options.target === 'undefined' ) {
            G.raise('No target.');
        }
        this.playing = false;
        this.playtime = 3000;
        this.active = null;
        this.queue = {};
        this.data = {};
        this.dom = {};
        this.controls = {
            active : 0,
            swap : function() {
                this.active = this.active ? 0 : 1;
            },
            getActive : function() {
                return this[this.active];
            },
            getNext : function() {
                return this[Math.abs(this.active - 1)];
            }
        };
        this.thumbnails = {};
        this.options = this.mix({
            autoplay: false,
            carousel: true,
            carousel_follow: true,
            carousel_speed: 200,
            carousel_steps: 'auto',
            data_config : function( elem ) { return {}; },
            data_image_selector: 'img',
            data_source: options.target,
            data_type: 'auto',
            debug: false,
            extend: function(options) {},
            height: undefined,
            image_crop: false,
            image_margin: 0,
            keep_source: false,
            link_source_images: true,
            max_scale_ratio: undefined,
            popup_links: false,
            preload: 2,
            queue: true,
            show: 0,
            thumb_crop: true,
            thumb_margin: 0,
            thumb_quality: 'auto',
            thumbnails: true,
            transition: G.transitions.fade,
            transition_speed: 400
        }, options);
        
        this.target = this.dom.target = this.getElements(this.options.target)[0];
        if (!this.target) {
             G.raise('Target not found.');
        }
        
        this.stageWidth = 0;
        this.stageHeight = 0;
        
        var elems = 'container stage images image-nav image-nav-left image-nav-right ' + 
                    'info info-link info-text info-title info-description info-author info-close ' +
                    'thumbnails thumbnails-list thumbnails-container thumb-nav-left thumb-nav-right ' +
                    'loader counter';
        elems = elems.split(' ');
        
        this.loop(elems, function(blueprint) {
            this.dom[ blueprint ] = this.create('div', 'galleria-' + blueprint);
        });
    },
    
    bind : function(type, fn) {
        this.listen( this.get('container'), type, this.proxy(fn) );
        return this;
    },
    
    trigger : function( type ) {
        type = typeof type == 'object' ? 
            this.mix( type, { scope: this } ) : 
            { type: type, scope: this };
        this.dispatch( this.get('container'), type );
        return this;
    },
    run : function() {
        
        var o = this.options;
        if (!this.data.length) {
            G.raise('Data is empty.');
        }
        if (!o.keep_source) {
            this.target.innerHTML = '';
        }
        this.loop(2, function() {
            var image = new Picture();
            this.setStyle( image.elem, {
                position: 'absolute',
                top: 0,
                left: 0
            });
            this.setStyle(this.get( 'images' ), {
                position: 'relative',
                top: 0,
                left: 0,
                width: '100%',
                height: '100%'
            });
            this.get( 'images' ).appendChild( image.elem );
            this.push(image, this.controls);
        }, this);
        
        for( var i=0; this.data[i]; i++ ) {
            var thumb;
            if (o.thumbnails === true) {
                thumb = new Picture(i);
                var src = this.data[i].thumb || this.data[i].image;
                this.get( 'thumbnails' ).appendChild( thumb.elem );
                thumb.load(src, this.proxy(function(e) {
                    var orig = this.width(e.target);
                    e.scope.scale(null, null, o.thumb_crop, null, o.thumb_margin, this.proxy(function() {
                        // set high quality if downscale is moderate
                        this.toggleQuality(e.target, o.thumb_quality === true || ( o.thumb_quality == 'auto' && orig < e.target.width * 3 ));
                        this.trigger({
                            type: G.THUMBNAIL,
                            thumbTarget: e.target,
                            thumbOrder: e.scope.order
                        });
                    }));
                }));
                if (o.preload == 'all') {
                    thumb.add(this.data[i].image);
                }
            } else if (o.thumbnails == 'empty') {
                thumb = {
                    elem:  this.create('div','galleria-image'),
                    image: this.create('span','img')
                };
                thumb.elem.appendChild(thumb.image);
                this.get( 'thumbnails' ).appendChild( thumb.elem );
            } else {
                thumb = {
                    elem: false,
                    image: false
                };
            }
            var activate = this.proxy(function(e) {
                e.preventDefault();
                var ind = e.currentTarget.rel;
                if (this.active !== ind) {
                    this.show( ind );
                }
            });
            if (o.thumbnails !== false) {
                thumb.elem.rel = i;
                this.listen(thumb.elem, 'click', activate);
            }
            if (o.link_source_images && o.keep_source && this.data[i].elem) {
                this.data[i].elem.rel = i;
                this.listen(this.data[i].elem, 'click', activate);
            }
            this.push(thumb, this.thumbnails );
        }
        this.build();
        this.target.appendChild(this.get('container'));
        this.wait(function() {
            this.stageWidth = this.width(this.get( 'stage' ));
            this.stageHeight = this.height( this.get( 'stage' ));
            if (!this.stageHeight && this.stageWidth) { // no height in css, set reasonable ratio (16/9)
                this.setStyle( this.get( 'container' ),  { 
                    height: this.options.height || Math.round( this.stageWidth*9/16 ) 
                } );
                this.stageHeight = this.height( this.get( 'stage' ));
            }
            return this.stageHeight && this.stageWidth;
        }, function() {
            var thumbWidth = this.thumbnails[0] ? this.width(this.thumbnails[0].elem, true) : 0;
            
            var thumbsWidth = thumbWidth * this.thumbnails.length;
            if (thumbsWidth < this.stageWidth) {
                o.carousel = false;
            }

            if (o.carousel) {
                this.toggleClass(this.get('thumbnails-container'), 'galleria-carousel');
                this.carousel = {
                    right: this.get('thumb-nav-right'),
                    left: this.get('thumb-nav-left'),
                    overflow: 0,
                    setOverflow: this.proxy(function(newWidth) {
                        newWidth = newWidth || this.width(this.get('thumbnails-list'));
                        this.carousel.overflow = Math.ceil( ( (thumbsWidth - newWidth) / thumbWidth ) + 1 ) * -1;
                    }),
                    pos: 0,
                    setClasses: this.proxy(function() {
                        this.toggleClass( this.carousel.left, 'disabled', this.carousel.pos === 0);
                        this.toggleClass( this.carousel.right, 'disabled', this.carousel.pos == this.carousel.overflow + 1);
                    }),
                    animate: this.proxy(function() {
                        this.carousel.setClasses();
                        this.animate( this.get('thumbnails'), {
                            to: { left: thumbWidth * this.carousel.pos },
                            duration: o.carousel_speed
                        });
                    })
                };
                this.carousel.setOverflow();
            
                this.setStyle(this.get('thumbnails-list'), {
                    overflow:'hidden',
                    position: 'relative' // for IE Standards mode
                });
                this.setStyle(this.get('thumbnails'), {
                    width: thumbsWidth,
                    position: 'relative'
                });
                
                this.proxy(function(c, steps) {
                    steps = (typeof steps == 'string' && steps.toLowerCase() == 'auto') ? this.thumbnails.length + c.overflow : steps;
                    c.setClasses();
                    this.loop(['left','right'], this.proxy(function(dir) {
                        this.listen(c[dir], 'click', function(e) {
                            if (c.pos === ( dir == 'right' ? c.overflow : 0 ) ) {
                                return;
                            }
                            c.pos = dir == 'right' ? Math.max(c.overflow + 1, c.pos - steps) : Math.min(0, c.pos + steps);
                            c.animate();
                        });
                    }));
                })(this.carousel, o.carousel_steps);
            }
            this.listen(this.get('image-nav-right'), 'click', this.proxy(function() {
                this.next();
            }));
            this.listen(this.get('image-nav-left'), 'click', this.proxy(function() {
                this.prev();
            }));
            this.trigger( G.READY );
        }, function() {
            G.raise('Galleria could not load. Make sure stage has a height and width.');
        }, 5000);
    },
    addElement : function() {
        this.loop(arguments, function(b) {
            this.dom[b] = this.create('div', 'galleria-' + b );
        });
        return this;
    },
    getDimensions: function(i) {
        return {
            w: i.width,
            h: i.height,
            cw: this.stageWidth,
            ch: this.stageHeight,
            top: (this.stageHeight - i.height) / 2,
            left: (this.stageWidth - i.width) / 2
        };
    },
    attachKeyboard : function(map) {
        jQuery(document).bind('keydown', {map: map, scope: this}, this.keyNav);
        return this;
    },
    detachKeyboard : function() {
        jQuery(document).unbind('keydown', this.keyNav);
        return this;
    },
    keyNav : function(e) {
        var key = e.keyCode || e.which;
        var map = e.data.map;
        var scope = e.data.scope;
        var keymap = {
            UP: 38,
            DOWN: 40,
            LEFT: 37,
            RIGHT: 39,
            RETURN: 13,
            ESCAPE: 27,
            BACKSPACE: 8
        };
        for( var i in map ) {
            var k = i.toUpperCase();
            if ( keymap[k] ) {
                map[keymap[k]] = map[i];
            }
        }
        if (typeof map[key] == 'function') {
            map[key].call(scope, e);
        }
    },
    build : function() {
        this.append({
            'info-text' :
                ['info-title', 'info-description', 'info-author'],
            'info' : 
                ['info-link', 'info-text', 'info-close'],
            'image-nav' : 
                ['image-nav-right', 'image-nav-left'],
            'stage' : 
                ['images', 'loader', 'counter', 'image-nav'],
            'thumbnails-list' :
                ['thumbnails'],
            'thumbnails-container' : 
                ['thumb-nav-left', 'thumbnails-list', 'thumb-nav-right'],
            'container' : 
                ['stage', 'thumbnails-container', 'info']
        });
    },
    
    appendChild : function(parent, child) {
        try {
            this.get(parent).appendChild(this.get(child));
        } catch(e) {}
    },
    
    append : function(data) {
        for( var i in data) {
            if (data[i].constructor == Array) {
                for(var j=0; data[i][j]; j++) {
                    this.appendChild(i, data[i][j]);
                }
            } else {
                this.appendChild(i, data[i]);
            }
        }
        return this;
    },
    
    rescale : function(width, height) {
        
        var check = this.proxy(function() {
            this.stageWidth = width || this.width(this.get('stage'));
            this.stageHeight = height || this.height(this.get('stage'));
            return this.stageWidth && this.stageHeight;
        });
        if ( G.WEBKIT ) {
            this.wait(check);// wekit is too fast
        } else {
            check.call(this); 
        }
        this.controls.getActive().scale(this.stageWidth, this.stageHeight, this.options.image_crop, this.options.max_scale_ratio, this.options.image_margin);
        if (this.carousel) {
            this.carousel.setOverflow();
        }
        
    },
    
    show : function(index, rewind, history) {
        if (!this.options.queue && this.queue.stalled) {
            return;
        }
        rewind = typeof rewind != 'undefined' ? !!rewind : index < this.active;
        history = history || false;
        index = parseInt(index);
        if (!history && G.History) {
            G.History.value(index.toString());
            return;
        }
        this.active = index;
        this.push([index,rewind], this.queue);
        if (!this.queue.stalled) {
            this.showImage();
        }
        return this;
    },
    
    showImage : function() {
        var o = this.options;
        var args = this.queue[0];
        var index = args[0];
        var rewind = !!args[1];
        if (o.carousel && this.carousel && o.carousel_follow) {
            this.proxy(function(c) {
                if (index <= Math.abs(c.pos)) {
                    c.pos = Math.max(0, (index-1))*-1;
                    c.animate();
                } else if ( index >= this.thumbnails.length + c.overflow + Math.abs(c.pos)) {
                    c.pos = this.thumbnails.length + c.overflow - index - 1 + (index == this.thumbnails.length-1 ? 1 : 0);
                    c.animate();
                }
            })(this.carousel);
        }
        
        var src = this.getData(index).image;
        var active = this.controls.getActive();
        var next = this.controls.getNext();
        var cached = next.isCached(src);
        if (active.image) {
            this.toggleQuality(active.image, false);
        }
        var complete = this.proxy(function() {
            this.queue.stalled = false;
            this.toggleQuality(next.image, o.image_quality);
            this.setStyle( active.elem, { zIndex : 0 } );
            this.setStyle( next.elem, { zIndex : 1 } );
            this.moveOut( active.image );
            this.controls.swap();
            if (this.getData( index ).link) {
                this.setStyle( next.image, { cursor: 'pointer' } );
                this.listen( next.image, 'click', this.proxy(function() {
                    if (o.popup_links) {
                        var win = window.open(this.getData( index ).link, '_blank');
                    } else {
                        window.location.href = this.getData( index ).link;
                    }
                }));
            }
            Array.prototype.shift.call( this.queue );
            if (this.queue.length) {
                this.showImage();
            }
            this.playCheck();
        });
        if (typeof o.preload == 'number' && o.preload > 0) {
            var p,n = this.getNext();
            try {
                for (var i = o.preload; i>0; i--) {
                    p = new Picture();
                    p.add(this.getData(n).image);
                    n = this.getNext(n);
                }
            } catch(e) {}
        }
        this.trigger( {
            type: G.LOADSTART,
            cached: cached,
            imageTarget: next.image,
            thumbTarget: this.thumbnails[index].image
        } );
        next.load( src, this.proxy(function(e) {
            next.scale(this.stageWidth, this.stageHeight, o.image_crop, o.max_scale_ratio, o.image_margin, this.proxy(function(e) {
                this.toggleQuality(next.image, false);
                this.trigger({
                    type: G.LOADFINISH,
                    cached: cached,
                    imageTarget: next.image,
                    thumbTarget: this.thumbnails[index].image
                });
                this.queue.stalled = true;
                var transition = G.transitions[o.transition] || o.transition;
                if (typeof transition == 'function') {
                    transition.call(this, {
                        prev: active.image,
                        next: next.image,
                        rewind: rewind,
                        speed: o.transition_speed || 400
                    }, complete );
                } else {
                    complete();
                }
            }));
            this.setInfo(index);
            this.get('counter').innerHTML = '<span class="current">' + (index+1) + 
                '</span> / <span class="total">' + this.thumbnails.length + '</span>';
        }));
    },
    
    getNext : function(base) {
        base = base || this.active;
        return base == this.data.length - 1 ? 0 : base + 1;
    },
    
    getPrev : function(base) {
        base = base || this.active;
        return base === 0 ? this.data.length - 1 : base - 1;
    },
    
    next : function() {
        if (this.data.length > 1) {
            this.show(this.getNext(), false);
        }
        return this;
    },
    
    prev : function() {
        if (this.data.length > 1) {
            this.show(this.getPrev(), true);
        }
        return this;
    },
    
    get : function( elem ) {
        return this.dom[ elem ] || false;
    },
    
    getData : function( index ) {
        return this.data[index] || this.data[this.active];
    },
    
    play : function(delay) {
        this.playing = true;
        this.playtime = delay || this.playtime;
        this.playCheck();
        return this;
    },
    
    pause : function() {
        this.playing = false;
        return this;
    },
    
    playCheck : function() {
        if (this.playing) {
            window.clearInterval(tID);
            tID = window.setTimeout(this.proxy(function() {
                if (this.playing) {
                    this.next();
                }
            }), this.playtime);
        }
    },
    
    setActive: function(val) {
        this.active = val;
        return this;
    },
    
    setInfo : function(index) {
        var data = this.getData(index);
        var set = this.proxy(function() {
            this.loop(arguments, function(type) {
                var elem = this.get('info-'+type);
                var fn = data[type] && data[type].length ? 'reveal' : 'hide';
                this[fn](elem);
                elem.innerHTML = data[type];
            });
        });
        set('title','description','author');
        return this;
    },
    
    hasInfo : function(index) {
        var d = this.getData(index);
        var l = d.title + d.description + d.author;
        return !!l.length;
    },
    
    getDataObject : function(o) {
        var obj = {
            image: '',
            thumb: '',
            title: '',
            description: '',
            author: '',
            link: ''
        };
        return o ? this.mix(obj,o) : obj;
    },
    
    jQuery : function( str ) {
        var ret = [];
        this.loop(str.split(','), this.proxy(function(elem) {
            elem = elem.replace(/^\s\s*/, "").replace(/\s\s*$/, "");
            if (this.get(elem)) {
                ret.push(elem);
            }
        }));
        var jQ = jQuery(this.get(ret.shift()));
        this.loop(ret, this.proxy(function(elem) {
            jQ = jQ.add(this.get(elem));
        }));
        return jQ;
    },
    
    $ : function( str ) {
        return this.jQuery( str );
    },
    
    toggleQuality : function(img, force) {
        if (!G.IE7 || typeof img == 'undefined' || !img) {
            return this;
        }
        if (typeof force === 'undefined') {
            force = img.style.msInterpolationMode == 'nearest-neighbor';
        }
        img.style.msInterpolationMode = force ? 'bicubic' : 'nearest-neighbor';

        return this;
    },
    
    load : function() {
        var loaded = 0;
        var o = this.options;
        if (
            (o.data_type == 'auto' && 
                typeof o.data_source == 'object' && 
                !(o.data_source instanceof jQuery) && 
                !o.data_source.tagName
            ) || o.data_type == 'json' || o.data_source.constructor == 'Array' ) {
            this.data = o.data_source;
            this.trigger( G.DATA );
            
        } else { // assume selector
            var images = jQuery(o.data_source).find(o.data_image_selector);
            var getData = this.proxy(function( elem ) {
                var i,j,anchor = elem.parentNode;
                if (anchor && anchor.nodeName == 'A') {
                    if (anchor.href.match(/\.(png|gif|jpg)/i)) {
                        i = anchor.href;
                    } else {
                        j = anchor.href;
                    }
                }
                var obj = this.getDataObject({
                    title: elem.title,
                    thumb: elem.src,
                    image: i || elem.src,
                    description: elem.alt,
                    link: j || elem.getAttribute('longdesc'),
                    elem: elem
                });
                return this.mix(obj, o.data_config( elem ) );
            });
            
            this.loop(images, function( elem ) {
                loaded++;
                this.push( getData( elem ), this.data );
                if (!o.keep_source) {
                    elem.parentNode.removeChild(elem);
                }
                if ( loaded == images.length ) {
                    this.trigger( G.DATA );
                }
            });
        }
    }
});

G.log = function() {
    try { 
        console.log.apply( console, Array.prototype.slice.call(arguments) ); 
    } catch(e) {
        try {
            opera.postError.apply( opera, arguments ); 
        } catch(er) { 
              alert( Array.prototype.join.call( arguments, " " ) ); 
        } 
    }
};

G.DATA = 'data';
G.READY = 'ready';
G.THUMBNAIL = 'thumbnail';
G.LOADSTART = 'loadstart';
G.LOADFINISH = 'loadfinish';

var nav = navigator.userAgent.toLowerCase();

G.IE7 = (window.XMLHttpRequest && document.expando);
G.IE6 = (!window.XMLHttpRequest);
G.IE = !!(G.IE6 || G.IE7);
G.WEBKIT = /webkit/.test( nav );
G.SAFARI = /safari/.test( nav );
G.CHROME = /chrome/.test( nav );
G.QUIRK = (G.IE && document.compatMode && document.compatMode == "BackCompat");
G.MAC = /mac/.test(navigator.platform.toLowerCase());

var tempPath = ''; // we need to save this in a global private variable later
var tempName = ''; // the last loaded theme
var tempLoading = false; // we need to manually check if script has loaded
var tempFile = ''; // the theme file
var hash = window.location.hash.replace(/#\//,'');

G.themes = {
    create: function(obj) {
        var orig = ['name','author','version','defaults','init'];
        var proto = G.prototype;
        proto.loop(orig, function(val) {
            if (!obj[ val ]) {
                G.raise(val+' not specified in theme.');
            }
            if ( typeof G.themes[obj.name] == 'undefined') {
                G.themes[obj.name] = {};
            }
            if (val != 'name' && val != 'init') {
                G.themes[obj.name][val] = obj[val];
            }
        });
        if (obj.css) {
            if (!tempPath.length) { // try to find the script tag to determine tempPath
                var theme_src = proto.getElements('script');
                proto.loop(theme_src, function(el) {
                    var reg = new RegExp('galleria.'+obj.name+'.js');
                    if(reg.test(el.src)) {
                        tempPath = el.src.replace(/[^\/]*$/, "");
                    }
                });
            }
            obj.cssPath = tempPath + obj.css;
            tempPath = '';
        }
        tempName = obj.name;
        G.themes[obj.name].init = function(o) {
            if (obj.cssPath) {
                var link = proto.getElements('#galleria-styles');
                if (link.length) {
                    link = link[0];
                } else {
                    link = proto.create('link');
                    link.id = 'galleria-styles';
                    link.rel = 'stylesheet';
                    link.media = 'all';
                    var li = document.getElementsByTagName('link').length ?
                        document.getElementsByTagName('link') : document.getElementsByTagName('style');
                    if (li[0]) {
                        li[0].parentNode.insertBefore(link, li[0]);
                    } else {
                        document.getElementsByTagName('head')[0].appendChild(link);
                    }
                }
                link.href = obj.cssPath;
            }
            if (obj.cssText) {
                proto.cssText(obj.cssText);
            }
            o = proto.mix( G.themes[obj.name].defaults, o );
            var gallery = new G( o );
            o = gallery.options;
            gallery.bind(G.DATA, function() {
                gallery.run();
            });
            gallery.bind(G.READY, function() {
                if (G.History) {
                    G.History.change(function(e) {
                        var val = parseInt(e.value.replace(/\//,''));
                        if (isNaN(val)) {
                            window.history.go(-1);
                        } else {
                            gallery.show(val, undefined, true);
                        }
                    });
                }
                obj.init.call(gallery, o);
                o.extend.call(gallery, o);
                if (/^[0-9]{1,4}$/.test(hash) && G.History) {
                    gallery.show(hash, undefined, true);
                } else if (typeof o.show == 'number') {
                    gallery.show(o.show);
                }
                if (o.autoplay) {
                    if (typeof o.autoplay == 'number') {
                        gallery.play(o.autoplay);
                    } else {
                        gallery.play();
                    }
                }
            });
            gallery.load();
            return gallery;
        };
    }
};

G.raise = function(msg) {
    if ( G.debug ) {
        throw new Error( msg );
    }
},

G.loadTheme = function(src, callback) {
    tempLoading = true;
    tempPath = src.replace(/[^\/]*$/, "");
    tempFile = src;
    G.prototype.getScript(src, function() {
        tempLoading = false;
        if (typeof callback == 'function') {
            callback();
        }
    });
};

jQuery.easing.galleria = function (x, t, b, c, d) {
    if ((t/=d/2) < 1) { 
        return c/2*t*t*t*t + b;
    }
    return -c/2 * ((t-=2)*t*t*t - 2) + b;
};

G.transitions = {
    add: function(name, fn) {
        if (name != arguments.callee.name ) {
            this[name] = fn;
        }
    },
    fade: function(params, complete) {
        jQuery(params.next).show().css('opacity',0).animate({
            opacity: 1
        }, params.speed, complete);
        if (params.prev) {
            jQuery(params.prev).css('opacity',1).animate({
                opacity: 0
            }, params.speed);
        }
    },
    flash: function(params, complete) {
        jQuery(params.next).css('opacity',0);
        if (params.prev) {
            jQuery(params.prev).animate({
                opacity: 0
            }, (params.speed/2), function() {
                jQuery(params.next).animate({
                    opacity: 1
                }, params.speed, complete);
            });
        } else {
            jQuery(params.next).animate({
                opacity: 1
            }, params.speed, complete);
        }
    },
    slide: function(params, complete) {
        var image = jQuery(params.next).parent();
        var images =  this.$('images');
        var width = this.stageWidth;
        image.css({
            left: width * ( params.rewind ? -1 : 1 )
        });
        images.animate({
            left: width * ( params.rewind ? 1 : -1 )
        }, {
            duration: params.speed,
            queue: false,
            easing: 'galleria',
            complete: function() {
                images.css('left',0);
                image.css('left',0);
                complete();
            }
        });
    },
    fadeslide: function(params, complete) {
        if (params.prev) {
            jQuery(params.prev).css({
                opacity: 1,
                left: 0
            }).animate({
                opacity: 0,
                left: 50 * ( params.rewind ? 1 : -1 )
            },{
                duration: params.speed,
                queue: false,
                easing: 'swing'
            });
        }
        jQuery(params.next).css({
            left: 50 * ( params.rewind ? -1 : 1 ), 
            opacity: 0
        }).animate({
            opacity: 1,
            left:0
        }, {
            duration: params.speed,
            complete: complete,
            queue: false,
            easing: 'swing'
        });
    }
};

jQuery.fn.galleria = function() {
    var selector = this.selector;
    var a = arguments;
    var hasTheme = typeof a[0] == 'string';
    var options = hasTheme ? a[1] || {} : a[0] || {};

    if ( !options.keep_source ) {
        jQuery(this).find('*').hide();
    }

    G.prototype.wait(function() {
        return !tempLoading;
    }, function() {
        var theme = hasTheme ? a[0] : tempName;
        options = G.prototype.mix(options, { target: selector } );
        G.debug = !!options.debug; 
        if (typeof G.themes[theme] == 'undefined') {
            var err = theme ? 'Theme '+theme+' not found.' : 'No theme specified';
            G.raise(err);
            return null;
        } else {
            return G.themes[theme].init(options);
        }
    }, function() {
        G.raise('Theme file '+tempFile+' not found.');
    });
};

})();

/*
 * FancyBox - jQuery Plugin
 * Simple and fancy lightbox alternative
 *
 * Examples and documentation at: http://fancybox.net
 * 
 * Copyright (c) 2008 - 2010 Janis Skarnelis
 *
 * Version: 1.3.1 (05/03/2010)
 * Requires: jQuery v1.3+
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */

(function($) {

	var tmp, loading, overlay, wrap, outer, inner, close, nav_left, nav_right,

		selectedIndex = 0, selectedOpts = {}, selectedArray = [], currentIndex = 0, currentOpts = {}, currentArray = [],

		ajaxLoader = null, imgPreloader = new Image(), imgRegExp = /\.(jpg|gif|png|bmp|jpeg)(.*)?$/i, swfRegExp = /[^\.]\.(swf)\s*$/i,

		loadingTimer, loadingFrame = 1,

		start_pos, final_pos, busy = false, shadow = 20, fx = $.extend($('<div/>')[0], { prop: 0 }), titleh = 0, 

		isIE6 = !$.support.opacity && !window.XMLHttpRequest,

		/*
		 * Private methods 
		 */

		fancybox_abort = function() {
			loading.hide();

			imgPreloader.onerror = imgPreloader.onload = null;

			if (ajaxLoader) {
				ajaxLoader.abort();
			}

			tmp.empty();
		},

		fancybox_error = function() {
			$.fancybox('<p id="fancybox_error">The requested content cannot be loaded.<br />Please try again later.</p>', {
				'scrolling'		: 'no',
				'padding'		: 20,
				'transitionIn'	: 'none',
				'transitionOut'	: 'none'
			});
		},

		fancybox_get_viewport = function() {
			return [ $(window).width(), $(window).height(), $(document).scrollLeft(), $(document).scrollTop() ];
		},

		fancybox_get_zoom_to = function () {
			var view	= fancybox_get_viewport(),
				to		= {},

				margin = currentOpts.margin,
				resize = currentOpts.autoScale,

				horizontal_space	= (shadow + margin) * 2,
				vertical_space		= (shadow + margin) * 2,
				double_padding		= (currentOpts.padding * 2),
				
				ratio;

			if (currentOpts.width.toString().indexOf('%') > -1) {
				to.width = ((view[0] * parseFloat(currentOpts.width)) / 100) - (shadow * 2) ;
				resize = false;

			} else {
				to.width = currentOpts.width + double_padding;
			}

			if (currentOpts.height.toString().indexOf('%') > -1) {
				to.height = ((view[1] * parseFloat(currentOpts.height)) / 100) - (shadow * 2);
				resize = false;

			} else {
				to.height = currentOpts.height + double_padding;
			}

			if (resize && (to.width > (view[0] - horizontal_space) || to.height > (view[1] - vertical_space))) {
				if (selectedOpts.type == 'image' || selectedOpts.type == 'swf') {
					horizontal_space	+= double_padding;
					vertical_space		+= double_padding;

					ratio = Math.min(Math.min( view[0] - horizontal_space, currentOpts.width) / currentOpts.width, Math.min( view[1] - vertical_space, currentOpts.height) / currentOpts.height);

					to.width	= Math.round(ratio * (to.width	- double_padding)) + double_padding;
					to.height	= Math.round(ratio * (to.height	- double_padding)) + double_padding;

				} else {
					to.width	= Math.min(to.width,	(view[0] - horizontal_space));
					to.height	= Math.min(to.height,	(view[1] - vertical_space));
				}
			}

			to.top	= view[3] + ((view[1] - (to.height	+ (shadow * 2 ))) * 0.5);
			to.left	= view[2] + ((view[0] - (to.width	+ (shadow * 2 ))) * 0.5);

			if (currentOpts.autoScale === false) {
				to.top	= Math.max(view[3] + margin, to.top);
				to.left	= Math.max(view[2] + margin, to.left);
			}

			return to;
		},

		fancybox_format_title = function(title) {
			if (title && title.length) {
				switch (currentOpts.titlePosition) {
					case 'inside':
						return title;
					case 'over':
						return '<span id="fancybox-title-over">' + title + '</span>';
					default:
						return '<span id="fancybox-title-wrap"><span id="fancybox-title-left"></span><span id="fancybox-title-main">' + title + '</span><span id="fancybox-title-right"></span></span>';
				}
			}

			return false;
		},

		fancybox_process_title = function() {
			var title	= currentOpts.title,
				width	= final_pos.width - (currentOpts.padding * 2),
				titlec	= 'fancybox-title-' + currentOpts.titlePosition;
				
			$('#fancybox-title').remove();

			titleh = 0;

			if (currentOpts.titleShow === false) {
				return;
			}

			title = $.isFunction(currentOpts.titleFormat) ? currentOpts.titleFormat(title, currentArray, currentIndex, currentOpts) : fancybox_format_title(title);

			if (!title || title === '') {
				return;
			}

			$('<div id="fancybox-title" class="' + titlec + '" />').css({
				'width'			: width,
				'paddingLeft'	: currentOpts.padding,
				'paddingRight'	: currentOpts.padding
			}).html(title).appendTo('body');

			switch (currentOpts.titlePosition) {
				case 'inside':
					titleh = $("#fancybox-title").outerHeight(true) - currentOpts.padding;
					final_pos.height += titleh;
				break;

				case 'over':
					$('#fancybox-title').css('bottom', currentOpts.padding);
				break;

				default:
					$('#fancybox-title').css('bottom', $("#fancybox-title").outerHeight(true) * -1);
				break;
			}

			$('#fancybox-title').appendTo( outer ).hide();
		},

		fancybox_set_navigation = function() {
			$(document).unbind('keydown.fb').bind('keydown.fb', function(e) {
				if (e.keyCode == 27 && currentOpts.enableEscapeButton) {
					e.preventDefault();
					$.fancybox.close();

				} else if (e.keyCode == 37) {
					e.preventDefault();
					$.fancybox.prev();

				} else if (e.keyCode == 39) {
					e.preventDefault();
					$.fancybox.next();
				}
			});

			if ($.fn.mousewheel) {
				wrap.unbind('mousewheel.fb');

				if (currentArray.length > 1) {
					wrap.bind('mousewheel.fb', function(e, delta) {
						e.preventDefault();

						if (busy || delta === 0) {
							return;
						}

						if (delta > 0) {
							$.fancybox.prev();
						} else {
							$.fancybox.next();
						}
					});
				}
			}

			if (!currentOpts.showNavArrows) { return; }

			if ((currentOpts.cyclic && currentArray.length > 1) || currentIndex !== 0) {
				nav_left.show();
			}

			if ((currentOpts.cyclic && currentArray.length > 1) || currentIndex != (currentArray.length -1)) {
				nav_right.show();
			}
		},

		fancybox_preload_images = function() {
			var href, 
				objNext;
				
			if ((currentArray.length -1) > currentIndex) {
				href = currentArray[ currentIndex + 1 ].href;

				if (typeof href !== 'undefined' && href.match(imgRegExp)) {
					objNext = new Image();
					objNext.src = href;
				}
			}

			if (currentIndex > 0) {
				href = currentArray[ currentIndex - 1 ].href;

				if (typeof href !== 'undefined' && href.match(imgRegExp)) {
					objNext = new Image();
					objNext.src = href;
				}
			}
		},

		_finish = function () {
			inner.css('overflow', (currentOpts.scrolling == 'auto' ? (currentOpts.type == 'image' || currentOpts.type == 'iframe' || currentOpts.type == 'swf' ? 'hidden' : 'auto') : (currentOpts.scrolling == 'yes' ? 'auto' : 'visible')));

			if (!$.support.opacity) {
				inner.get(0).style.removeAttribute('filter');
				wrap.get(0).style.removeAttribute('filter');
			}

			$('#fancybox-title').show();

			if (currentOpts.hideOnContentClick)	{
				inner.one('click', $.fancybox.close);
			}
			if (currentOpts.hideOnOverlayClick)	{
				overlay.one('click', $.fancybox.close);
			}

			if (currentOpts.showCloseButton) {
				close.show();
			}

			fancybox_set_navigation();

			$(window).bind("resize.fb", $.fancybox.center);

			if (currentOpts.centerOnScroll) {
				$(window).bind("scroll.fb", $.fancybox.center);
			} else {
				$(window).unbind("scroll.fb");
			}

			if ($.isFunction(currentOpts.onComplete)) {
				currentOpts.onComplete(currentArray, currentIndex, currentOpts);
			}

			busy = false;

			fancybox_preload_images();
		},

		fancybox_draw = function(pos) {
			var width	= Math.round(start_pos.width	+ (final_pos.width	- start_pos.width)	* pos),
				height	= Math.round(start_pos.height	+ (final_pos.height	- start_pos.height)	* pos),

				top		= Math.round(start_pos.top	+ (final_pos.top	- start_pos.top)	* pos),
				left	= Math.round(start_pos.left	+ (final_pos.left	- start_pos.left)	* pos);

			wrap.css({
				'width'		: width		+ 'px',
				'height'	: height	+ 'px',
				'top'		: top		+ 'px',
				'left'		: left		+ 'px'
			});

			width	= Math.max(width - currentOpts.padding * 2, 0);
			height	= Math.max(height - (currentOpts.padding * 2 + (titleh * pos)), 0);

			inner.css({
				'width'		: width		+ 'px',
				'height'	: height	+ 'px'
			});

			if (typeof final_pos.opacity !== 'undefined') {
				wrap.css('opacity', (pos < 0.5 ? 0.5 : pos));
			}
		},

		fancybox_get_obj_pos = function(obj) {
			var pos		= obj.offset();

			pos.top		+= parseFloat( obj.css('paddingTop') )	|| 0;
			pos.left	+= parseFloat( obj.css('paddingLeft') )	|| 0;

			pos.top		+= parseFloat( obj.css('border-top-width') )	|| 0;
			pos.left	+= parseFloat( obj.css('border-left-width') )	|| 0;

			pos.width	= obj.width();
			pos.height	= obj.height();

			return pos;
		},

		fancybox_get_zoom_from = function() {
			var orig = selectedOpts.orig ? $(selectedOpts.orig) : false,
				from = {},
				pos,
				view;

			if (orig && orig.length) {
				pos = fancybox_get_obj_pos(orig);

				from = {
					width	: (pos.width	+ (currentOpts.padding * 2)),
					height	: (pos.height	+ (currentOpts.padding * 2)),
					top		: (pos.top		- currentOpts.padding - shadow),
					left	: (pos.left		- currentOpts.padding - shadow)
				};
				
			} else {
				view = fancybox_get_viewport();

				from = {
					width	: 1,
					height	: 1,
					top		: view[3] + view[1] * 0.5,
					left	: view[2] + view[0] * 0.5
				};
			}

			return from;
		},

		fancybox_show = function() {
			loading.hide();

			if (wrap.is(":visible") && $.isFunction(currentOpts.onCleanup)) {
				if (currentOpts.onCleanup(currentArray, currentIndex, currentOpts) === false) {
					$.event.trigger('fancybox-cancel');

					busy = false;
					return;
				}
			}

			currentArray	= selectedArray;
			currentIndex	= selectedIndex;
			currentOpts		= selectedOpts;

			inner.get(0).scrollTop	= 0;
			inner.get(0).scrollLeft	= 0;

			if (currentOpts.overlayShow) {
				if (isIE6) {
					$('select:not(#fancybox-tmp select)').filter(function() {
						return this.style.visibility !== 'hidden';
					}).css({'visibility':'hidden'}).one('fancybox-cleanup', function() {
						this.style.visibility = 'inherit';
					});
				}

				overlay.css({
					'background-color'	: currentOpts.overlayColor,
					'opacity'			: currentOpts.overlayOpacity
				}).unbind().show();
			}

			final_pos = fancybox_get_zoom_to();

			fancybox_process_title();

			if (wrap.is(":visible")) {
				$( close.add( nav_left ).add( nav_right ) ).hide();

				var pos = wrap.position(),
					equal;

				start_pos = {
					top		:	pos.top ,
					left	:	pos.left,
					width	:	wrap.width(),
					height	:	wrap.height()
				};

				equal = (start_pos.width == final_pos.width && start_pos.height == final_pos.height);

				inner.fadeOut(currentOpts.changeFade, function() {
					var finish_resizing = function() {
						inner.html( tmp.contents() ).fadeIn(currentOpts.changeFade, _finish);
					};
					
					$.event.trigger('fancybox-change');

					inner.empty().css('overflow', 'hidden');

					if (equal) {
						inner.css({
							top			: currentOpts.padding,
							left		: currentOpts.padding,
							width		: Math.max(final_pos.width	- (currentOpts.padding * 2), 1),
							height		: Math.max(final_pos.height	- (currentOpts.padding * 2) - titleh, 1)
						});
						
						finish_resizing();

					} else {
						inner.css({
							top			: currentOpts.padding,
							left		: currentOpts.padding,
							width		: Math.max(start_pos.width	- (currentOpts.padding * 2), 1),
							height		: Math.max(start_pos.height	- (currentOpts.padding * 2), 1)
						});
						
						fx.prop = 0;

						$(fx).animate({ prop: 1 }, {
							 duration	: currentOpts.changeSpeed,
							 easing		: currentOpts.easingChange,
							 step		: fancybox_draw,
							 complete	: finish_resizing
						});
					}
				});

				return;
			}

			wrap.css('opacity', 1);

			if (currentOpts.transitionIn == 'elastic') {
				start_pos = fancybox_get_zoom_from();

				inner.css({
						top			: currentOpts.padding,
						left		: currentOpts.padding,
						width		: Math.max(start_pos.width	- (currentOpts.padding * 2), 1),
						height		: Math.max(start_pos.height	- (currentOpts.padding * 2), 1)
					})
					.html( tmp.contents() );

				wrap.css(start_pos).show();

				if (currentOpts.opacity) {
					final_pos.opacity = 0;
				}

				fx.prop = 0;

				$(fx).animate({ prop: 1 }, {
					 duration	: currentOpts.speedIn,
					 easing		: currentOpts.easingIn,
					 step		: fancybox_draw,
					 complete	: _finish
				});

			} else {
				inner.css({
						top			: currentOpts.padding,
						left		: currentOpts.padding,
						width		: Math.max(final_pos.width	- (currentOpts.padding * 2), 1),
						height		: Math.max(final_pos.height	- (currentOpts.padding * 2) - titleh, 1)
					})
					.html( tmp.contents() );

				wrap.css( final_pos ).fadeIn( currentOpts.transitionIn == 'none' ? 0 : currentOpts.speedIn, _finish );
			}
		},

		fancybox_process_inline = function() {
			tmp.width(	selectedOpts.width );
			tmp.height(	selectedOpts.height );

			if (selectedOpts.width	== 'auto') {
				selectedOpts.width = tmp.width();
			}
			if (selectedOpts.height	== 'auto') {
				selectedOpts.height	= tmp.height();
			}

			fancybox_show();
		},
		
		fancybox_process_image = function() {
			busy = true;

			selectedOpts.width	= imgPreloader.width;
			selectedOpts.height	= imgPreloader.height;

			$("<img />").attr({
				'id'	: 'fancybox-img',
				'src'	: imgPreloader.src,
				'alt'	: selectedOpts.title
			}).appendTo( tmp );

			fancybox_show();
		},

		fancybox_start = function() {
			fancybox_abort();

			var obj	= selectedArray[ selectedIndex ],
				href, 
				type, 
				title,
				str,
				emb,
				selector,
				data;

			selectedOpts = $.extend({}, $.fn.fancybox.defaults, (typeof $(obj).data('fancybox') == 'undefined' ? selectedOpts : $(obj).data('fancybox')));
			title = obj.title || $(obj).title || selectedOpts.title || '';
			
			if (obj.nodeName && !selectedOpts.orig) {
				selectedOpts.orig = $(obj).children("img:first").length ? $(obj).children("img:first") : $(obj);
			}

			if (title === '' && selectedOpts.orig) {
				title = selectedOpts.orig.attr('alt');
			}

			if (obj.nodeName && (/^(?:javascript|#)/i).test(obj.href)) {
				href = selectedOpts.href || null;
			} else {
				href = selectedOpts.href || obj.href || null;
			}

			if (selectedOpts.type) {
				type = selectedOpts.type;

				if (!href) {
					href = selectedOpts.content;
				}
				
			} else if (selectedOpts.content) {
				type	= 'html';

			} else if (href) {
				if (href.match(imgRegExp)) {
					type = 'image';

				} else if (href.match(swfRegExp)) {
					type = 'swf';

				} else if ($(obj).hasClass("iframe")) {
					type = 'iframe';

				} else if (href.match(/#/)) {
					obj = href.substr(href.indexOf("#"));

					type = $(obj).length > 0 ? 'inline' : 'ajax';
				} else {
					type = 'ajax';
				}
			} else {
				type = 'inline';
			}

			selectedOpts.type	= type;
			selectedOpts.href	= href;
			selectedOpts.title	= title;

			if (selectedOpts.autoDimensions && selectedOpts.type !== 'iframe' && selectedOpts.type !== 'swf') {
				selectedOpts.width		= 'auto';
				selectedOpts.height		= 'auto';
			}

			if (selectedOpts.modal) {
				selectedOpts.overlayShow		= true;
				selectedOpts.hideOnOverlayClick	= false;
				selectedOpts.hideOnContentClick	= false;
				selectedOpts.enableEscapeButton	= false;
				selectedOpts.showCloseButton	= false;
			}

			if ($.isFunction(selectedOpts.onStart)) {
				if (selectedOpts.onStart(selectedArray, selectedIndex, selectedOpts) === false) {
					busy = false;
					return;
				}
			}

			tmp.css('padding', (shadow + selectedOpts.padding + selectedOpts.margin));

			$('.fancybox-inline-tmp').unbind('fancybox-cancel').bind('fancybox-change', function() {
				$(this).replaceWith(inner.children());
			});

			switch (type) {
				case 'html' :
					tmp.html( selectedOpts.content );
					fancybox_process_inline();
				break;

				case 'inline' :
					$('<div class="fancybox-inline-tmp" />').hide().insertBefore( $(obj) ).bind('fancybox-cleanup', function() {
						$(this).replaceWith(inner.children());
					}).bind('fancybox-cancel', function() {
						$(this).replaceWith(tmp.children());
					});

					$(obj).appendTo(tmp);

					fancybox_process_inline();
				break;

				case 'image':
					busy = false;

					$.fancybox.showActivity();

					imgPreloader = new Image();

					imgPreloader.onerror = function() {
						fancybox_error();
					};

					imgPreloader.onload = function() {
						imgPreloader.onerror = null;
						imgPreloader.onload = null;
						fancybox_process_image();
					};

					imgPreloader.src = href;
		
				break;

				case 'swf':
					str = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="' + selectedOpts.width + '" height="' + selectedOpts.height + '"><param name="movie" value="' + href + '"></param>';
					emb = '';
					
					$.each(selectedOpts.swf, function(name, val) {
						str += '<param name="' + name + '" value="' + val + '"></param>';
						emb += ' ' + name + '="' + val + '"';
					});

					str += '<embed src="' + href + '" type="application/x-shockwave-flash" width="' + selectedOpts.width + '" height="' + selectedOpts.height + '"' + emb + '></embed></object>';

					tmp.html(str);

					fancybox_process_inline();
				break;

				case 'ajax':
					selector	= href.split('#', 2);
					data		= selectedOpts.ajax.data || {};

					if (selector.length > 1) {
						href = selector[0];

						if (typeof data == "string") {
							data += '&selector=' + selector[1];
						} else {
							data.selector = selector[1];
						}
					}

					busy = false;
					$.fancybox.showActivity();

					ajaxLoader = $.ajax($.extend(selectedOpts.ajax, {
						url		: href,
						data	: data,
						error	: fancybox_error,
						success : function(data, textStatus, XMLHttpRequest) {
							if (ajaxLoader.status == 200) {
								tmp.html( data );
								fancybox_process_inline();
							}
						}
					}));

				break;

				case 'iframe' :
					$('<iframe id="fancybox-frame" name="fancybox-frame' + new Date().getTime() + '" frameborder="0" hspace="0" scrolling="' + selectedOpts.scrolling + '" src="' + selectedOpts.href + '"></iframe>').appendTo(tmp);
					fancybox_show();
				break;
			}
		},

		fancybox_animate_loading = function() {
			if (!loading.is(':visible')){
				clearInterval(loadingTimer);
				return;
			}

			$('div', loading).css('top', (loadingFrame * -40) + 'px');

			loadingFrame = (loadingFrame + 1) % 12;
		},

		fancybox_init = function() {
			if ($("#fancybox-wrap").length) {
				return;
			}

			$('body').append(
				tmp			= $('<div id="fancybox-tmp"></div>'),
				loading		= $('<div id="fancybox-loading"><div></div></div>'),
				overlay		= $('<div id="fancybox-overlay"></div>'),
				wrap		= $('<div id="fancybox-wrap"></div>')
			);

			if (!$.support.opacity) {
				wrap.addClass('fancybox-ie');
				loading.addClass('fancybox-ie');
			}

			outer = $('<div id="fancybox-outer"></div>')
				.append('<div class="fancy-bg" id="fancy-bg-n"></div><div class="fancy-bg" id="fancy-bg-ne"></div><div class="fancy-bg" id="fancy-bg-e"></div><div class="fancy-bg" id="fancy-bg-se"></div><div class="fancy-bg" id="fancy-bg-s"></div><div class="fancy-bg" id="fancy-bg-sw"></div><div class="fancy-bg" id="fancy-bg-w"></div><div class="fancy-bg" id="fancy-bg-nw"></div>')
				.appendTo( wrap );

			outer.append(
				inner		= $('<div id="fancybox-inner"></div>'),
				close		= $('<a id="fancybox-close"></a>'),

				nav_left	= $('<a href="javascript:;" id="fancybox-left"><span class="fancy-ico" id="fancybox-left-ico"></span></a>'),
				nav_right	= $('<a href="javascript:;" id="fancybox-right"><span class="fancy-ico" id="fancybox-right-ico"></span></a>')
			);

			close.click($.fancybox.close);
			loading.click($.fancybox.cancel);

			nav_left.click(function(e) {
				e.preventDefault();
				$.fancybox.prev();
			});

			nav_right.click(function(e) {
				e.preventDefault();
				$.fancybox.next();
			});

			if (isIE6) {
				overlay.get(0).style.setExpression('height',	"document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'");
				loading.get(0).style.setExpression('top',		"(-20 + (document.documentElement.clientHeight ? document.documentElement.clientHeight/2 : document.body.clientHeight/2 ) + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop )) + 'px'");

				outer.prepend('<iframe id="fancybox-hide-sel-frame" src="javascript:\'\';" scrolling="no" frameborder="0" ></iframe>');
			}
		};

	/*
	 * Public methods 
	 */

	$.fn.fancybox = function(options) {
		$(this)
			.data('fancybox', $.extend({}, options, ($.metadata ? $(this).metadata() : {})))
			.unbind('click.fb').bind('click.fb', function(e) {
				e.preventDefault();

				if (busy) {
					return;
				}

				busy = true;

				$(this).blur();

				selectedArray	= [];
				selectedIndex	= 0;

				var rel = $(this).attr('rel') || '';

				if (!rel || rel == '' || rel === 'nofollow') {
					selectedArray.push(this);

				} else {
					selectedArray	= $("a[rel=" + rel + "], area[rel=" + rel + "]");
					selectedIndex	= selectedArray.index( this );
				}

				fancybox_start();

				return false;
			});

		return this;
	};

	$.fancybox = function(obj) {
		if (busy) {
			return;
		}

		busy = true;

		var opts = typeof arguments[1] !== 'undefined' ? arguments[1] : {};

		selectedArray	= [];
		if (opts.selectedIndex) {
			selectedIndex = opts.selectedIndex;
		} else {
			selectedIndex	= 0;
		}

		if ($.isArray(obj)) {
			for (var i = 0, j = obj.length; i < j; i++) {
				if (typeof obj[i] == 'object') {
					$(obj[i]).data('fancybox', $.extend({}, opts, obj[i]));
				} else {
					obj[i] = $({}).data('fancybox', $.extend({content : obj[i]}, opts));
				}
			}

			selectedArray = jQuery.merge(selectedArray, obj);

		} else {
			if (typeof obj == 'object') {
				$(obj).data('fancybox', $.extend({}, opts, obj));
			} else {
				obj = $({}).data('fancybox', $.extend({content : obj}, opts));
			}

			selectedArray.push(obj);
		}

		if (selectedIndex > selectedArray.length || selectedIndex < 0) {
			selectedIndex = 0;
		}

		fancybox_start();
	};

	$.fancybox.showActivity = function() {
		clearInterval(loadingTimer);

		loading.show();
		loadingTimer = setInterval(fancybox_animate_loading, 66);
	};

	$.fancybox.hideActivity = function() {
		loading.hide();
	};

	$.fancybox.next = function() {
		return $.fancybox.pos( currentIndex + 1);
	};
	
	$.fancybox.prev = function() {
		return $.fancybox.pos( currentIndex - 1);
	};

	$.fancybox.pos = function(pos) {
		if (busy) {
			return;
		}

		pos = parseInt(pos, 10);

		if (pos > -1 && currentArray.length > pos) {
			selectedIndex = pos;
			fancybox_start();
		}

		if (currentOpts.cyclic && currentArray.length > 1 && pos < 0) {
			selectedIndex = currentArray.length - 1;
			fancybox_start();
		}

		if (currentOpts.cyclic && currentArray.length > 1 && pos >= currentArray.length) {
			selectedIndex = 0;
			fancybox_start();
		}

		return;
	};

	$.fancybox.cancel = function() {
		if (busy) {
			return;
		}

		busy = true;

		$.event.trigger('fancybox-cancel');

		fancybox_abort();

		if (selectedOpts && $.isFunction(selectedOpts.onCancel)) {
			selectedOpts.onCancel(selectedArray, selectedIndex, selectedOpts);
		}

		busy = false;
	};

	// Note: within an iframe use - parent.$.fancybox.close();
	$.fancybox.close = function() {
		if (busy || wrap.is(':hidden')) {
			return;
		}

		busy = true;

		if (currentOpts && $.isFunction(currentOpts.onCleanup)) {
			if (currentOpts.onCleanup(currentArray, currentIndex, currentOpts) === false) {
				busy = false;
				return;
			}
		}

		fancybox_abort();

		$(close.add( nav_left ).add( nav_right )).hide();

		$('#fancybox-title').remove();

		wrap.add(inner).add(overlay).unbind();

		$(window).unbind("resize.fb scroll.fb");
		$(document).unbind('keydown.fb');

		function _cleanup() {
			overlay.fadeOut('fast');

			wrap.hide();

			$.event.trigger('fancybox-cleanup');

			inner.empty();

			if ($.isFunction(currentOpts.onClosed)) {
				currentOpts.onClosed(currentArray, currentIndex, currentOpts);
			}

			currentArray	= selectedOpts	= [];
			currentIndex	= selectedIndex	= 0;
			currentOpts		= selectedOpts	= {};

			busy = false;
		}

		inner.css('overflow', 'hidden');

		if (currentOpts.transitionOut == 'elastic') {
			start_pos = fancybox_get_zoom_from();

			var pos = wrap.position();

			final_pos = {
				top		:	pos.top ,
				left	:	pos.left,
				width	:	wrap.width(),
				height	:	wrap.height()
			};

			if (currentOpts.opacity) {
				final_pos.opacity = 1;
			}

			fx.prop = 1;

			$(fx).animate({ prop: 0 }, {
				 duration	: currentOpts.speedOut,
				 easing		: currentOpts.easingOut,
				 step		: fancybox_draw,
				 complete	: _cleanup
			});

		} else {
			wrap.fadeOut( currentOpts.transitionOut == 'none' ? 0 : currentOpts.speedOut, _cleanup);
		}
	};

	$.fancybox.resize = function() {
		var c, h;
		
		if (busy || wrap.is(':hidden')) {
			return;
		}

		busy = true;

		c = inner.wrapInner("<div style='overflow:auto'></div>").children();
		h = c.height();

		wrap.css({height:	h + (currentOpts.padding * 2) + titleh});
		inner.css({height:	h});

		c.replaceWith(c.children());

		$.fancybox.center();
	};

	$.fancybox.center = function() {
		busy = true;

		var view	= fancybox_get_viewport(),
			margin	= currentOpts.margin,
			to		= {};

		to.top	= view[3] + ((view[1] - ((wrap.height() - titleh) + (shadow * 2 ))) * 0.5);
		to.left	= view[2] + ((view[0] - (wrap.width() + (shadow * 2 ))) * 0.5);

		to.top	= Math.max(view[3] + margin, to.top);
		to.left	= Math.max(view[2] + margin, to.left);

		wrap.css(to);

		busy = false;
	};

	$.fn.fancybox.defaults = {
		padding				:	10,
		margin				:	20,
		opacity				:	false,
		modal				:	false,
		cyclic				:	false,
		scrolling			:	'auto',	// 'auto', 'yes' or 'no'

		width				:	560,
		height				:	340,

		autoScale			:	true,
		autoDimensions		:	true,
		centerOnScroll		:	false,

		ajax				:	{},
		swf					:	{ wmode: 'transparent' },

		hideOnOverlayClick	:	true,
		hideOnContentClick	:	false,

		overlayShow			:	true,
		overlayOpacity		:	0.3,
		overlayColor		:	'#666',

		titleShow			:	true,
		titlePosition		:	'outside',	// 'outside', 'inside' or 'over'
		titleFormat			:	null,

		transitionIn		:	'fade',	// 'elastic', 'fade' or 'none'
		transitionOut		:	'fade',	// 'elastic', 'fade' or 'none'

		speedIn				:	300,
		speedOut			:	300,

		changeSpeed			:	300,
		changeFade			:	'fast',

		easingIn			:	'swing',
		easingOut			:	'swing',

		showCloseButton		:	true,
		showNavArrows		:	true,
		enableEscapeButton	:	true,

		onStart				:	null,
		onCancel			:	null,
		onComplete			:	null,
		onCleanup			:	null,
		onClosed			:	null
	};

	$(document).ready(function() {
		fancybox_init();
	});

})(jQuery);

// COOKIE Script
var tree = null;

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;
    }
};

// END OTHER SCRIPTS //


// BEGIN MANZ //

/**** OPTIONS *****/
//Fancybox opts
var opts = {
		'titleShow'         : false,
		'transitionIn'		: 'elastic',
		'transitionOut'		: 'elastic',
		'type'              : 'image',
		'overlayShow'		:	true,
		'overlayOpacity'	: 0.7,
		'overlayColor'		:	'#000000',
		'hideOnContentClick': false,
		'callbackOnStart': function() {

			$("#fancy_overlay").bind("click","null");

		}
};


/***** FUNCTIONS *****/
var animating=false;

// Validate input from kunden newsletter form
function checkNewsletterK() {
	if ($("#newsletterk #rechtaktuell:checked").val()==null &&  $("#newsletterk #buchhaktuell:checked").val()==null 
		&& $("#newsletterk #steueraktuell:checked").val()==null && $("#newsletterk #veranstaltung:checked").val()==null
		&& $("#newsletterk #autorennews:checked").val()==null) {
		
		alert("Bitte einen Newsletter auswählen!");
		return false;
	}
	
	if ($("#newsletterk .form-radiobtn:checked").val()==null && $("#newsletterk .radiobtn:checked").val()==null) {
		alert("Bitte eine Anrede auswählen!");
		return false;
	}
	
	if ($("#newsletterk input#vorname").val()=="") {
		alert("Bitte einen Vornamen angeben!");
		return false;
	}
	if ($("#newsletterk input#nachname").val()=="") {
		alert("Bitte einen Nachnamen angeben!");
		return false;
	}
	if ($("#newsletterk #email").val()=="") {
		alert("Bitte eine E-Mail Adresse angeben!");
		return false;
	}
	
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    if(reg.test($("#newsletterk #email").val()) == false) {
    	alert("Die angegebene E-Mail Adresse ist ungültig!");
    	return false;
    }

    if ($("#newsletterk #branche").val()=="") {
		alert("Bitte eine Branche angeben!");
		return false;
	}
	
	return true;
}

//Validate input from autoren newsletter
function checkAutorenNewsletter() {
	if ($("#newsletterautoren .form-radiobtn:checked").val()==null && $("#newsletterautoren .radiobtn:checked").val()==null) {
		alert("Bitte eine Anrede auswählen!");
		return false;
	}
	
	if ($("#newsletterautoren input#vorname").val()=="") {
		alert("Bitte einen Vornamen angeben!");
		return false;
	}
	if ($("#newsletterautoren input#nachname").val()=="") {
		alert("Bitte einen Nachnamen angeben!");
		return false;
	}
	if ($("#newsletterautoren #email").val()=="") {
		alert("Bitte eine E-Mail Adresse angeben!");
		return false;
	}
	
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    if(reg.test($("#newsletterautoren #email").val()) == false) {
    	alert("Die angegebene E-Mail Adresse ist ungültig!");
    	return false;
    }

    if ($("#newsletterautoren #branche").val()=="") {
		alert("Bitte eine Branche angeben!");
		return false;
	}
    
    if(!$("#newsletterautoren input[name='approval']").is(":checked")) {
       alert("Bitte bestaetigen Sie, dass Sie MANZ-AutorIn sind!");
       return false;
    }
	
	return true;
}

//Validate input from fachkonferenz form
function checkFachkonferenz() {
	if ($("#fachkonferenz .form-radiobtn:checked").val()==null && $("#fachkonferenz .radiobtn:checked").val()==null) {
		alert("Bitte eine Anrede auswählen!");
		return false;
	}
	
	if ($("#fachkonferenz input#vorname").val()=="") {
		alert("Bitte einen Vornamen angeben!");
		return false;
	}
	if ($("#fachkonferenz input#nachname").val()=="") {
		alert("Bitte einen Nachnamen angeben!");
		return false;
	}
	if ($("#fachkonferenz #email").val()=="") {
		alert("Bitte eine E-Mail Adresse angeben!");
		return false;
	}
	
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    if(reg.test($("#fachkonferenz #email").val()) == false) {
    	alert("Die angegebene E-Mail Adresse ist ungültig!");
    	return false;
    }

    if ($("#fachkonferenz #branche").val()=="") {
		alert("Bitte eine Branche angeben!");
		return false;
	}
    
    if ($("#fachkonferenz #strasse").val()=="") {
		alert("Bitte eine Strasse angeben!");
		return false;
	}
    
    if ($("#fachkonferenz #plz").val()=="") {
		alert("Bitte eine PLZ angeben!");
		return false;
	}
    
    if ($("#fachkonferenz #ort").val()=="") {
		alert("Bitte einen Ort angeben!");
		return false;
	}
    
    if ($("#fachkonferenz #veraa:checked").val()==null) {
    	alert("Sie müssen mit den Anmeldebedingungen einverstanden sein.");
		return false;
    }
	
	return true;
}

//Validate input from gewinnspiel form
function checkGewinnspiel() {
	if ($("#gewinnspiel .form-radiobtn:checked").val()==null && $("#gewinnspiel .radiobtn:checked").val()==null) {
		alert("Bitte eine Anrede auswählen!");
		return false;
	}
	
	if ($("#gewinnspiel input#vorname").val()=="") {
		alert("Bitte einen Vornamen angeben!");
		return false;
	}
	if ($("#gewinnspiel input#nachname").val()=="") {
		alert("Bitte einen Nachnamen angeben!");
		return false;
	}
	if ($("#gewinnspiel #email").val()=="") {
		alert("Bitte eine E-Mail Adresse angeben!");
		return false;
	}
	
	if ($("#gewinnspiel #strasse").val()=="") {
		alert("Bitte eine Strasse angeben!");
		return false;
	}
	
	if ($("#gewinnspiel #plz").val()=="") {
		alert("Bitte eine PLZ angeben!");
		return false;
	}
	
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    if(reg.test($("#gewinnspiel #email").val()) == false) {
    	alert("Die angegebene E-Mail Adresse ist ungültig!");
    	return false;
    }

    return true;
}

// Validate input from buchhaendler newsletter form
function checkNewsletterB() {
	if ($("#newsletter input#buchhandlung").val()=="") {
		alert("Bitte einen Buchhandlung angeben!");
		return false;
	}
	
	if ($("#newsletter .form-radiobtn:checked").val()==null && $("#newsletter .radiobtn:checked").val()==null) {
		alert("Bitte eine Anrede auswählen!");
		return false;
	}
	
	
	if ($("#newsletter input#vorname").val()=="") {
		alert("Bitte einen Vornamen angeben!");
		return false;
	}
	if ($("#newsletter input#nachname").val()=="") {
		alert("Bitte einen Nachnamen angeben!");
		return false;
	}
	if ($("#newsletter #email").val()=="") {
		alert("Bitte eine E-Mail Adresse angeben!");
		return false;
	}
	
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    if(reg.test($("#newsletter #email").val()) == false) {
    	alert("Die angegebene E-Mail Adresse ist ungültig!");
    	return false;
    }

    if ($("#newsletter #branche").val()=="") {
		alert("Bitte eine Branche angeben!");
		return false;
	}
	
	$("#newsletter").submit();
}

//ShowText
function showText(what,text) {
	$("#message-added-"+what+" .header").text(" ");
	$("#message-added-"+what+" .author").text(" ");
	$("#message-added-"+what+" .header").text(" ");
	$("#message-added-"+what+" .title strong").text(" ");
	$("#message-added-"+what+" .notes").html("<b>"+text+"</b>");
}

// Small Slider wird geladen und angezeigt.
function loadSmallSlider() {
	$("#stage-close").hide();
	var rand=String((new Date()).getTime()).replace(/\D/gi, '');
	
	var parameter="?back="+get_url_parameter("back")
				+"&page="+get_url_parameter("page")
				+"&sort="+get_url_parameter("sort")
				+"&rand="+rand;
	
	var url="administration/SmallSlider.html"+parameter;
	//$("#stage .page .stage-slider").remove();
	
	$("#stage-slider-small").load(contexttPath + url + " #stage-slider-small",function() {
		/** SMALL SLIDER on product page (http://flowplayer.org/tools/scrollable.html) */
		var scroll = $("#stage-slider-small .scrollable").scrollable({	
			size: 3,
			speed: 500,
			api: true
		});
		
		 $("#stage-slider-small .scrollable .items li").click(function(){
			loadProduct($(this));
		});
		 
		 var len = 0;
		 if ($("#stage-slider-small").length>=1) 
		 {
			len = $("#stage-slider-small").html().length;
			if (len>1) {
				$("#stage .stage-slider").show();			
				$("#stage").slideDown("normal",function() {
					showBuehne();
				});
			}
		 }
	});
}

// Dazu passend wird geladen und angezeigt.
function loadDazuPassend() {
	var rand=String((new Date()).getTime()).replace(/\D/gi, '');
	var str=$(".sstring").text();
	str=str.replace(/\n/g, "");
	str=str.replace(/ /g, "");
	var isbn=get_url_parameter("isbn");
	if (isbn.length<3)
	{
		isbn=get_url_parameter("tisbn");
	}
	var parameter="?str="+str
				+"&rand="+rand
				+"&isbn="+isbn;
	
	if (get_url_parameter("pdebug")!="") {
		alert("administration/DazuPassend.html"+parameter);
	}
	var url="administration/DazuPassend.html"+parameter;
	
	$(".related").load(contexttPath + url + " .related > *",function () {
		if (get_url_parameter("pdebug")!="") {
			alert($(this).html());
		}
		/** ADD TO WATCHLIST **/
		$(".btn-addtowatchlist, .btn-addtowatchlist-icon").click(function(){
			addTo($(this),"watchlist");
			showMessage("message-added-watchlist");		
			
		});
		
		$(".btn-addtocart, .btn-addtocart-icon").unbind("click");
		
		/** ADD TO CART **/
		$(".btn-addtocart, .btn-addtocart-icon").click(function(){
			addTo($(this),"cart");
			showMessage("message-added-cart");		
		});
		
		$(this).hide().fadeIn(function() {
			if(jQuery.browser.msie){
		        $(this).get(0).style.removeAttribute("filter");                    
		    }
		});
	});
}


/***** AUSBLENDUNG HEADER ERGEBNISSE */
function showBuehne() {
	if ($(".infobar-top") != null) {
		/* MANZ Header Trefferliste */
		var isbn = get_url_parameter("isbn");
		
		if(isbn) 
		{
			var found = $("#buehne_isbn:contains(" + isbn + ")");
			if (found) {
				if ($("#stage-slider-small .scrollable")) 
				{
				    var api = $("#stage-slider-small .scrollable").scrollable(); 
					if(typeof api.getItems == 'function') {
						var index = api.getItems().filter(":contains(" + isbn + ")").getIndex();
						api.getItems().filter(":contains(" + isbn + ")").addClass("active");
						api.seekTo(index,250);
						api.reload();
					}
				}
			}
		} else {
			if ($(".showBooks").length<1) {
				$("#stage .stage-slider").remove();
			}
		}
	}
}


/** TRIM function **/
function trim(s)
{
    var l=0; var r=s.length -1;
    while(l < s.length && s[l] == ' ')
    {     l++; }
    while(r > l && s[r] == ' ')
    {     r-=1;     }
    return s.substring(l, r+1);
} 
// URL Parameter
function get_url_parameter(name)
{
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href);
	if( results == null ) {
		return "";
	} else {
	    return results[1];
	}
}
// IsbN wird ueberprueft
function checkISBN() {
	var link = location.href;
	var isbn=get_url_parameter("isbn");
	var isbn_inp = document.getElementById("isbn").value;
	
	if (isbn=="") {
		if (isbn_inp != "") {
			link+="&isbn=" + isbn_inp;
		}
	} else {
		link=link.substring(0,link.indexOf("&isbn="));
		
		if (isbn_inp != "") {
			link+="&isbn=" + isbn_inp;
		}
		
	}
	
	link+="&checkISBN=1";
	
	window.location.href=link;
}


/* QUICK SEARCH */
function checkQuick() {
	var quick = trim(document.getElementById("quick").value);
	
	if (quick!="" && quick!="Autor, ISBN, Verlag, Stichwort, ...") {
		return true;
	} else {
		return false;
	}
}

function trackPage(toTrack) {
	var _gaq = _gaq || [];
	_gaq.push(['_setAccount', 'UA-16905329-2']);
    _gaq.push(['_trackPageview',toTrack]);
    _gaq.push(['_anonymizeIp']);
    
	$.getScript("http://www.google-analytics.com/ga.js",function() {
	     var pageTracker = _gat._getTracker('UA-16905329-2');
         pageTracker._trackPageview(toTrack); 
     });
}

function PWRemind() {
	var user=document.getElementById("user").value;
	if (user) {
		top.window.location.href='https://www.buchmedia.at/manz/konto?pwremind=1&check='+user;
	} else {
		top.window.location.href='https://www.buchmedia.at/manz/konto?pwremind=1';
	}
}

/* WARENKORB UND REMIND WERTE SETZEN */
function loadNumbers() {
	var rand=String((new Date()).getTime()).replace(/\D/gi, '');
	
	$("#tool-cart .value").load(contexttPath + "administration/basketdata.html?rand=" + rand + " .sumwarenkorb",function (){
		var num = $(this).find(".sumwarenkorb").attr("value");
		
		if (!num) 
		{
			num="0";
		}
		
		$(this).text(num);
		
		if (parseInt(num)>0) {
			$("#tool-cart").addClass("highlighted");
			$("#message-added-cart").css("right","48px");
			$("#message-added-watchlist").css("right","110px");
		} else {
			$("#tool-cart").removeClass("highlighted");
			$("#message-added-cart").css("right","-5px");
			$("#message-added-watchlist").css("right","48px");
		}
		if (num=="0") 
		{
			num="1";
		}
		
		wknum=parseInt(num);
	});
	
	$("#tool-watchlist .value").load(contexttPath + "administration/notepaddata.html?rand=" + rand + " .summerkzettel",function (){
		var num = $(this).find(".summerkzettel").attr("value");
		if (!num) {
			num="0";
		}
		$(this).text(num);
		if (num>0) {
			$("#tool-watchlist").addClass("highlighted");
		} else {
			$("#tool-watchlist").removeClass("highlighted");
		}
		if (num=="0") {
			num="1";
		}
		
		mznum=parseInt(num);
	});
}

function loadBasket() {
	var rand=String((new Date()).getTime()).replace(/\D/gi, '');
	$("#stage-cart").load(contexttPath + "administration/basketdata.html?rand=" + rand + " #basketdata",function (){
		$("#stage-cart .btn-delete").click(function() {
			deleteFromBasket($(this));
		});
		
		/** REFRESH CART **/
		$("#stage-cart .btn-refresh").click(function(){
			refreshBasket();
		});
		
		$("#stage-cart .btn-addtowatchlist-small").click(function() {
			addTo($(this),"watchlist");
			showMessage("message-added-watchlist");	
			loadNotepad();
		});
	});
	
}

function loadNotepad() {
	var rand=String((new Date()).getTime()).replace(/\D/gi, '');
	
	$("#stage-watchlist").load(contexttPath + "administration/notepaddata.html?rand=" + rand + " #notepaddata",function (){
		$("#stage-watchlist .btn-delete").click(function() {
			deleteFromNotepad($(this));
		});
		
		$(".btn-addtocart-small").click(function() {
			addTo($(this),"cart");
			showMessage("message-added-cart");	
			loadBasket();
		});
		//var toSet=122*wknum+109;
		//$("#stage1").css("height",toSet + "px");
	});
}

//addTo
function addTo(me,what) {
	var rand=String((new Date()).getTime()).replace(/\D/gi, '');
	// Values werden gelesen
	var parent = me.parent();
	var isbn = parent.children(".param_isbn").text();
	var text = parent.children(".param_text").text();
	var autor = parent.children(".param_autor").text();
	var preis = parent.children(".param_preis").text();
	var utitel = parent.children(".param_utitel").text();
	var titel = parent.children(".param_titel").text();
	var download = parent.children(".param_download").text();
	var chk = parent.children(".param_chk").text();
	var cover = "http://manz.buchmedia.at/cover/" + parent.children(".param_cover").text();
	
	// Setze values
	$("#message-added-"+what+" .author").text(autor);
	$("#message-added-"+what+" .title strong").text(titel);
	$("#message-added-"+what+" .notes").text(text);
	
	var basketnotepad="basketdata";
	if (what=="watchlist") {
		trackPage("/addnotepad.html");
		basketnotepad="notepaddata";
		var found = $("#notepaddata .param_isbn:contains(" + isbn + ")");
		
		if (found.html()) {
			showText("watchlist","Der Titel ist bereits vorgemerkt.");
			return false;
		}
		
	}
	if (what=="cart") {
		basketnotepad="basketdata";
		trackPage("/addbasket.html");
		var found = $("#basketdata .param_isbn:contains(" + isbn + ")");
		if (found.length>=1) {
			var num=parseInt($("[name=" + isbn + "]").val());
			num++;
			$("[name=" + isbn + "]").val(num);
			refreshBasket();
			
			return false;
		}
	}
	// Übergebe per AJAX an buchmedia
	var url = contexttPath + "administration/"+basketnotepad+".html?rand=" + rand + "&add=" + escape(isbn) + "&titel=" + escape(titel) + "&autor=" 
						   + escape(autor) + "&preis=" + escape(preis) + "&ztext=" + escape(text) + "&utitel=" + escape(utitel) + "&anzahl=1&chk="+chk;
	
	if (download.length>=1) {
		url=url+"&download=libreka";
	}
	
	$.get(url,function() {
		
		if (what=="cart") {
			loadBasket(); 
			if ($("#tool-checkout").css("margin-left")=="0px") {
				$("#tool-checkout").animate({"width": "55px", "margin-left": "7px"});
			}
			
		}
		if (what=="watchlist") {
			loadNotepad();
		}
		
		
		loadNumbers();
	});
}

function loadAutoren(t, charrr) {
	$("#select-author li a").each(function() {
		$(this).removeClass("selected");
	});
	
	t.addClass("selected");
	
	if (charrr!="#newautor") {
		if (charrr) {
			charrr=charrr.substring(8,7);
			url=contexttPath + "autoren/liste/"+charrr+".html?load=1";
			
			if ($(".authors-namelist").css("display")=="none") {
				loadAutorenData(url);
				
			} else {
				$(".authors-namelist").slideToggle("slow",function (){
					loadAutorenData(url);
				});
				
			}
		}
	} else {
		var url=contexttPath + "autoren/liste/A.html?newautor=true&load=1";
		if ($(".authors-namelist").css("display")=="none") {
			loadAutorenData(url);
			
		} else {
			$(".authors-namelist").slideToggle("normal",function (){
				loadAutorenData(url);
			});
			
		}
	}
}

function loadAutorenData(url) {
	$.cookie("completedss","1");
	
	$(".authors-namelist #autor-A").load(url+" .authors-namelist #autor-A",function (){
		var exists = $(".switchname").data("events");
		if (!exists) 
		{
			$(".switchname").click(function() {
				var name=$(this).attr("id");
				//$("#sidebar").fadeOut("normal");
				
				loadAutor(name);
			});
			
			if ($.cookie("completedss")!=null) 
			{
				$.cookie("completedss",null);
				$(".authors-namelist").slideToggle("slow", function() {
					$.cookie("completedss","1");
				});
			}
		}
	});
}

function loadAutor(name) {
	$("#autordata").fadeOut("normal",function() {
		// Load autor data
		$("#autordata").load(name +" #autordata",function (){
			$(this).fadeIn("normal");
		});
		
		// Load teaser right
		//$("#sidebar").load(name+" #sidebar",function (){
		//	$(this).fadeIn("normal");
		//});
		
		$(".authors-namelist").slideToggle("slow");
	});
}


/* SHOWING HIDING STICHWORT / SCHLAGWORTE */
function showHideE(target) {
	if ($(target).css("display")=="block")
	{
		$(target).css("display","none");
	} else {
		$(target).css("display","block");
	}
}

function deleteFromNotepad(me) 
{
	var rand=String((new Date()).getTime()).replace(/\D/gi, '');
	trackPage("deleteFromNotepad.html");
	// Values werden gelesen
	var parent = me.parent();
	var isbn = parent.children(".param_isbn").text();
	
	// Übergebe per AJAX an buchmedia
	var url = contexttPath + "administration/notepaddata.html?del=" + escape(isbn) + "&rand=" + rand;
	
	$.get(url,function() {
		loadNotepad();
		var quantity = parseInt($("#tool-watchlist .value").html());
		quantity--;
		
		if (quantity<1) {
			showStage("#stage-watchlist");
		}
		
		loadNumbers();
	});
	
	
}

function deleteFromBasket(me) {
	var rand=String((new Date()).getTime()).replace(/\D/gi, '');
	// Values werden gelesen
	var parent = me.parent();
	var isbn = parent.children(".param_isbn").text();
	trackPage("deleteFromBasket.html");
	// Übergebe per AJAX an buchmedia
	var url = contexttPath + "administration/basketdata.html?del=" + escape(isbn) + "&rand=" + rand;
	
	$.get(url,function() {
		var rand=String((new Date()).getTime()).replace(/\D/gi, '');
		
		$("#stage-cart").load(contexttPath + "administration/basketdata.html?rand=" + rand + " #basketdata",function (){
			$("#stage-cart .btn-delete").click(function() {
				deleteFromBasket($(this));
			});
			
			/** REFRESH CART **/
			$("#stage-cart .btn-refresh").click(function(){
				refreshBasket();
			});
			
			$("#stage-cart .btn-addtowatchlist-small").click(function() {
				addTo($(this),"watchlist");
				showMessage("message-added-watchlist");	
				loadNotepad();
			});
			
			var quantity = parseInt($(this).find(".total-quantity span").text());
			if (!quantity) {
				$("#tool-checkout").css({"width": "0", "margin-left": "0"});
				showStage("#stage-cart");	
			}
			
			loadNumbers();
		});
	});
}

function refreshBasket() {
	var rand=String((new Date()).getTime()).replace(/\D/gi, '');
	var anz=$("*").find(".sumwarenkorb").attr("value");
	trackPage("/refreshbasket.html");
	anz++;
	
	var url=contexttPath + "administration/basketdata.html?updatebasket=1&rand=" + rand;
	
	for (var i=1;i<anz;i++) {
		var val=parseInt($("#wk-stueckzahl-ware" + i).attr("value"));
		if (val) {
			if (val==0) {
				val=1;
			}
			var ISBN=$("#wk-stueckzahl-ware" + i).attr("name");
			url+="&anz" + i + "=" + ISBN + ":" + val;
		}
	}
	
	$.get(url, function() {
		loadBasket();
		loadNumbers();
	});	
}

$.fn.getIndex = function(){
	var $p=$(this).parent().children();
	return $p.index(this);
};


/** opens the stage with a certain content (or closes it) **/
function showStage(id, callback) {	
	// hide closing button (because it looks nicer this way)
	$("#stage-close").hide();
	
	// check if stage should be closed (if wanted stage is already open)
	var close = false;
	if ($("#stage #"+id+":visible").length >= 1) {
		close = true;
		if (id=="stage-adv-search") {
			trackPage("/hideErwSuche.html");
		}
		
		if (id=="stage-account") {
			trackPage("/hideAccount.html");
		}
		
		if (id=="stage-watchlist") {
			trackPage("/hideNotepad.html");
		}
		
		if (id=="stage-cart") {
			trackPage("/hideBasket.html");
		}
	} else {
		if (id=="stage-adv-search") {
			trackPage("/showErwSuche.html");
		}
		
		if (id=="stage-account") {
			trackPage("/showAccount.html");
		}
		
		if (id=="stage-watchlist") {
			trackPage("/showNotepad.html");
		}
		
		if (id=="stage-cart") {
			trackPage("/showBasket.html");
		}
	}
	
	// hide stage content before sliding up (avoids display bugs in IE 6 & 7)	
	if ($.browser.msie && ($.browser.version == "6.0" || $.browser.version == "7.0")) {
		$("#stage .stage-content").hide();		
	}
	
	// slide up stage
	$("#stage").slideUp("normal", function(){		
		if (!close) { // show wanted content						
			$("#stage .stage-content").hide();
			$("#stage #" + id).show();
			if (!$("#stage #" + id).hasClass("stage-slider")) {
				$("#stage-close").show();	
			}
			$("#stage").slideDown("normal", callback);
		} else if ($("#stage .stage-slider").length >= 1) { // show slider again			
			$("#stage .stage-content").hide();
			$("#stage .stage-slider").show();			
			$("#stage").slideDown("normal", callback);	
		}					
	});	
}
var loaded=false;

$.addthis = function(code)
{
	
	function init()
	{
		try
		{
			// determine whether to include the normal or SSL version
			var addthisurl = (location.href.indexOf("https") == 0 ? "https://" : "http://") + "s7.addthis.com/js/250/addthis_widget.js?pub=" + code;
			
			// isbn
			var isbn="";
			
			var isbn=$(".buy .inside .param_isbn:first").text();
			
			// include the script
			$.getScript(addthisurl, function()
			{
					var $url="http://www.manz.at/list.html?isbn="+isbn;
				
					var addthis_share = {
				    		url : $url
				    };
				    addthis_share.url=$url;
				    
				    var tit=$(".product-header h1").text();
				    if (tit.length>=20) {
				    	tit=tit.substring(0,20)+"...";
				    }
				    var title=tit + " - "+isbn;
				    var twitterurl="http://twitter.com/share?url="+$url+"&text="+title+"&via=AddThis";
					$toaddthis='<br /><div class="addthis_toolbox addthis_default_style"><a href="http://www.addthis.com/bookmark.php?v=250&amp;username=xa-4c50379b67c47cf7" class="addthis_button_compact at300m"><span class="at300bs at15t_compact"></span>Share</a><span class="addthis_separator">|</span> ';
					$toaddthis2='<a class="addthis_button_favorites at300b" title="Add To Favorites"><span class="at300bs at15t_favorites"></span></a>';
					$toaddthis3='<a title="Send to Facebook"></a><a title="Send to Facebook" target="_blank" href="http://www.addthis.com/bookmark.php?v=250&amp;winname=addthis&amp;pub='+code+'&amp;source=tbx-250&amp;lng=en-US&amp;s=facebook&amp;url=http%3A%2F%2Fwww.manz.at%2Flist.html?isbn='+isbn+'&amp;title=MANZ&amp;ate=AT-'+code+'/-/pz-2/4c907c0b748b4fdd/1&amp;CXNID=2000001.5215456080540439074NXC&amp;tt=0" class="addthis_button_facebook at300b"><span class="at300bs at15t_facebook"></span></a> <a title="Tweet This" target="_blank" href="'+twitterurl+'"><span class="at300bs at15t_twitter"></span></a> <a title="Send to Google" target="_blank" href="http://www.addthis.com/bookmark.php?v=250&amp;winname=addthis&amp;pub='+code+'&amp;source=tbx-250&amp;lng=en-US&amp;s=google&amp;url='+$url+'&amp;title=MANZ&amp;ate=AT-xa-4c50379b67c47cf7/-/pz-2/4c907c0b748b4fdd/2&amp;CXNID=2000001.5215456080540439074NXC&amp;tt=0" class="addthis_button_google at300b"><span class="at300bs at15t_google"></span></a> <div class="atclear"></div></div>';
					$("a.addthis").append($toaddthis+$toaddthis2+$toaddthis3);
					$(".addthis_button_compact").mouseover(
						function()
						{
							return addthis_open(this, "", $url, "[TITLE]");
						}).mouseout(function(){
									addthis_close();
						}).click(function(){
									return addthis_sendto();
						}
					);
					
					if ($("#product").length>0) {
						loaded=true;
					} else {
						loaded=false;
					}
					if (loaded) {
						$(".addthis_button_favorites").click(function() {
							if (window.chrome) {
								alert("Bitte drücken Sie <Command>+D um die Seite zu Ihren Favoriten hinzuzufügen.");
							} else if (window.sidebar) 
							{
								window.sidebar.addPanel(document.title, location.href,"");
							} else if(window.external) 
							{
								window.external.AddFavorite(location.href, document.title);
							} else if(window.opera)
							{
								var elem = document.createElement("a");
							    elem.setAttribute("href",location.href);
							    elem.setAttribute("title",document.title);
							    elem.setAttribute("rel","sidebar");
							    elem.click();
							}
						});
					}
			});
		} catch(err) {
			// log any failurea
			console.log("Failed to load AddThis Script:" + err);
		}
	}

	init();
};



function loadProduct(me) {
	loaded=true;
	
	$(".related").html(" ");
	var insert = "<div style='padding-left: 100px;padding-top: 10px;'><img src='" + contexttPath + "docroot/images/loading.gif'></div>";
	$("#product").html(insert);
	
	var isbn = me.find("#buehne_isbn").html();
	var rand=String((new Date()).getTime()).replace(/\D/gi, '');
	
	$("#product").load(contexttPath + "list.html?isbn=" + isbn + "&rand=" + rand + " #product > *",function ()
	{
		if ($(".widget").length)
		{
			loadWidget(isbn);
		}
		
		$(this).hide().fadeIn("slow",function() {
			if(jQuery.browser.msie){
		        $(this).get(0).style.removeAttribute("filter");                    
		    }
		});
		
		var content=$(this).html();
		loadDazuPassend();
		
		/** ADD TO WATCHLIST **/
		$(".btn-addtowatchlist, .btn-addtowatchlist-icon").click(function(){
			addTo($(this),"watchlist");
			showMessage("message-added-watchlist");		
			
		});
		
		$(".btn-addtocart, .btn-addtocart-icon").unbind("click");
		
		/** ADD TO CART **/
		$(".btn-addtocart, .btn-addtocart-icon").click(function(){
			addTo($(this),"cart");
			showMessage("message-added-cart");		
		});
		
		/** TABS **/
		$(".tabs .nav").tabs(".tabs .content");
		
		/*** STICHWORTE EINBLENDEN */
		$(".stichworte").click(function(){
			showHideE(".tab1");
		});
		
		/***** Lightbox Funktionalität */
		$("a.zoom").fancybox(opts);
		
		$.addthis("xa-4c8f6a1447b0008e");
		
	});
}

// Loads the bicmedia widget
function loadWidget(toLoad) {
	var bicmediaopts="lang=de,buyButton=no,tellafriend=no,showTAFButton,showTitleInPopUp=no,arrowTeaser=true,bgcolorArrowTeaser=FFFFFF";
	
	if (GetSwfVer()==-1) 
	{
		$(".widget").hide();
		$(".widget-fallback").show();
	} else {
		var widget = DMRWidget(toLoad,bicmediaopts);
		$(".widget").prepend(widget);
	}
}

/** shows a message **/
function showMessage(id) {	
	$("#toolbar .message").css("z-index", 1);
	var msg = $("#" + id);
	msg.css("z-index", 20);	
	var duration = 2000;
	if (typeof $.browser.msie == "undefined") { // hide fading from ie because it looks ugly	
		msg.fadeIn("normal", function(){
			window.setTimeout(function(){
				msg.fadeOut();
			}, duration);
		});
	} else {
		msg.show();
		window.setTimeout(function(){
			msg.hide();
		}, duration);
	}
}

function switchToSubnav(idx) {	
	//console.log("switchToSubnav: "+idx);	
	$("#nav-main > li").removeClass("hover").find(".subnav").css("left", "-9999px");
	
	if ($(".subnav-smaller").length > 0) {
		if (idx != null) {			
			$("#nav-main > li:eq(" + idx + ")").each(function(){
				if ($("#nav-main").hasClass("subnav-smaller")) {
					var posLeft = $(this).position().left - 5;
				} else {
					var posLeft = -4;
				}
				$(this).addClass("hover").find(".subnav").css("left", posLeft + "px");
			});
		}
	} else {
		if (idx != null) {
			$("#nav-main > li:eq(" + idx + ")").addClass("hover").find(".subnav").css("left", "-4px");
		}
	}
}

function getNum(what) {
	loadNumbers();
	
	var quantity = parseInt($("#tool-" + what + " .value").html());
	
	return quantity;
}

function showText(what,text) {
	$("#message-added-"+what+" .header").text(" ");
	$("#message-added-"+what+" .author").text(" ");
	$("#message-added-"+what+" .header").text(" ");
	$("#message-added-"+what+" .title strong").text(" ");
	$("#message-added-"+what+" .notes").html("<b>"+text+"</b>");
}
// END FUNCTIONS //

// DOCUMENT READY (jQuery functions)

$(document).ready(function() {
	/** MAIN NAV **/	
	$("#nav-main").hover(function(){
		//console.log("#nav-main OVER");
	},function(){
		//console.log("#nav-main OUT");
		window.clearTimeout(timeoutID);
		timeoutID = window.setTimeout('switchToSubnav(null)', 300);		
	});
	var timeoutID;
	$("#nav-main > li").hover(function(){		
		//console.log("#nav-main > li OVER");
		window.clearTimeout(timeoutID);		
		timeoutID = window.setTimeout("switchToSubnav("+$(this).index()+")", 300);		
	},function(){
		//console.log("#nav-main > li OUT");		
	});
	
	/** SEARCH **/
	var inputText = $("#tools input.text");
	// show example string "SUCHE"
	if (inputText.val() == "") {
		inputText.addClass("example");
	}	
	// hide example string
	inputText.focus(function(){
		$(this).removeClass("example");
	});
	
	/** STAGE **/	
	// show slider stage if there is one	
	if ($("#stage .stage-slider").length == 1) {		
		$("#stage .stage-slider").show();
		$("#stage").show();
		$("#stage-close").hide();
	}		

	// actions	
	$("#tool-adv-search").click(function(){		
		showStage("stage-adv-search", function(){ 
			$("#stage-adv-search input:first").focus(); 
		});		
	});
	
	$("#tool-watchlist").click(function(){
		if (getNum("watchlist")>=1) {
			showStage("stage-watchlist");
		} else {
			showText("watchlist","Sie haben derzeit keine Titel vorgemerkt.");
			showMessage("message-added-watchlist");	
		}
	});
	$("#tool-cart").click(function(){
		if (getNum("cart")>=1) {
			showStage("stage-cart");
		} else {
			showText("cart","Sie haben derzeit keine Titel im Warenkorb.");
			showMessage("message-added-cart");
		}
	});
	$("#stage-close").click(function(){
		$("#stage").slideUp("normal");
		// show slider stage again if there is one
		if ($("#stage .stage-slider").length >= 1) {
			showStage($("#stage .stage-slider").attr("id"));			
		}
	});

	
	/* advanced search */		
	$("#stage-adv-search .fieldset input, #stage-adv-search .fieldset select").focus(function(){
		// move pointer
		var position = $(this).position();
		var positionY = position.top - 2;
		$("#stage-adv-search .info").css("background-position", "0 " + positionY + "px");
		
		// load text				
		$("#stage-adv-search .info").load(contexttPath + "administration/hilfe_erw_suche.html #help-" + $(this).attr("id"));
	});
	
	/** BIG SLIDER on home page (http://flowplayer.org/tools/scrollable.html) **/
	if ($("#stage-slider-big").length == 1) {
		// init & config
		var bigSlider = $("#stage-slider-big .scrollable").scrollable({
			api: true,
			loop: true,
			size: 6,
			speed: 1000
		});
		
		// circular plugin
		$("#stage-slider-big .scrollable").circular();
		
		// autoscroll plugin	
		$("#stage-slider-big .scrollable").autoscroll({
			interval: 3000
		});
		
		// no auto srcolling when tooltip is visible
		bigSlider.onBeforeSeek(function(){
			if ($("#slider-big-tooltip:visible").length == 1) {
				bigSlider.pause();
				return false;
			}
		});
		
		// controls
		$("#stage-slider-big .controls .pause").toggle(function(){
			$(this).addClass("stopped");
			$(this).attr("title", "Play");
			bigSlider.stop();
		}, function(){
			$(this).removeClass("stopped");
			$(this).attr("title", "Pause");
			bigSlider.play();
		});
		
		/** TOOL TIP (http://flowplayer.org/tools/tooltip.html) **/
		$("#slider-big-tooltip").appendTo("#stage"); // move tooltip outside of .page because of absolute positioning
		$("#stage-slider-big .scrollable a").tooltip({
			cancelDefault: false, // disable removing of title attribute
			//effect: 'slide',
			lazy: false,		
			tip: '#slider-big-tooltip',		
			offset: [-160, 0],
			position: 'bottom right',		
			onBeforeShow: function(event, pos) {
				// copy tooltip content to trigger (done this way because of positioning)		
				var trigger = this.getTrigger();
				$("#slider-big-tooltip .inside").html(trigger.next(".tooltip").html());
				
				//console.log("Tooltip: onBeforeShow");
			}
		}).dynamic({
			classNames: 'top right tooltip-bottom tooltip-left',
			bottom: {
				offset: [0, 0]
			}
		});
	}		
		

	/** SMALL SLIDER on product page (http://flowplayer.org/tools/scrollable.html) */
	$("#stage-slider-small .scrollable").scrollable({		
		size: 3,
		speed: 500
	});
	
	/** TOPIC NAV **/
	// close all that are not flagged as open
	$("#nav-topic > li").each(function(){
		if (!$(this).hasClass("open")) {
			$("ul", this).hide();
		}
	});

	// opening/closing
	$("#nav-topic .toggle").click(function(){
		// get current item
		var li = $(this).closest("li");	
		var li_idx = li.index();
		
		// close other open items
		$("#nav-topic > li.open").each(function(){
			if ($(this).index() != li_idx) {
				$(this).removeClass("open");
				$(this).find("ul").slideToggle();	
			}						
		});		
		
		// toggle current item
		li.find("ul").slideToggle();
		li.toggleClass("open");
		
		return false;
	});
	
	/** PRODUCTS NAV **/
	// init treeview plugin (http://docs.jquery.com/Plugins/Treeview/treeview)
	tree = $("#nav-products > ul").treeview({				
		collapsed: true,
		persist: "location",
		unique: true
	});	
	// make node links also collapsable
	$("#nav-products .collapsable > a, #nav-products .expandable > a").click(function(){
		$(this).parent().find("> .hitarea").click();
		return false;	
	});	
	
	/** TABS **/
	$(".tabs .nav").tabs(".tabs .content");
	
	/** ADD TO WATCHLIST **/
	var quantity_watchlist = parseInt($("#tool-watchlist .value").html());
	// hide checkout button if cart is empty
	if (quantity_watchlist > 0) {		
		$("#tool-watchlist").addClass("highlighted");
	}
	// add to watchlist action 
	$(".btn-addtowatchlist").click(function(){
		showMessage("message-added-watchlist");		
	});
	
	/** ADD TO CART **/
	var quantity = parseInt($("#tool-cart .value").html());
	// hide checkout button if cart is empty
	if (quantity == 0) {			
		$("#tool-checkout").css({"width": "0", "margin-left": "0"});
	}
	
	// add to cart action 
	$(".btn-addtocart").click(function(){
		showMessage("message-added-cart");		
		// move in checkout button
		if (quantity == 0) {
			$("#tool-checkout").animate({"width": "55px", "margin-left": "7px"});
		}
	});

	/***** AUSBLENDUNG HEADER ERGEBNISSE */
	if ($(".infobar-top") != null) {
		/* MANZ Header Trefferliste */
		var isbn = get_url_parameter("isbn");
		
		if(isbn) {
			var found = $("#buehne_isbn:contains(" + isbn + ")");
			if (found) {
				if ($("#stage-slider-small .scrollable")) {
					var api = $("#stage-slider-small .scrollable").scrollable(); 
					if(typeof api.getItems == 'function') {
						api.getItems().filter(":contains(" + isbn + ")").click();
						api.reload();
					}
				}
			}
		}
	}
	
	if ($("#stage-slider-big").length <1) {
		$("#stage").hide();
	}
	var url=window.location.href;
	if (contexttPath.substring(contexttPath.length-1)!="/"
		&& url.indexOf("file:")==-1) {
		contexttPath+="/";
	} 
	
	// Gallery
	if($(".scrollable_gallery").length) {
		Galleria.loadTheme(contexttPath + "docroot/galleria/themes/classic/galleria.classic.js");
		$(".scrollable_gallery").galleria({
			height	: 400
	    });
	}
	
	// Gallery
	if($(".galleryteaser").length) {
		Galleria.loadTheme(contexttPath + "docroot/galleria/themes/lightbox/galleria.lightbox.js");
		$(".galleryteaser").galleria({
			height	: 400
	    });
	}
	
	// Fancybox
	$("div.gallery_selected").click(function(){
		var all=new Array();
		var current=escape($(this).find("img").attr("src"));
		
		$("div.scrollable_gallery ul.gallery li").each(function(index) {
			var src=$(this).find("img").attr("src");
			all[index]=src;
			
			if (current==src) {
				current=index;
			}
			opts["selectedIndex"]=current;
		});
		
		$.fancybox(all, opts);
	});
	
	// Fancybox Teaser-Gallery
	$("div.teaser-gallery ul.gallery li").click(function(){
		var all=new Array();
		var current=escape($(this).find("img").attr("src"));
		
		$("div.teaser-gallery ul.gallery li").each(function(index) {
			var src=$(this).find("img").attr("src");
			all[index]=src;
			
			if (current==src) {
				current=index;
			}
			opts["selectedIndex"]=current;
		});
		
		$.fancybox(all, opts);
	});
	
	// Basket and others
	var wknum="0";
	var mznum="0";
	
	/**** Hilfefunktion f. Detailsuche   */
	$('input.suche-feld-first,input.suche-feld,select.sort-buchform-field,input.suche-feld-last').focus(function(){
		var id = $(this).attr("id");
		var rand=Math.floor(Math.random()*10001);
		$('span.[class^=selector_]').hide();
		$('span.suche-hilfe').load(contexttPath + "administration/hilfe_erw_suche.html?rand="+rand+" #"+id).hide().fadeIn("slow");
		$('span.[class^=selector_]').removeClass().addClass("selector_"+id).show();
	});
	
	/***** NAV */
	var idx, lastidx;
	$(".topicnav .opensub").click(function(){
		idx = $(".topicnav .opensub").index(this);
		lastidx=$.cookie("lastidx");
		
		if (lastidx == idx) {
			$(".topicnav ul ul").slideUp();
			$(".topicnav .opensub").removeClass("closed");
			$.cookie("lastidx",null);
		} else {
			$(".topicnav ul ul").slideUp();
			$(lastidx).removeClass("closed");
			$(lastidx).parent().next("ul").show();
			
			lastidx = idx;
			$.cookie("lastidx",lastidx);
			$(this).toggleClass("closed");
			$(this).parent().next("ul").slideToggle();	
		}
		return false;
	});
	
	// AUTOMATICAL OPEN NAVIGATION IF COOKIE EXISTS
	if ($.cookie("lastidx")!=null) {
		var lastidx=$(".topicnav .opensub").get($.cookie("lastidx"));
		
		if (lastidx) {
			$(lastidx).toggleClass("closed");
			$(lastidx).parent().next("ul").show();
		}
	}

	/***** Lightbox Funktionalität */
	$("a.zoom").fancybox(opts);

	/***** ADD TO REMIND */

	var timer;
	/*** STICHWORTE EINBLENDEN */
	$(".stichworte").click(function(){
		showHideE(".tab1");
	});
	
	/*** SCHLAGWORTE EINBLENDEN */
	$(".schlagworte").click(function(){
		showHideE(".tab0");
	});
	
	
	/****  ****/
	$("#search").keyup(function(event) 
	{
		if (event.keyCode == 13) {
			document.search.submit();
		}
	});
	/* LOGIN */
	$("#account").keyup(function(event) 
	{
		if (event.keyCode == 13) {
			document.login.submit();
		}
	});	
	
	/***** SCROLLABLE für Gallery*/
	var scrollGallery = $(".scrollable_gallery").scrollable(                                             
	{                                                              
		   clickable	: true,                                           
		   api			: true,
		   size			: 3
	}); 
	
	$(".gallery-back").click(function() {
		scrollGallery.prevPage();
	});
	
	$(".gallery-next").click(function() {
		scrollGallery.nextPage();
	});
	
	
	// Autor switch
	$(".authors-namelist").hide();
	var show=trim(unescape(get_url_parameter("show")));
	if ($(".authors-namelist:visible").length<1) {
		if (show.length<3) {
			$("#select-author").children(":eq(1)").find("a").addClass("selected");
			var url=contexttPath + "autoren/liste/A.html?newautor=false&load=1";
			
			if ($(".authors-namelist").css("display")=="none") {
				loadAutorenData(url);
				
			} else {
				$(".authors-namelist").slideToggle("normal",function (){
					loadAutorenData(url);
				});
				
			}
		} else {
			var abc=show.substring(0,1);
			var found=$("#select-author li a:contains('" + abc + "')").addClass("selected");
			$("#select-author").children(":eq(0)").find("a").removeClass("selected");
			url=contexttPath + "autoren/liste/"+abc+".html?load=1";
			$(".authors-namelist #autor-A").load(url+" .authors-namelist #autor-A",function (){
				var foundautor=false;
				
				$(".switchname").each(function() {
					var text=trim($(this).text());
					if (text==show) {
						foundautor=true;
						var id=$(this).attr("id");
						$("#autordata").load(id +" #autordata",function (){
							$(this).fadeIn("normal");
						});
					}
				});
				
				if (!foundautor) {
					alert("Der angegebene Autor kann nicht gefunden werden!");
				}
			});
			
		}
	}
	
	
	//$("#autordata").hide();
	
	$("#select-author li a").click(function() {
		var charrr = this.hash;
		var me = $(this);
		
		if ($("#autordata:visible").length==1) {
			$("#autordata").fadeOut("normal",function () {
				loadAutoren(me, charrr);
			});
		} else {
			loadAutoren(me, charrr);
		}
	});
	
	
	$("#journal-list").load(window.location.pathname+"?view=list #journal-list li",function (){
		$("#journal-list").parent().hide();
	});
	
	$(".journal-toolbar a").click(function() {
		if (this.hash=="#list") {
			$("#journal-galery").parent().hide();
			$(".grid-view").removeClass("grid-view-active");
			$("#journal-list").parent().show();
			$(".list-view").addClass("list-view-active");
			
		}
		
		if (this.hash=="#gallery") {
			$("#journal-list").parent().hide();
			$(".list-view").removeClass("list-view-active");
			$("#journal-galery").parent().show();
			$(".grid-view").addClass("grid-view-active");
		}
	});
	
	// BUEHNE Detailseite
	var toLoad="";
	
	if ($(".widget").length) 
	{
		toLoad=$(".info table td:first").text();
		loadWidget(toLoad);
	}
	$("#stage-slider-small .scrollable .items li").click(function(){
		loadProduct($(this));
	});
	
	/** ADD TO WATCHLIST **/
	$(".btn-addtowatchlist, .btn-addtowatchlist-icon").click(function(){
		addTo($(this),"watchlist");
	});
	
	/** ADD TO CART **/
	$(".btn-addtocart, .btn-addtocart-icon").click(function(){
		addTo($(this),"cart");
	});
	
	/** SEARCH **/
	var inputText = $("#tools input.text");
	// On focus out..
	inputText.focusout(function(){
		if (inputText.val()=="") {
			$(this).addClass("example");
		}
	});
	
	// DELETING COOKIE
	if (!$("#infobar-top").length) 
	{
		$.cookie("last-topic",null);
		$.cookie("last-topic-sel",null);
		//$.cookie("nav-products-active",null);
	} else {
		if ($(".infobarfake").length) {
			$.cookie("last-topic-sel",null);
			$.cookie("nav-products-active",null);
		}
	}
	
	if (get_url_parameter("reihe")!="") {
		$.cookie("last-topic",null);
		$.cookie("last-topic-sel",null);
	}
	
	if (get_url_parameter("raw")!="") {
		$.cookie("nav-products-active",null);
	}
	
	if (get_url_parameter("quick")!="") {
		$.cookie("last-topic",null);
		$.cookie("last-topic-sel",null);
		$.cookie("nav-products-active",null);
	}
	
	if (get_url_parameter("erws")!="") {
		$.cookie("last-topic",null);
		$.cookie("last-topic-sel",null);
		$.cookie("nav-products-active",null);
	}
	
	/** TOPIC NAV **/
	// opening
	if ($.cookie("last-topic-sel")!=null) {
		$("#nav-topic > li a").each(function(){
			if ($(this).text()==$.cookie("last-topic-sel")) {
				$(this).parent().addClass("active");
			}
			
		});
	}
	
	if ($.cookie("last-topic")!=null) {
		$("#nav-topic > li").each(function(){
			if ($(this).text()==$.cookie("last-topic")) {
				$(this).find("ul").show();
				$(this).toggleClass("open");
			}
		});
	}
	
	$("#nav-topic li, #nav-topic li a").click(function(){
		var found = $(this).text();
		if (found!="") {
			$.cookie("last-topic",found);
		}
	});
	
	$("#nav-topic li li a").click(function() {
		$.cookie("last-topic-sel",$(this).text());
	});
	
	if (!noshop)
	{
		loadBasket();
		loadNotepad();
	}
	
	if ($("#tool-checkout").css("margin-left")!="0px") {
		$("#message-added-cart").css("right","48px");
		$("#message-added-watchlist").css("right","110px");
	}
	
	// Products nav Cookie
	$("#nav-products a").click(function() {
		if (!$(this).parent().find("ul").length) {
			var text=$(this).text();
			$("#nav-products a:hover, #nav-products li.active").removeClass("active");
			$.cookie("nav-products-active",text);
			$(this).parent().addClass("active");
			
			if (text=="E-Books" || text=="CD-Roms") {
				$("#nav-products ul").treeview({
					collapsed: true
				 });
				//$("#nav-products ul").find("ul:visible").hide();
			}
		}
	});
	// Check Products-Nav Cookie
	if ($.cookie("nav-products-active")) {
		$("#nav-products a").each(function() {
			if ($(this).text()==$.cookie("nav-products-active")) {
				$(this).parent().addClass("active");
			}
		});
	}
	
	// Newsletter
	$("#newsletterk").submit(function() {
		return checkNewsletterK();
	});
	// Autoren Newsletter
	$("#newsletterautoren").submit(function() {
		return checkAutorenNewsletter();
	});
	
	// Facbhkonferenz
	$("#fachkonferenz").submit(function() {
		return checkFachkonferenz();
	});
	
	// Newsletter
	$("#newsletter").submit(function() {
		return checkNewsletterB();
	});
	
	// Gewinnspiel
	$("#gewinnspiel").submit(function() {
		return checkGewinnspiel();
	});
	
	// Small Slider && Dazu passend
	if (get_url_parameter("back")!="") {
		loadSmallSlider();
		loadDazuPassend();
	} else {
		if ($(".showBooks").length<1) {
			$("#stage .stage-slider").remove();
		}
		if ($(".param_isbn:contains('0000')").length>=1) {
			loadDazuPassend();
		}
		if ($(".btn-furtherseries").length>=1) {
			loadDazuPassend();
		}
		
		
	}
	
	$.addthis("xa-4c8f6a1447b0008e");
	
	// Focus bei Newsletter anmelden Teaser
	if ($(".submit-form .input").val()!="E-Mail") {
		$(".submit-form .input").val("E-Mail");
	}
	$(".submit-form .input").focus(function() {
		if ($(this).val()=="E-Mail") {
			$(this).val("");
		}
	});
	
	$(".submit-form .input").blur(function() {
		if ($(this).val()=="") {
			$(this).val("E-Mail");
		}
	});
	
	// Check E-Mail in Teaser
	$(".submit-form").submit(function() {
		if ($(".submit-form .input").val()=="") {
			alert("Die angegebene E-Mail Adresse ist ungültig!");
			dontpost=true;
			return false;
		}
		var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	    if(reg.test($(".submit-form .input").val()) == false) {
	    	alert("Die angegebene E-Mail Adresse ist ungültig!");
	    	dontpost=true;
	    	return false;
	    }
	    
	    dontpost=false;
	});
	
	$(".btn-reset").click(function() {
		$("#input-author").val("");
		$("#input-publisher").val("");
		$("#input-keywords").val("");
		$("#input-title").val("");
		$("#input-isbn").val("");
		$("#input-type")[0].selectedIndex=0;
		$("#input-year").val("");
	});
	
// VirtualUriMapping
	
	$("#urimapping tr td a").click(function() {
		// Getting cell values
		var tr = $(this).parent().parent();
		var name=tr.find("td").eq(0).text();
		var von=tr.find("td").eq(1).text();
		var nach=tr.find("td").eq(2).text();
		
		// Setting values
		$("#redirectname").val(name);
		$("#von").val(von);
		$("#nach").val(nach);
		
	});
	
	$("#urimapping tr").hover(
			function () {
				$(this).css("background-color","#E7E2DF");
			}, 
			function () {
				$(this).css("background-color","white");
			});
	
	$("#urimapping tr td a, #addnode").fancybox({
		
	});
	
	$("#savebtn").click(function() {
		var name=$("#redirectname").val();
		var von=$("#von").val();
		var nach=$("#nach").val();
		
		$.post("Virtualurimapping.html", { name: name, von: von, nach: nach },
		   function(data){
			loadUriMapping();
			$.fancybox.close();
		   });
	});
	
	$("#addnode").click(function() {
		var name=$("#redirectname").val("");
		var von=$("#von").val("");
		var nach=$("#nach").val("");
		var rowCount = (((1+Math.random())*0x10000)|0).toString(16).substring(1);
		
		$("#redirectname").val("redirect"+rowCount);
		$("#redirectname").attr("disabled","disabled");
		$.fancybox.close();
	});
	
	$("#deletebtn").click(function() {
		var redirectname=$("#redirectname").val();
		$.post("Virtualurimapping.html", { name: redirectname, del: "1"},
				function(data){
			loadUriMapping();
			$.fancybox.close();
		});
	});
	
	$("#month,#selzeit,#heft").change(function() {
		loadZeitschriften();
	});
	
	function loadZeitschriften() {
		var year=get_url_parameter("year");
		var month=$("#month").val();
		var zeitschrift=$("#selzeit").val();
		var heft=$("#heft").val();
		
		var param="";
		
		if (year!="") {
			param=param+"?year="+year;
		}
		
		if (month!="") {
			param=param+"&month="+month;
		}
		
		if (zeitschrift!="") {
			param=param+"&zeitschrift="+zeitschrift;
		}
		
		if (heft!="") {
			param=param+"&heft="+heft;
		}
		
		if (month!="") {
			top.window.location.href="Zeitschriften.html"+param;
		}
	}
	
	function loadUriMapping() {
		$("#urimapping").load("Virtualurimapping.html #urimapping tr", function() {
			$("#urimapping tr td a").click(function() {
				// Getting cell values
				var tr = $(this).parent().parent();
				var name=tr.find("td").eq(0).text();
				var von=tr.find("td").eq(1).text();
				var nach=tr.find("td").eq(2).text();
				
				// Setting values
				$("#redirectname").val(name);
				$("#von").val(von);
				$("#nach").val(nach);
				
			});
			
			$("#urimapping tr").hover(
					function () {
						$(this).css("background-color","#E7E2DF");
					}, 
					function () {
						$(this).css("background-color","white");
					});
			
			$("#urimapping tr td a, #addnode").fancybox({
				
			});
			
			$("#addnode").click(function() {
				var name=$("#redirectname").val("");
				var von=$("#von").val("");
				var nach=$("#nach").val("");
				var rowCount = (((1+Math.random())*0x10000)|0).toString(16).substring(1);
				
				$("#redirectname").val("redirect"+rowCount);
				$("#redirectname").attr("disabled","disabled");
				$.fancybox.close();

			});
			
			$("#deletebtn").click(function() {
				var redirectname=$(".delname").val();
				$.post("Virtualurimapping.html", { name: redirectname, del: "1"},
						function(data){
						loadUriMapping();
						$.fancybox.close();
				});
			});
			
			
		});
	}
	
	if ($(".toSlide").length > 0) {
		var url=top.window.location.pathname;
		$(".toSlide").load(url+"?slider=true #slider-small",function() {
			/** SMALL SLIDER (http://flowplayer.org/tools/scrollable.html) */
			$("#slider-small .scrollable").scrollable({		
				size: 3,
				speed: 500
			});
			$("#slider-small .scrollable").circular();
		});
	}
	
	if ($("#magazine-content").length > 0) {
		$(".chapter-directory").hide();
		$("*").find("tr.captionHide").hide();
		$(".chapter-directory tr").each(function() {
			if ($(this).attr("id")) {
				$(this).hide();
			}
		});
		
		$(".open-close-text,.open-close-text-subtitle,.open-close").click(function() {
			if ($(this).hasClass("container")) {
				var id=$(this).parent().attr("id");
				$(this).parent().parent().parent().find("tr#"+id).each(function() {
					$(this).toggle();
				});
			} else {
				$(this).parent().parent().find(".chapter-directory").toggle();
			}
			
			if ($(this).parent().find(".btn-closed").length > 0) {
				$(this).parent().find("a").removeClass("btn-closed");
				$(this).parent().find("a").addClass("btn-opened");
			} else {
				$(this).parent().find("a").removeClass("btn-opened");
				$(this).parent().find("a").addClass("btn-closed");
			}
		});
		
		$(".caption-open-close").click(function() {
		    var toOpen=$(this).attr("id");
			$(this).parent().parent().find(".captionHide").toggle();
			if ($(this).find(".btn-closed").length > 0) {
				$(this).find("a").removeClass("btn-closed");
				$(this).find("a").addClass("btn-opened");
			} else {
				$(this).find("a").removeClass("btn-opened");
				$(this).find("a").addClass("btn-closed");
			}
		});
		
		$(".btn-full-opened,.btn-full-openedd").click(function() {
			$(".chapter-directory").show();
			$("*").find(".btn-closed").removeClass("btn-closed").addClass("btn-opened");
			$("tr").show();
		});
	}
	
	$(".submit-form #email").focus(function() {
		if ($(this).val()=="E-Mail") {
			$(this).val("");
		}
	});
	
	$(".submit-form #email").blur(function() {
		if ($(this).val()=="") {
			$(this).val("E-Mail");
		}
	});
	
	// ZeitschriftTeaser validation
	$("#feedback").submit(function() {
		if (!$("#answer1:checked").val() && !$("#answer2:checked").val() && !$("#answer3:checked").val() 
				&& !$("#answer4:checked").val() && !$("#answer5:checked").val()) {
				alert("Bitte eine Antwort auswählen!");
				return false;
		}
		
		if (!dontpost) {
			var qquestion=$(".feedback h2").text();
			var emailtoo=$("#emailto").val();
			var subjectt=$("#emailsubject").val();
			var emailfrom=$("#email").val();
			var aanswer=$(".feedback input[name='answer']:checked").val();
			
			$.get("http://www.manz.at/Zeitschriften.html", { sendmail: "feedbackzeitschrift", question: qquestion, answer: aanswer, emailto: emailtoo, email: emailfrom, emailsubject: subjectt} ,function() {
				
			});
			$(".feedback").html("");
			$(".feedback").html("<b>Vielen Dank für Ihr Feedback!</b>");
			
			return false;
		}
	});
	
	// Zeitschriften Veranstaltungen
	var toLoad="";
	
	function loadMonth(toLoad,me) {
		$(".volume li a").removeClass("active");
		me.addClass("active");
		toLoad=toLoad.replace("&month=","&prevmonth=");
		toLoad+="&month="+me.attr("id").replace("#","");
		
		$(".event-overview").load(toLoad+" .event-overview > *",function() {
			$(".site-table").tablesorter( {sortList: [[0,1]]} );
			
			if (!$("#year li a").data("events"))
			{ 
				$("#year li a").click(function() {
					loadYear($(this));
				});
			}
			
			if (!$(".volume li a").data("events"))
			{
				$(".volume li a").click(function() {
					loadMonth(toLoad,$(this));
					
					if (!$("#year li a").data("events"))
					{ 
						$("#year li a").click(function() {
							loadYear($(this));
						});
					}
				});
			}		
		});
	}
	
	function loadYear(me) {
		var year = me.attr("id");
		year=year.replace("#","");
		$("ul#year li a").removeClass("active");
		var today=new Date();
		var todayyear=today.getFullYear();
		me.addClass("active");
		toLoad=window.location.pathname+"?year="+year;
		var month="jaenner";
		$("#jaenner").click();
		
		toLoad=window.location.pathname+"?year="+year+"&month="+month;
		$(".event-overview").load(toLoad+" .event-overview > *",function() {
			$(".event-archiv ul.volume li").each(function() {
				var vmonth=$(this).find("a").attr("id").replace("#","");
				if (month[today.getMonth()]==vmonth) {
					$(this).find("a").addClass("active");
				}
			});
			
			$(".site-table").tablesorter( {sortList: [[0,1]]} );
			
			if (!$("#year li a").data("events"))
			{ 
				$("#year li a").click(function() {
					loadYear($(this));
				});
			}
			
			
		});
	}
	
	$("#year li a").click(function() {
		loadYear($(this));
	});
	
	// Show table on Document ready
	if ($(".event-archiv").length > 0) {
		var today=new Date();
		var year=today.getFullYear();
		var month=new Array(12);
		month[0]="jaenner";
		month[1]="februar";
		month[2]="maerz";
		month[3]="april";
		month[4]="mai";
		month[5]="juni";
		month[6]="juli";
		month[7]="august";
		month[8]="september";
		month[9]="oktober";
		month[10]="november";
		month[11]="dezember";
		
		toLoad=window.location.pathname+"?year="+year;
		
		if ($(this).find("ul#year li a #"+year).length > 0) {
			$(".event-archiv").load(toLoad+" .event-archiv > *",function() {
				$(this).find("ul#year li").each(function() {
					var vyear=$(this).text();
					if (year==vyear) {
						$(this).find("a").addClass("active");
					}
				});
				
				toLoad=window.location.pathname+"?year="+year+"&month="+month[today.getMonth()];
				$(".event-overview").load(toLoad+" .event-overview > *",function() {
					$(".event-archiv ul.volume li").each(function() {
						var vmonth=$(this).find("a").attr("id").replace("#","");
						if (month[today.getMonth()]==vmonth) {
							$(this).find("a").addClass("active");
						}
					});
					
					$(".site-table").tablesorter( {sortList: [[0,1]]} );
					
					if (!$("#year li a").data("events"))
					{ 
						$("#year li a").click(function() {
							loadYear($(this));
						});
					}
					
					if (!$(".volume li a").data("events"))
					{
						$(".volume li a").click(function() {
							loadMonth(toLoad,$(this));
							
							if (!$("#year li a").data("events"))
							{ 
								$("#year li a").click(function() {
									loadYear($(this));
								});
							}
						});
					}
				});
			});
		} else {
			var foundyear=$(this).find("ul#year li a").html();
			toLoad=window.location.pathname+"?year="+foundyear;
			
			$(".event-archiv").load(toLoad+" .event-archiv > *",function() {
				$(this).find("ul#year li").each(function() {
					var vyear=$(this).text();
					if (year==vyear) {
						$(this).find("a").addClass("active");
					}
				});
				
				toLoad=window.location.pathname+"?year="+foundyear+"&month="+month[today.getMonth()];
				$(".event-overview").load(toLoad+" .event-overview > *",function() {
					var showMonth="jaenner";
					
					$(".event-archiv ul.volume li").each(function() {
						var vmonth=$(this).find("a").attr("id").replace("#","");
						if (showMonth==vmonth) {
							$(this).find("a").addClass("active");
						}
					});
					
					$(".site-table").tablesorter( {sortList: [[0,1]]} );
					
					if (!$("#year li a").data("events"))
					{ 
						$("#year li a").click(function() {
							loadYear($(this));
						});
					}
					
					if (!$(".volume li a").data("events"))
					{
						$(".volume li a").click(function() {
							loadMonth(toLoad,$(this));
							
							if (!$("#year li a").data("events"))
							{ 
								$("#year li a").click(function() {
									loadYear($(this));
								});
							}
						});
					}
				});
			});
		}
		
	}
	
	$(".index-of-contents ul li a").click(function() {
		var chapter=$(this).attr("href");
		chapter=chapter.replace("#","");
		if ($("#"+chapter).length > 0) {
			
			if ($("#"+chapter).next().find(".chapter-directory:visible").length > 0) {
				$("#"+chapter).next().find(".chapter-directory").hide();
				$("#"+chapter).next().find(".open-close a").removeClass("btn-opened");
				$("#"+chapter).next().find(".open-close a").addClass("btn-closed");
			} else {
				$("#"+chapter).next().find(".chapter-directory").show();
				$("#"+chapter).next().find(".open-close:not(.container) a").removeClass("btn-closed");
				$("#"+chapter).next().find(".open-close:not(.container) a").addClass("btn-opened");
			}
		}
	});
	
	$(".link-fulltext a").click(function() {
		window.open("http://recherche.rdb.at/recherche/direct_document_page.html?print=on&ddl=on&documentid="+$(this).attr("id"));
	});
	
	$("#debug").click(function() {
		$(".debug").show();
		$("#debug").hide();
	});
	
	$(".zeitschriftUpload").submit(function() {
		if ($("#dokument").val()=="") {
			alert("Bitte eine Zeitschriftendatei auswählen!");
			
			return false;
		}
		
		return true;
	});
	
	$(".showdetail").click(function() {
		$(this).parent().find(".toshowdetail").toggle();
	});
});

function getRdbLink(DocId) {
	window.open("http://recherche.rdb.at/recherche/direct_document_page.html?print=on&ddl=on&documentid="+DocId);
	var toLoad=window.location.pathname+"?year="+year+"&month="+month[today.getMonth()];
}
	

