
function str_replace(search, replace, subject) {
    return subject.split(search).join(replace);
} 


(function($) {

/**
 * Chainable method for converting elements into rich media.
 *
 * @name media
 * @param Object options Options object
 * @param Function callback fn invoked for each matched element before conversion
 * @param Function callback fn invoked for each matched element after conversion
 * @cat Plugins/media
 */
$.fn.media = function(options, f1, f2) {
    return this.each(function() {
        if (typeof options == 'function') {
            f2 = f1;
            f1 = options;
            options = {};
        }
        var o = getSettings(this, options);
        // pre-conversion callback, passes original element and fully populated options
        if (typeof f1 == 'function') f1(this, o);
        
        var r = getTypesRegExp();
        var m = r.exec(o.src) || [''];
        o.type ? m[0] = o.type : m.shift();
        for (var i=0; i < m.length; i++) {
            fn = m[i].toLowerCase();
            if (isDigit(fn[0])) fn = 'fn' + fn; // fns can't begin with numbers
            if (!$.fn.media[fn]) 
                continue;  // unrecognized media type
            // normalize autoplay settings
            var player = $.fn.media[fn+'_player'];
            if (!o.params) o.params = {};
            if (player) {
                var num = player.autoplayAttr == 'autostart';
                o.params[player.autoplayAttr || 'autoplay'] = num ? (o.autoplay ? 1 : 0) : o.autoplay ? true : false;
            }
            var $div = $.fn.media[fn](this, o);

            $div.css('backgroundColor', o.bgColor).width(o.width);
            
            // post-conversion callback, passes original element, new div element and fully populated options
            if (typeof f2 == 'function') f2(this, $div[0], o, player.name);
            break;
        }
    });
};

/**
 * Non-chainable method for adding or changing file format / player mapping
 * @name mapFormat
 * @param String format File format extension (ie: mov, wav, mp3)
 * @param String player Player name to use for the format (one of: flash, quicktime, realplayer, winmedia, silverlight or iframe
 */
$.fn.media.mapFormat = function(format, player) {
    if (!format || !player || !$.fn.media.defaults.players[player]) return; // invalid
    format = format.toLowerCase();
    if (isDigit(format[0])) format = 'fn' + format;
    $.fn.media[format] = $.fn.media[player];
    $.fn.media[format+'_player'] = $.fn.media.defaults.players[player];
};

// global defautls; override as needed
$.fn.media.defaults = {
    width:         400,
    height:        400,
    preferMeta:    1,         // true if markup metadata takes precedence over options object
    autoplay:      0,         // normalized cross-player setting
    bgColor:       '#ffffff', // background color
    params:        {},        // added to object element as param elements; added to embed element as attrs
    attrs:         {},        // added to object and embed elements as attrs
    flashvars:     {},        // added to flash content as flashvars param/attr
    flashVersion:  '7',       // required flash version
    expressInstaller: null,
    
    // default flash video and mp3 player (@see: http://jeroenwijering.com/?item=Flash_Media_Player)
    flvPlayer:     'mediaplayer.swf',
    mp3Player:     'mediaplayer.swf',
    
    // @see http://msdn2.microsoft.com/en-us/library/bb412401.aspx
    silverlight: {
        inplaceInstallPrompt: 'true', // display in-place install prompt?
        isWindowless:         'true', // windowless mode (false for wrapping markup)
        framerate:            '24',   // maximum framerate
        version:              '0.9',  // Silverlight version
        onError:              null,   // onError callback
        onLoad:               null,   // onLoad callback
        initParams:           null,   // object init params
        userContext:          null    // callback arg passed to the load callback
    }
};

// Media Players; think twice before overriding
$.fn.media.defaults.players = {
    flash: {
        name:         'flash',
        types:        'flv,mp3,swf',
        oAttrs:   {
            classid:  'clsid:d27cdb6e-ae6d-11cf-96b8-444553540000',
            type:     'application/x-oleobject',
            codebase: 'http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=' + $.fn.media.defaults.flashVersion
        },
        eAttrs: {
            type:         'application/x-shockwave-flash',
            pluginspage:  'http://www.adobe.com/go/getflashplayer'
        }        
    },
    quicktime: {
        name:         'quicktime',
        types:        'aif,aiff,aac,au,bmp,gsm,mov,mid,midi,mpg,mpeg,mp4,m4a,psd,qt,qtif,qif,qti,snd,tif,tiff,wav,3g2,3gp',
        oAttrs:   {
            classid:  'clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B',
            codebase: 'http://www.apple.com/qtactivex/qtplugin.cab'
        },
        eAttrs: {
            pluginspage:  'http://www.apple.com/quicktime/download/'
        }
    },
    realplayer: {
        name:         'real',
        types:        'ra,ram,rm,rpm,rv,smi,smil',
        autoplayAttr: 'autostart',
        oAttrs:   {
            classid:  'clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA'
        },
        eAttrs: {
            type:         'audio/x-pn-realaudio-plugin',
            pluginspage:  'http://www.real.com/player/'
        }
    },
    winmedia: {
        name:         'winmedia',
        types:        'asf,avi,wma,wmv',
        autoplayAttr: 'autostart',
        oUrl:         'url',
        oAttrs:   {
            classid:  'clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6',
            type:     'application/x-oleobject'
        },
        eAttrs: {
            type:         $.browser.mozilla && isFirefoxWMPPluginInstalled() ? 'application/x-ms-wmp' : 'application/x-mplayer2',
            pluginspage:  'http://www.microsoft.com/Windows/MediaPlayer/'
        }        
    },
    // special cases
    iframe: {
        name:  'iframe',
        types: 'html,pdf'
    },
    silverlight: {
        name:  'silverlight',
        types: 'xaml'
    }
};

//
//  everything below here is private
//


// detection script for FF WMP plugin (http://www.therossman.org/experiments/wmp_play.html)
// (hat tip to Mark Ross for this script)
function isFirefoxWMPPluginInstalled() {
    var plugs = navigator.plugins;
    for (i = 0; i < plugs.length; i++) {
        var plugin = plugs[i];
        if (plugin['filename'] == 'np-mswmp.dll')
            return true;
    }
    return false;
}

var counter = 1;

for (var player in $.fn.media.defaults.players) {
    var types = $.fn.media.defaults.players[player].types;
    $.each(types.split(','), function(i,o) {
        if (isDigit(o[0])) o = 'fn' + o;
        $.fn.media[o] = $.fn.media[player] = getGenerator(player);
        $.fn.media[o+'_player'] = $.fn.media.defaults.players[player];
    });
};

function getTypesRegExp() {
    var types = '';
    for (var player in $.fn.media.defaults.players) {
        if (types.length) types += ',';
        types += $.fn.media.defaults.players[player].types;
    };
    return new RegExp('\\.(' + types.replace(/,/g,'|') + ')\\b');
};

function getGenerator(player) {
    return function(el, options) {
        return generate(el, options, player);
    };
};

function isDigit(c) {
    return '0123456789'.indexOf(c) > -1;
};

// flatten all possible options: global defaults, meta, option obj
function getSettings(el, options) {
    options = options || {};
    var $el = $(el);
    var cls = el.className || '';
    // support metadata plugin (v1.0 and v2.0)
    var meta = $.metadata ? $el.metadata() : $.meta ? $el.data() : {};
    meta = meta || {};
    var w = meta.width  || parseInt(((cls.match(/w:(\d+)/)||[])[1]||0));
    var h = meta.height || parseInt(((cls.match(/h:(\d+)/)||[])[1]||0));
    if (w) meta.width  = w;
    if (h) meta.height = h;
    if (cls) meta.cls = cls;

    var a = $.fn.media.defaults;
    var b = (($.meta || $.metadata) && $.fn.media.defaults.preferMeta) ? options : meta;
    var c = b == options ? meta : options;

    var p = { params: { bgColor: options.bgColor || $.fn.media.defaults.bgColor } };
    var opts = $.extend({}, a, b, c);
    $.each(['attrs','params','flashvars','silverlight'], function(i,o) {
        opts[o] = $.extend({}, p[o] || {}, a[o] || {}, b[o] || {}, c[o] || {});
    });

    if (typeof opts.caption == 'undefined') opts.caption = $el.text();

    // make sure we have a source!
    opts.src = opts.src || $el.attr('href') || $el.attr('src') || 'unknown';
    return opts;
};

//
//  Flash Player
//

// generate flash using SWFObject if possible
$.fn.media.swf = function(el, opts) {
    if (typeof SWFObject == 'undefined') {
        // roll our own
        if (opts.flashvars) {
            var a = [];
            for (var f in opts.flashvars)
                a.push(f + '=' + opts.flashvars[f]);
            if (!opts.params) opts.params = {};
            opts.params.flashvars = a.join('&');
        }
        return generate(el, opts, 'flash');
    }

    var id = el.id ? (' id="'+el.id+'"') : '';
    var cls = opts.cls ? (' class="' + opts.cls + '"') : '';
    var $div = $('<div' + id + cls + '>');
    $(el).after($div).remove();

    var so = new SWFObject(opts.src, 'movie_player_' + counter++, opts.width, opts.height, opts.flashVersion, opts.bgColor);
    if (opts.expressInstaller) so.useExpressInstall(opts.expressInstaller);    

    for (var p in opts.params)
        if (p != 'bgColor') so.addParam(p, opts.params[p]);
    for (var f in opts.flashvars)
        so.addVariable(f, opts.flashvars[f]);
    so.write($div[0]);

    if (opts.caption) $('<div>').appendTo($div).html(opts.caption);
    return $div;
};

// map flv and mp3 files to the swf player by default
$.fn.media.flv = $.fn.media.mp3 = function(el, opts) {
    var src = opts.src;
    var player = /\.mp3\b/i.test(src) ? $.fn.media.defaults.mp3Player : $.fn.media.defaults.flvPlayer;
    opts.src = player;
    opts.src = opts.src + '?file=' + src;
    opts.flashvars = $.extend({}, { file: src }, opts.flashvars );
    return $.fn.media.swf(el, opts);
};

//
//  Silverlight
//
$.fn.media.xaml = function(el, opts) {
    if (!window.Sys || !window.Sys.Silverlight) {
        if ($.fn.media.xaml.warning) return;
        $.fn.media.xaml.warning = 1;
        alert('You must include the Silverlight.js script.');
        return;
    }

    var props = {
        width: opts.width,
        height: opts.height,
        background: opts.bgColor,
        inplaceInstallPrompt: opts.silverlight.inplaceInstallPrompt,
        isWindowless: opts.silverlight.isWindowless,
        framerate: opts.silverlight.framerate,
        version: opts.silverlight.version
    };
    var events = {
        onError: opts.silverlight.onError,
        onLoad: opts.silverlight.onLoad
    };

    var id1 = el.id ? (' id="'+el.id+'"') : '';
    var id2 = opts.id || 'AG' + counter++;
    // convert element to div
    var cls = opts.cls ? (' class="' + opts.cls + '"') : '';
    var $div = $('<div' + id1 + cls + '>');
    $(el).after($div).remove();
    
    Sys.Silverlight.createObjectEx({
        source: opts.src,
        initParams: opts.silverlight.initParams,
        userContext: opts.silverlight.userContext,
        id: id2,
        parentElement: $div[0],
        properties: props,
        events: events
    });

    if (opts.caption) $('<div>').appendTo($div).html(opts.caption);
    return $div;
};

//
// generate object/embed markup
//
function generate(el, opts, player) {
    var $el = $(el);
    var o = $.fn.media.defaults.players[player];
    
    if (player == 'iframe') {
        var o = $('<iframe' + ' width="' + opts.width + '" height="' + opts.height + '" >');
        o.attr('src', opts.src);
        o.css('backgroundColor', o.bgColor);
    }
    else if ($.browser.msie) {
        var a = ['<object width="' + opts.width + '" height="' + opts.height + '" '];
        for (var key in opts.attrs)
            a.push(key + '="'+opts.attrs[key]+'" ');
        for (var key in o.oAttrs || {})
            a.push(key + '="'+o.oAttrs[key]+'" ');
        a.push('></ob'+'ject'+'>');
        var p = ['<param name="' + (o.oUrl || 'src') +'" value="' + opts.src + '">'];
        for (var key in opts.params)
            p.push('<param name="'+ key +'" value="' + opts.params[key] + '">');
        var o = document.createElement(a.join(''));
        for (var i=0; i < p.length; i++)
            o.appendChild(document.createElement(p[i]));
    }
    else {
        var a = ['<embed width="' + opts.width + '" height="' + opts.height + '" style="display:block"'];
        if (opts.src) a.push(' src="' + opts.src + '" ');
        for (var key in opts.attrs)
            a.push(key + '="'+opts.attrs[key]+'" ');
        for (var key in o.eAttrs || {})
            a.push(key + '="'+o.eAttrs[key]+'" ');
        for (var key in opts.params)
            a.push(key + '="'+opts.params[key]+'" ');
        a.push('></em'+'bed'+'>');
    }
    // convert element to div
    var id = el.id ? (' id="'+el.id+'"') : '';
    var cls = opts.cls ? (' class="' + opts.cls + '"') : '';
    var $div = $('<div' + id + cls + '>');
    $el.after($div).remove();
    ($.browser.msie || player == 'iframe') ? $div.append(o) : $div.html(a.join(''));
    if (opts.caption) $('<div>').appendTo($div).html(opts.caption);
    return $div;
};


})(jQuery);




/**
 * jQuery Plugin FlyDOM v3.0
 *
 * Create DOM elements on the fly and automatically append or prepend them to another DOM object.
 * There are also template functions (tplAppend and tplPrepend) that can take a simple HTML structure
 * and apply a JSON object to it to make creating layouts MUCH easier.
 *
 * This plugin was inspired by "Oslow" [http://mg.to/2006/02/27/easy-dom-creation-for-jquery-and-prototype#comment-176],
 * and since I could not get his code to work, I decided I write my own plugin. My hope is that this
 * version will be easier to understand and maintain with future versions of jQuery.
 *
 * Copyright (c) 2007 Ken Stanley [dohpaz at gmail dot com]
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * @version     3.0.5
 *
 * @author      Ken Stanley [dohpaz at gmail dot com]
 * @copyright   (C) 2007. All rights reserved.
 *
 * @license     http://www.opensource.org/licenses/mit-license.php
 * @license     http://www.opensource.org/licenses/gpl-license.php
 *
 * @package     jQuery Plugins
 * @subpackage  FlyDOM
 *
 * @todo        Cache basic elements that are created, and if an already existing basic element is
 *              asked to be created an additional time, use a copy of the cached element to build from.
 */

/**
 * Create DOM elements on the fly and automatically append them to the current DOM obejct
 *
 * @uses    jQuery
 * @uses    function convertCamel()
 *
 * @param   string  element - The name of the DOM element to create (i.e., img, table, a, etc)
 * @param   object  attrs   - An optional object of attributes to apply to the element
 * @param   array   content - An optional array of content (or element children) to append to element
 *
 * @return  jQuery  element - The jQuery object representing the new element
 *
 * @since   1.0
 */
jQuery.fn.createAppend = function(element, attrs, content)
{
    // This helps me remember what 'this' is later on.
    var parentElement = this[0];
    // I *hate* exceptions
    if (jQuery.browser.msie && element == 'input' && attrs.type) {
        // IE will not allow you to modify the type attribute after an element is
        // created, so we must create the input element with the type attribute.
        var element = document.createElement('<' + element + ' type="' + attrs.type + '" />');
    } else {
        // This is for every other element
        var element = document.createElement(element);
    };
    // Check to see if we are using IE, and trying to append a TR to a TABLE.
    if (jQuery.browser.msie && parentElement.nodeName.toLowerCase() == 'table' && element.nodeName.toLowerCase() == 'tr') {
        // Check to see if we already have a tbody element in the table
        if (parentElement.parentNode.getElementsByTagName('tbody')[0]) {
            // Use the existing tbody
            var tbody = parentElement.getElementsByTagName('tbody')[0];
        } else {
            // Create a new tbody
            var tbody = parentElement.appendChild(document.createElement('tbody'));
        };
        // Append our TR to our TBODY and continue
        var element = tbody.appendChild(element);
    } else {
        // Add the element directly to the parentElement
        var element = parentElement.appendChild(element);
    };

    // Parse our attributes into our new element
    element = __FlyDOM_parseAttrs(element, attrs);
    // Determine what to do with our red-headed stepchild.
    if (typeof content == 'object' && content != null) {
        // Loop through content and create child elements
        for (var i = 0; i < content.length; i = i + 3) {
            jQuery(element).createAppend(content[i], content[i + 1] || {}, content[i + 2] || []);
        };

    // Add as text
    } else if (content != null) {
        element = __FlyDOM_setText(element, content);
    };

    // Return the newly appended element to the caller
    return jQuery(element);

}

/**
 * Create DOM elements on the fly and automatically prepend them to the current DOM obejct
 *
 * @uses    jQuery
 * @uses    createAppend()
 *
 * @param   string  element - The name of the DOM element to create (i.e., img, table, a, etc)
 * @param   object  attrs   - An optional object of attributes to apply to the element
 * @param   array   content - An optional array of content (or element children) to append to element
 * @return  jQuery  element - The jQuery object representing the new element
 *
 * @since   1.0
 */
jQuery.fn.createPrepend = function(element, attrs, content)
{

    // Create our DOM element
    var element     = document.createElement(element);
    // If we do not have a child node, just append the new element
    if (this[0].hasChildNodes() == false) {
        var element = this[0].appendChild(element);
    };

    // Parse our attributes into our new element
    element = __FlyDOM_parseAttrs(element, attrs);

    // Determine what to do with our red-headed stepchild.
    if (typeof content == 'object' && content != null) {

        // Loop through the content and append any children
        for (var i = 0; i < content.length; i = i + 3) {
            jQuery(element).createAppend(content[i], content[i + 1] || {}, content[i + 2] || []);
        };

    // Add as text
    } else if (content != null) {
        element = __FlyDOM_setText(element, content);
    };

    // Here we check to see if this element has children, and if so,
    // we will insert it before the first child node.
    if (this[0].hasChildNodes() == true) {
        var element = this[0].insertBefore(element, this[0].firstChild);
    };

    // Return the newly appended element to the caller
    return jQuery(element);

}

/**
 * Create DOM elements on the fly using a simple template system, and then append the new element(s) to
 * the end of the calling object.
 *
 * @uses jQuery
 * @uses createAppend()
 *
 * @param   object  json    - A JSON-formatted object that holds the dynamic data
 * @param   array   tpl     - An array containing the element(s) to append to the caller
 * @return  jQuery  self    - The jQuery object representing the new element(s)
 *
 * @since   2.0
 */
jQuery.fn.tplAppend = function(json, tpl)
{

    // Make sure that we have an array to work with
    if (json.constructor != Array) { json = [ json ]; };

    // Don't try to do anything if we have nothing to do
    if (json.length == 0) { return false; };

    // Loop through our JSON "rows"
    for (var i = 0; i < json.length; i++) {

        // Apply the data to the template and get our results
        var results = tpl.apply(json[i]);

        // Just like with createAppend/createPrepend; this is the best way to
        // loop through and create our new element(s).
        for (var j = 0; j < results.length; j = j + 3) {
            jQuery(this).createAppend(results[j], results[j + 1], results[j + 2]);
        };
    };

    // Return ourself for chaining
    return self;

}

/**
 * Create DOM elements on the fly using a simple template system, and then prepend the new element(s) to
 * the beginning of the calling object. The elements will first be appended to a temporary div container,
 * and then prepended before the first child of the parent element.
 *
 * @uses jQuery
 * @uses createAppend()
 *
 * @param   object  json    - A JSON-formatted object that holds the dynamic data
 * @param   array   tpl     - An array containing the element(s) to prepend to the caller
 * @return  jQuery  self    - The jQuery object representing the new element(s)
 *
 * @since   2.0
 */
jQuery.fn.tplPrepend = function(json, tpl) {

    // This will allow 'this' to go inside of a .each() loop
    var self = this[0];

    // Make sure that we have an array to work with
    if (json.constructor != Array) { json = [ json ]; };

    // Don't try to do anything if we have nothing to do
    if (json.length == 0) { return false; };

    // Here we create a div and insert it before the element we're
    // prepending to
    var div = document.createElement('div');

    // Loop through our JSON "rows"
    for (var i = 0; i < json.length; i++) {

        // Apply the data to the template and get our results
        var results = tpl.apply(json[i]);

        // Just like with createAppend/createPrepend; this is the best way to
        // loop through and create our new element(s).
        for (var j = 0; j < results.length; j = j + 3) {
            jQuery(div).createAppend(results[j], results[j + 1], results[j + 2]);
        };
    };

    // Apply each child node of the div container starting from the last one
    // This will ensure that all elements get applied as expected, and still
    // be readable from top to bottom.
    for (i = div.childNodes.length - 1; i >= 0; i--) {

        if (jQuery.browser.msie && self.nodeName.toLowerCase() == 'table' && div.childNodes[i].nodeName.toLowerCase() == 'tr') {
            if (self.getElementsByTagName('tbody')[0]) {
                var tbodyElement = self.getElementsByTagName('tbody')[0];
                tbodyElement.insertBefore(div.childNodes[i], tbodyElement.firstChild);
            } else {
                var tbodyElement = self.insertBefore(document.createElement('tbody'), self.firstChild);
                tbodyElement.appendChild(tbodyElement.appendChild(div.childNodes[i]));
            };
        } else {
            self.insertBefore(div.childNodes[i], self.firstChild);
        };
    };

    // Return ourself for chaining
    return jQuery(self);

};

/**
 * Convert a hyphenated set of words into one camel cased word. For example,
 * the hyphenated set of words 'border-left-width' would turn into 'borderLeftWidth'.
 *
 * @param   string  hyphenatedText  - The text to convert into camel case
 *
 * @return  string
 *
 * @since   3.0
 */
String.prototype.toCamelCase = function()
{

    var self = this;

    if (self.indexOf('-') > 0) {

        var parts = self.split('-');

        // Start the new text with the first word
        self = parts[0];

        // We skip over the first word, and capitalize
        // each word after.
        for (i = 1; i < parts.length; i++) {
            // Uppercase the first letter, and ensure the rest is lowercase.
            self += parts[i].substr(0, 1).toUpperCase() + parts[i].substr(1).toLowerCase();
        };

    };

    return self;

};

/**
 * Trims the whitespace from the beginning and end of a string.
 * This is the same exact method from the jQuery library, but
 * is put here to avoid having to call jQuery to do this one
 * simple thing.
 *
 * @param   string  text    - The text to trim
 *
 * @return  string
 *
 * @since   3.0
 */
String.prototype.trim = function()
{

    return this.replace(/^\s+|\s+$/g, '');

};

/**
 * Parse the attributes of element and return the element modified with
 * attrs.
 *
 * @uses    function toCamelCase()
 * @uses    function trim()
 *
 * @return  element
 *
 * @since   3.0
 */
__FlyDOM_parseAttrs = function(element, attrs)
{

    // Attach any attributes for this element
    for (attr in attrs) {

        // Break the styles up into a parameters array
        var attrName    = attr;
        var attrValue   = attrs[attr];

        switch (attrName) {

            // Styles are special because the DOM holds style information in an object.
            case 'style':

                if (typeof attrValue == 'string') {

                    var params = attrValue.split(';');

                    // Loop through each set of properties
                    for (var i = 0; i < params.length; i++) {

                        // Check to make sure someone (like myself) didn't end the value with a
                        // semi-colon.
                        if (params[i].trim() != '') {

                            // This is just to ease my burden of reading and typing :)
                            var styleName   = params[i].split(':')[0].trim();
                            var styleValue  = params[i].split(':')[1].trim();

                            // Take into account that styles with hyphens in the name need
                            // to be converted into camelCase.
                            styleName = styleName.toCamelCase();

                            // Don't try to apply the style if it is empty (this happens if
                            // the value of the attribute ends with a semi-colon.
                            if (styleName != '') {

                                // Apply each name/value pair, after removing any whitespace
                                element.style[styleName] = styleValue;

                            };

                        };

                    };

                } else if (typeof attrValue == 'object') {

                    for (styleName in attrValue) {

                        // Take into account that styles with hyphens in the name need
                        // to be converted into camelCase.
                        var styleNameCamel = styleName.toCamelCase();

                        if (styleName.trim() != '') {

                            element.style[styleNameCamel] = attrValue[styleName];

                        };

                    };

                };
                break;

            // Other attributes are treated as strings.
            default:

                // Check for any on* events
                if (attrName.substr(0, 2) == 'on') {

                    // Get the type of on event
                    var event = attrName.substr(2);

                    // Determine whether we need to create an anonymous function,
                    // or if the user was kind enough to do it for us.
                    attrValue = (typeof attrValue != 'function') ? eval('function() { ' + attrValue + '}') : attrValue;

                    // Bind the function to the event
                    jQuery(element).bind(event, attrValue);

                } else {

                    // Everything else (I hope) :)
                    element[attrName.toCamelCase()] = attrValue;

                }

        };

    };

    return element;

};

/**
 * Determines whether content should be treated as HTML or plain text,
 * and appended to element.
 *
 * @return  element
 *
 * @since   3.0
 */
__FlyDOM_setText = function(element, content)
{

    // Check for HTML tags or HTML entities.
    var isHtml = /(<\S[^><]*>)|(&.+;)/g;

    // Determine whether the text contains any HTML or entities
    // An exception is made for <textarea></textarea>; all text must be treated as text.
    if (content.match(isHtml) != null && element.tagName.toUpperCase() != 'TEXTAREA') {
        element.innerHTML = content;
    } else {
        // Create a text node from the content
        var textNode = document.createTextNode(content);
        // Add the text node to the element
        element.appendChild(textNode);
    };
    return element;
};


/* Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-08-12 22:47:23 -0500 (Sun, 12 Aug 2007) $
 * $Rev: 2669 $
 *
 * Version: 1.1
 *
 * Requires: jQuery 1.1.3+
 */
(function($){var height=$.fn.height,width=$.fn.width;$.fn.extend({height:function(){if(!this[0])error();if(this[0]==window)if(($.browser.mozilla||$.browser.opera)&&$(document).width()>self.innerWidth)return self.innerHeight-getScrollbarWidth();else
return self.innerHeight||$.boxModel&&document.documentElement.clientHeight||document.body.clientHeight;if(this[0]==document)return Math.max(document.body.scrollHeight,document.body.offsetHeight);return height.apply(this,arguments);},width:function(){if(!this[0])error();if(this[0]==window)if(($.browser.mozilla||$.browser.opera)&&$(document).height()>self.innerHeight)return self.innerWidth-getScrollbarWidth();else
return self.innerWidth||$.boxModel&&document.documentElement.clientWidth||document.body.clientWidth;if(this[0]==document)if($.browser.mozilla){var scrollLeft=self.pageXOffset;self.scrollTo(99999999,self.pageYOffset);var scrollWidth=self.pageXOffset;self.scrollTo(scrollLeft,self.pageYOffset);return document.body.offsetWidth+scrollWidth;}else
return Math.max(document.body.scrollWidth,document.body.offsetWidth);return width.apply(this,arguments);},innerHeight:function(){if(!this[0])error();return this[0]==window||this[0]==document?this.height():this.is(':visible')?this[0].offsetHeight-num(this,'borderTopWidth')-num(this,'borderBottomWidth'):this.height()+num(this,'paddingTop')+num(this,'paddingBottom');},innerWidth:function(){if(!this[0])error();return this[0]==window||this[0]==document?this.width():this.is(':visible')?this[0].offsetWidth-num(this,'borderLeftWidth')-num(this,'borderRightWidth'):this.width()+num(this,'paddingLeft')+num(this,'paddingRight');},outerHeight:function(options){if(!this[0])error();options=$.extend({margin:false},options||{});return this[0]==window||this[0]==document?this.height():this.is(':visible')?this[0].offsetHeight+(options.margin?(num(this,'marginTop')+num(this,'marginBottom')):0):this.height()+num(this,'borderTopWidth')+num(this,'borderBottomWidth')+num(this,'paddingTop')+num(this,'paddingBottom')+(options.margin?(num(this,'marginTop')+num(this,'marginBottom')):0);},outerWidth:function(options){if(!this[0])error();options=$.extend({margin:false},options||{});return this[0]==window||this[0]==document?this.width():this.is(':visible')?this[0].offsetWidth+(options.margin?(num(this,'marginLeft')+num(this,'marginRight')):0):this.width()+num(this,'borderLeftWidth')+num(this,'borderRightWidth')+num(this,'paddingLeft')+num(this,'paddingRight')+(options.margin?(num(this,'marginLeft')+num(this,'marginRight')):0);},scrollLeft:function(val){if(!this[0])error();if(val!=undefined)return this.each(function(){if(this==window||this==document)window.scrollTo(val,$(window).scrollTop());else
this.scrollLeft=val;});if(this[0]==window||this[0]==document)return self.pageXOffset||$.boxModel&&document.documentElement.scrollLeft||document.body.scrollLeft;return this[0].scrollLeft;},scrollTop:function(val){if(!this[0])error();if(val!=undefined)return this.each(function(){if(this==window||this==document)window.scrollTo($(window).scrollLeft(),val);else
this.scrollTop=val;});if(this[0]==window||this[0]==document)return self.pageYOffset||$.boxModel&&document.documentElement.scrollTop||document.body.scrollTop;return this[0].scrollTop;},position:function(returnObject){return this.offset({margin:false,scroll:false,relativeTo:this.offsetParent()},returnObject);},offset:function(options,returnObject){if(!this[0])error();var x=0,y=0,sl=0,st=0,elem=this[0],parent=this[0],op,parPos,elemPos=$.css(elem,'position'),mo=$.browser.mozilla,ie=$.browser.msie,oa=$.browser.opera,sf=$.browser.safari,sf3=$.browser.safari&&parseInt($.browser.version)>520,absparent=false,relparent=false,options=$.extend({margin:true,border:false,padding:false,scroll:true,lite:false,relativeTo:document.body},options||{});if(options.lite)return this.offsetLite(options,returnObject);if(options.relativeTo.jquery)options.relativeTo=options.relativeTo[0];if(elem.tagName=='BODY'){x=elem.offsetLeft;y=elem.offsetTop;if(mo){x+=num(elem,'marginLeft')+(num(elem,'borderLeftWidth')*2);y+=num(elem,'marginTop')+(num(elem,'borderTopWidth')*2);}else
if(oa){x+=num(elem,'marginLeft');y+=num(elem,'marginTop');}else
if((ie&&jQuery.boxModel)){x+=num(elem,'borderLeftWidth');y+=num(elem,'borderTopWidth');}else
if(sf3){x+=num(elem,'marginLeft')+num(elem,'borderLeftWidth');y+=num(elem,'marginTop')+num(elem,'borderTopWidth');}}else{do{parPos=$.css(parent,'position');x+=parent.offsetLeft;y+=parent.offsetTop;if(mo||ie||sf3){x+=num(parent,'borderLeftWidth');y+=num(parent,'borderTopWidth');if(mo&&parPos=='absolute')absparent=true;if(ie&&parPos=='relative')relparent=true;}op=parent.offsetParent||document.body;if(options.scroll||mo){do{if(options.scroll){sl+=parent.scrollLeft;st+=parent.scrollTop;}if(oa&&($.css(parent,'display')||'').match(/table-row|inline/)){sl=sl-((parent.scrollLeft==parent.offsetLeft)?parent.scrollLeft:0);st=st-((parent.scrollTop==parent.offsetTop)?parent.scrollTop:0);}if(mo&&parent!=elem&&$.css(parent,'overflow')!='visible'){x+=num(parent,'borderLeftWidth');y+=num(parent,'borderTopWidth');}parent=parent.parentNode;}while(parent!=op);}parent=op;if(parent==options.relativeTo&&!(parent.tagName=='BODY'||parent.tagName=='HTML')){if(mo&&parent!=elem&&$.css(parent,'overflow')!='visible'){x+=num(parent,'borderLeftWidth');y+=num(parent,'borderTopWidth');}if(((sf&&!sf3)||oa)&&parPos!='static'){x-=num(op,'borderLeftWidth');y-=num(op,'borderTopWidth');}break;}if(parent.tagName=='BODY'||parent.tagName=='HTML'){if(((sf&&!sf3)||(ie&&$.boxModel))&&elemPos!='absolute'&&elemPos!='fixed'){x+=num(parent,'marginLeft');y+=num(parent,'marginTop');}if(sf3||(mo&&!absparent&&elemPos!='fixed')||(ie&&elemPos=='static'&&!relparent)){x+=num(parent,'borderLeftWidth');y+=num(parent,'borderTopWidth');}break;}}while(parent);}var returnValue=handleOffsetReturn(elem,options,x,y,sl,st);if(returnObject){$.extend(returnObject,returnValue);return this;}else{return returnValue;}},offsetLite:function(options,returnObject){if(!this[0])error();var x=0,y=0,sl=0,st=0,parent=this[0],offsetParent,options=$.extend({margin:true,border:false,padding:false,scroll:true,relativeTo:document.body},options||{});if(options.relativeTo.jquery)options.relativeTo=options.relativeTo[0];do{x+=parent.offsetLeft;y+=parent.offsetTop;offsetParent=parent.offsetParent||document.body;if(options.scroll){do{sl+=parent.scrollLeft;st+=parent.scrollTop;parent=parent.parentNode;}while(parent!=offsetParent);}parent=offsetParent;}while(parent&&parent.tagName!='BODY'&&parent.tagName!='HTML'&&parent!=options.relativeTo);var returnValue=handleOffsetReturn(this[0],options,x,y,sl,st);if(returnObject){$.extend(returnObject,returnValue);return this;}else{return returnValue;}},offsetParent:function(){if(!this[0])error();var offsetParent=this[0].offsetParent;while(offsetParent&&(offsetParent.tagName!='BODY'&&$.css(offsetParent,'position')=='static'))offsetParent=offsetParent.offsetParent;return $(offsetParent);}});var error=function(){throw"Dimensions: jQuery collection is empty";};var num=function(el,prop){return parseInt($.css(el.jquery?el[0]:el,prop))||0;};var handleOffsetReturn=function(elem,options,x,y,sl,st){if(!options.margin){x-=num(elem,'marginLeft');y-=num(elem,'marginTop');}if(options.border&&(($.browser.safari&&parseInt($.browser.version)<520)||$.browser.opera)){x+=num(elem,'borderLeftWidth');y+=num(elem,'borderTopWidth');}else if(!options.border&&!(($.browser.safari&&parseInt($.browser.version)<520)||$.browser.opera)){x-=num(elem,'borderLeftWidth');y-=num(elem,'borderTopWidth');}if(options.padding){x+=num(elem,'paddingLeft');y+=num(elem,'paddingTop');}if(options.scroll&&(!$.browser.opera||elem.offsetLeft!=elem.scrollLeft&&elem.offsetTop!=elem.scrollLeft)){sl-=elem.scrollLeft;st-=elem.scrollTop;}return options.scroll?{top:y-st,left:x-sl,scrollTop:st,scrollLeft:sl}:{top:y,left:x};};var scrollbarWidth=0;var getScrollbarWidth=function(){if(!scrollbarWidth){var testEl=$('<div>').css({width:100,height:100,overflow:'auto',position:'absolute',top:-1000,left:-1000}).appendTo('body');scrollbarWidth=100-testEl.append('<div>').find('div').css({width:'100%',height:200}).width();testEl.remove();}return scrollbarWidth;};})(jQuery);


/* Copyright (c) 2006 Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * 
 * See http://kelvinluck.com/assets/jquery/jScrollPane/
 * $Id: jScrollPane.min.js 3579 2007-10-06 17:17:09Z kelvin.luck $
 */

jQuery.jScrollPane={active:[]};jQuery.fn.jScrollPane=function(settings){settings=jQuery.extend({scrollbarWidth:10,scrollbarMargin:5,wheelSpeed:18,showArrows:true,arrowSize:0,animateTo:false,dragMinHeight:1,dragMaxHeight:99999,animateInterval:100,animateStep:3,maintainPosition:true},settings);return this.each(function(){var $this=jQuery(this);if(jQuery(this).parent().is('.jScrollPaneContainer')){var currentScrollPosition=settings.maintainPosition?$this.offset({relativeTo:jQuery(this).parent()[0]}).top:0;var $c=jQuery(this).parent();var paneWidth=$c.innerWidth();var paneHeight=$c.outerHeight();var trackHeight=paneHeight;if($c.unmousewheel){$c.unmousewheel()}jQuery('>.jScrollPaneTrack, >.jScrollArrowUp, >.jScrollArrowDown',$c).remove();$this.css({'top':0})}else{var currentScrollPosition=0;this.originalPadding=$this.css('paddingTop')+' '+$this.css('paddingRight')+' '+$this.css('paddingBottom')+' '+$this.css('paddingLeft');this.originalSidePaddingTotal=(parseInt($this.css('paddingLeft'))||0)+(parseInt($this.css('paddingRight'))||0);var paneWidth=$this.innerWidth();var paneHeight=$this.innerHeight();var trackHeight=paneHeight;$this.wrap(jQuery('<div></div>').attr({'className':'jScrollPaneContainer'}).css({'height':paneHeight+'px','width':paneWidth+'px'}));jQuery(document).bind('emchange',function(e,cur,prev){$this.jScrollPane(settings)})}var p=this.originalSidePaddingTotal;$this.css({'height':'auto','width':paneWidth-settings.scrollbarWidth-settings.scrollbarMargin-p+'px','paddingRight':settings.scrollbarMargin+'px'});var contentHeight=$this.outerHeight();var percentInView=paneHeight/contentHeight;if(percentInView<.99){var $container=$this.parent();$container.append(jQuery('<div></div>').attr({'className':'jScrollPaneTrack'}).css({'width':settings.scrollbarWidth+'px'}).append(jQuery('<div></div>').attr({'className':'jScrollPaneDrag'}).css({'width':settings.scrollbarWidth+'px'}).append(jQuery('<div></div>').attr({'className':'jScrollPaneDragTop'}).css({'width':settings.scrollbarWidth+'px'}),jQuery('<div></div>').attr({'className':'jScrollPaneDragBottom'}).css({'width':settings.scrollbarWidth+'px'}))));var $track=jQuery('>.jScrollPaneTrack',$container);var $drag=jQuery('>.jScrollPaneTrack .jScrollPaneDrag',$container);if(settings.showArrows){var currentArrowButton;var currentArrowDirection;var currentArrowInterval;var currentArrowInc;var whileArrowButtonDown=function(){if(currentArrowInc>4||currentArrowInc%4==0){positionDrag(dragPosition+currentArrowDirection*mouseWheelMultiplier)}currentArrowInc++};var onArrowMouseUp=function(event){jQuery('body').unbind('mouseup',onArrowMouseUp);currentArrowButton.removeClass('jScrollActiveArrowButton');clearInterval(currentArrowInterval)};var onArrowMouseDown=function(){jQuery('body').bind('mouseup',onArrowMouseUp);currentArrowButton.addClass('jScrollActiveArrowButton');currentArrowInc=0;whileArrowButtonDown();currentArrowInterval=setInterval(whileArrowButtonDown,100)};$container.append(jQuery('<a></a>').attr({'href':'javascript:;','className':'jScrollArrowUp'}).css({'width':settings.scrollbarWidth+'px'}).html('Scroll up').bind('mousedown',function(){currentArrowButton=jQuery(this);currentArrowDirection=-1;onArrowMouseDown();this.blur();return false}),jQuery('<a></a>').attr({'href':'javascript:;','className':'jScrollArrowDown'}).css({'width':settings.scrollbarWidth+'px'}).html('Scroll down').bind('mousedown',function(){currentArrowButton=jQuery(this);currentArrowDirection=1;onArrowMouseDown();this.blur();return false}));var $upArrow = jQuery('>.jScrollArrowUp', $container);var $downArrow = jQuery('>.jScrollArrowDown', $container);if(settings.arrowSize){trackHeight=paneHeight-settings.arrowSize-settings.arrowSize;$track.css({'height':trackHeight+'px',top:settings.arrowSize+'px'})}else{var topArrowHeight=$upArrow.height();settings.arrowSize=topArrowHeight;trackHeight=paneHeight-topArrowHeight-$downArrow.height();$track.css({'height':trackHeight+'px',top:topArrowHeight+'px'})}}var $pane=jQuery(this).css({'position':'absolute','overflow':'visible'});var currentOffset;var maxY;var mouseWheelMultiplier;var dragPosition=0;var dragMiddle=percentInView*paneHeight/2;var getPos=function(event,c){var p=c=='X'?'Left':'Top';return event['page'+c]||(event['client'+c]+(document.documentElement['scroll'+p]||document.body['scroll'+p]))||0};var ignoreNativeDrag=function(){return false};var initDrag=function(){ceaseAnimation();currentOffset=$drag.offset(false);currentOffset.top-=dragPosition;maxY=trackHeight-$drag[0].offsetHeight;mouseWheelMultiplier=2*settings.wheelSpeed*maxY/contentHeight};var onStartDrag=function(event){initDrag();dragMiddle=getPos(event,'Y')-dragPosition-currentOffset.top;jQuery('body').bind('mouseup',onStopDrag).bind('mousemove',updateScroll);if(jQuery.browser.msie){jQuery('body').bind('dragstart',ignoreNativeDrag).bind('selectstart',ignoreNativeDrag)}return false};var onStopDrag=function(){jQuery('body').unbind('mouseup',onStopDrag).unbind('mousemove',updateScroll);dragMiddle=percentInView*paneHeight/2;if(jQuery.browser.msie){jQuery('body').unbind('dragstart',ignoreNativeDrag).unbind('selectstart',ignoreNativeDrag)}};var positionDrag=function(destY){destY=destY<0?0:(destY>maxY?maxY:destY);dragPosition=destY;$drag.css({'top':destY+'px'});var p=destY/maxY;$pane.css({'top':((paneHeight-contentHeight)*p)+'px'});$this.trigger('scroll'); if (settings.showArrows) {$upArrow[destY == 0 ? 'addClass' : 'removeClass']('disabled');$downArrow[destY == maxY ? 'addClass' : 'removeClass']('disabled');}};var updateScroll=function(e){positionDrag(getPos(e,'Y')-currentOffset.top-dragMiddle)};var dragH=Math.max(Math.min(percentInView*(paneHeight-settings.arrowSize*2),settings.dragMaxHeight),settings.dragMinHeight);$drag.css({'height':dragH+'px'}).bind('mousedown',onStartDrag);var trackScrollInterval;var trackScrollInc;var trackScrollMousePos;var doTrackScroll=function(){if(trackScrollInc>8||trackScrollInc%4==0){positionDrag((dragPosition-((dragPosition-trackScrollMousePos)/2)))}trackScrollInc++};var onStopTrackClick=function(){clearInterval(trackScrollInterval);jQuery('body').unbind('mouseup',onStopTrackClick).unbind('mousemove',onTrackMouseMove)};var onTrackMouseMove=function(event){trackScrollMousePos=getPos(event,'Y')-currentOffset.top-dragMiddle};var onTrackClick=function(event){initDrag();onTrackMouseMove(event);trackScrollInc=0;jQuery('body').bind('mouseup',onStopTrackClick).bind('mousemove',onTrackMouseMove);trackScrollInterval=setInterval(doTrackScroll,100);doTrackScroll()};$track.bind('mousedown',onTrackClick);if($container.mousewheel){$container.mousewheel(function(event,delta){initDrag();ceaseAnimation();var d=dragPosition;positionDrag(dragPosition-delta*mouseWheelMultiplier);var dragOccured=d!=dragPosition;return!dragOccured},false)}var _animateToPosition;var _animateToInterval;function animateToPosition(){var diff=(_animateToPosition-dragPosition)/settings.animateStep;if(diff>1||diff<-1){positionDrag(dragPosition+diff)}else{positionDrag(_animateToPosition);ceaseAnimation()}}var ceaseAnimation=function(){if(_animateToInterval){clearInterval(_animateToInterval);delete _animateToPosition}};var scrollTo=function(pos,preventAni){if(typeof pos=="string"){$e=jQuery(pos,this);if(!$e.length)return;pos=$e.offset({relativeTo:this}).top}ceaseAnimation();var destDragPosition=-pos/(paneHeight-contentHeight)*maxY;if(!preventAni||settings.animateTo){_animateToPosition=destDragPosition;_animateToInterval=setInterval(animateToPosition,settings.animateInterval)}else{positionDrag(destDragPosition)}};$this[0].scrollTo=scrollTo;$this[0].scrollBy=function(delta){var currentPos=-parseInt($pane.css('top'))||0;scrollTo(currentPos+delta)};initDrag();scrollTo(-currentScrollPosition,true);jQuery.jScrollPane.active.push($this[0])}else{$this.css({'height':paneHeight+'px','width':paneWidth-this.originalSidePaddingTotal+'px','padding':this.originalPadding})}})};jQuery(window).bind('unload',function(){var els=jQuery.jScrollPane.active;for(var i=0;i<els.length;i++){els[i].scrollTo=els[i].scrollBy=null}});


/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

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
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        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;
    }
};

/*
 * jQuery history plugin
 *
 * Copyright (c) 2006 Taku Sano (Mikage Sawatari)
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Modified by Lincoln Cooper to add Safari support and only call the callback once during initialization
 * for msie when no initial hash supplied.
 */


jQuery.extend({
	historyCurrentHash: undefined,
	
	historyCallback: undefined,
	
	historyInit: function(callback){
		jQuery.historyCallback = callback;
		var current_hash = location.hash;
		
		jQuery.historyCurrentHash = current_hash;
		if(jQuery.browser.msie) {
			// To stop the callback firing twice during initilization if no hash present
			if (jQuery.historyCurrentHash == '') {
			jQuery.historyCurrentHash = '#';
		}
		
			// add hidden iframe for IE
			$("body").prepend('<iframe id="jQuery_history" style="display: none;"></iframe>');
			var ihistory = $("#jQuery_history")[0];
			var iframe = ihistory.contentWindow.document;
			iframe.open();
			iframe.close();
			iframe.location.hash = current_hash;
		}
		else if ($.browser.safari) {
			// etablish back/forward stacks
			jQuery.historyBackStack = [];
			jQuery.historyBackStack.length = history.length;
			jQuery.historyForwardStack = [];
			
			jQuery.isFirst = true;
		}
	//	jQuery.historyCallback(current_hash.replace(/^#/, ''));
		setInterval(jQuery.historyCheck, 100);
	},
	
	historyAddHistory: function(hash) {
		// This makes the looping function do something
		jQuery.historyBackStack.push(hash);
		
		jQuery.historyForwardStack.length = 0; // clear forwardStack (true click occured)
		this.isFirst = true;
	},
	
	historyCheck: function(){
try
{
		if(jQuery.browser.msie) {
			// On IE, check for location.hash of iframe
			var ihistory = $("#jQuery_history")[0];
			var iframe = ihistory.contentDocument || ihistory.contentWindow.document;
			var current_hash = iframe.location.hash;
			if(current_hash != jQuery.historyCurrentHash) {
			
				location.hash = current_hash;
				jQuery.historyCurrentHash = current_hash;
				jQuery.historyCallback(current_hash.replace(/^#/, ''));
				
			}
		} else if ($.browser.safari) {
			if (!jQuery.dontCheck) {
				var historyDelta = history.length - jQuery.historyBackStack.length;
				
				if (historyDelta) { // back or forward button has been pushed
					jQuery.isFirst = false;
					if (historyDelta < 0) { // back button has been pushed
						// move items to forward stack
						for (var i = 0; i < Math.abs(historyDelta); i++) jQuery.historyForwardStack.unshift(jQuery.historyBackStack.pop());
					} else { // forward button has been pushed
						// move items to back stack
						for (var i = 0; i < historyDelta; i++) jQuery.historyBackStack.push(jQuery.historyForwardStack.shift());
					}
					var cachedHash = jQuery.historyBackStack[jQuery.historyBackStack.length - 1];
					if (cachedHash != undefined) {
						jQuery.historyCurrentHash = location.hash;
						jQuery.historyCallback(cachedHash);
					}
				} else if (jQuery.historyBackStack[jQuery.historyBackStack.length - 1] == undefined && !jQuery.isFirst) {
					// back button has been pushed to beginning and URL already pointed to hash (e.g. a bookmark)
					// document.URL doesn't change in Safari
					if (document.URL.indexOf('#') >= 0) {
						jQuery.historyCallback(document.URL.split('#')[1]);
					} else {
						var current_hash = location.hash;
						jQuery.historyCallback('');
					}
					jQuery.isFirst = true;
				}
			}
		} else {
			// otherwise, check for location.hash
			var current_hash = location.hash;
			if(current_hash != jQuery.historyCurrentHash) {
				jQuery.historyCurrentHash = current_hash;
				jQuery.historyCallback(current_hash.replace(/^#/, ''));
			}
		}
	
}
catch (e)
{
}

	},
	historyLoad: function(hash){
		var newhash;
		
		if (jQuery.browser.safari) {
			newhash = hash;
		}
		else {
			newhash = '#' + hash;
			//alert(1);
			location.hash = newhash;
		}
		jQuery.historyCurrentHash = newhash;
		
		if(jQuery.browser.msie) {
			var ihistory = $("#jQuery_history")[0];
			var iframe = ihistory.contentWindow.document;
			iframe.open();
			iframe.close();
			iframe.location.hash = newhash;
			jQuery.historyCallback(hash, true);
		}
		else if (jQuery.browser.safari) {
			jQuery.dontCheck = true;
			// Manually keep track of the history values for Safari
			this.historyAddHistory(hash);
			
			// Wait a while before allowing checking so that Safari has time to update the "history" object
			// correctly (otherwise the check loop would detect a false change in hash).
			var fn = function() {jQuery.dontCheck = false;};
			window.setTimeout(fn, 200);
			jQuery.historyCallback(hash, true);
			// N.B. "location.hash=" must be the last line of code for Safari as execution stops afterwards.
			//      By explicitly using the "location.hash" command (instead of using a variable set to "location.hash") the
			//      URL in the browser and the "history" object are both updated correctly.
			location.hash = newhash;
		}
		else {
		  jQuery.historyCallback(hash, true);
		}
	}
});


/* Copyright (c) 2006 Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 *
 * $LastChangedDate: 2007-12-14 23:57:10 -0600 (Fri, 14 Dec 2007) $
 * $Rev: 4163 $
 *
 * Version: 3.0
 * 
 * Requires: $ 1.2.2+
 */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(5($){$.6.j.4={L:5(){9 b=$.6.j.4.i;7($.8.f)$(2).o(\'y.4\',5(a){$.d(2,\'h\',{x:a.x,l:a.l,s:a.s,r:a.r})});7(2.q)2.q(($.8.f?\'v\':\'4\'),b,n);m 2.w=b},D:5(){9 a=$.6.j.4.i;$(2).k(\'y.4\');7(2.u)2.u(($.8.f?\'v\':\'4\'),a,n);m 2.w=5(){};$.A(2,\'h\')},i:5(a){9 c=U.T.S.P(O,1);a=$.6.N(a||M.6);$.t(a,$.d(2,\'h\')||{});9 b=0,K=J;7(a.e)b=a.e/I;7(a.p)b=-a.p/3;7($.8.H)b=-a.e;a.d=a.d||{};a.G="4";c.z(b);c.z(a);g $.6.F.E(2,c)}};$.Q.t({4:5(a){g a?2.o("4",a):2.R("4")},C:5(a){g 2.k("4",a)}})})(B);',57,57,'||this||mousewheel|function|event|if|browser|var||||data|wheelDelta|mozilla|return|mwcursorposdata|handler|special|unbind|pageY|else|false|bind|detail|addEventListener|clientY|clientX|extend|removeEventListener|DOMMouseScroll|onmousewheel|pageX|mousemove|unshift|removeData|jQuery|unmousewheel|teardown|apply|handle|type|opera|120|true|returnValue|setup|window|fix|arguments|call|fn|trigger|slice|prototype|Array'.split('|'),0,{}));

/* Copyright 2008 MagicToolBox.com. To use this code on your own site, visit http://magictoolbox.com */
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('a 4=\'h\';a W=X.Y.V();6(W.7("n")!=-1){4=\'n\'}j 6(W.7("h")!=-1){4=\'h\'}j 6(W.7("m")!=-1){4=\'m\'}j 6(W.7("U")!=-1){4=\'q\'}d A(){};A.R={S:d(3){2.3=3;a e=B.T(\'Z\');2.f=\'\';10(a i=0;i<e.15;i++){6(e[i].5&&(/u.16/i.14(e[i].5))){a 5=e[i].5;Q=(5.7(\'y\')!=-1)?\'y\':\'\';5=5.13(0,5.11(\'/\'));2.f=5+"/";6(2.f==\'/\')2.f=\'\';12}}2.3[\'r\']="17"+2.3[\'r\'].G(\'#\',\'\');2.k=2.3[\'k\'];2.o=2.f+\'u?k=\'+2.p(2.k)+\'&w=\'+2.p(2.3[\'w\'])+\'&L=\'+((2.3["P"]==\'1\')?\'0\':\'1\')+\'&O=\'+2.3[\'r\']+\'&I=\'+2.3[\'I\']+\'&z=\'+2.3[\'z\'];a l=B.M+\'\';l=(l.7("C")!=-1)?"C":"v";H N(\'K\',l+\'://1e.t.x/1H/1v/1w/1y/1z.1x#1t=9,0,0,0\',\'1A\',\'1B:18-1G-1F-1E-1C\',\'J\',2.3[\'J\'],\'s\',2.3[\'s\'],\'5\',2.o,\'1D\',\'1u\',\'1r\',\'v://1s.t.x/1f/1g\',\'1d\',2.o,\'1c\',\'19\',\'1a\',\'1b\',\'1h\',\'.\')},p:d(F){H 1i(1o(F)).G(/\\+/g,\'%1p\')}};d 1q(8,b,c){6(4==\'q\'||4==\'n\'||4==\'m\'){8.1n(b,c,D)}j 6(4==\'h\'){8.1m("E"+b,c)}};d 1j(8,b,c){6(4==\'q\'||4==\'n\'||4==\'m\'){8.1k(b,c,D)}j 6(4==\'h\'){8.1l("E"+b,c)}};',62,106,'||this|params|mm_ua|src|if|indexOf|obj||var|event|listener|function|MagicMagnify_elements|baseurl||msie||else|smallImageUrl|httppref|safari|opera|swfUrl|escapeParam|gecko|zoomColor|height|macromedia|magicmagnify|http|bigImageUrl|com|_src|type|MagicMagnifyClass|document|https|false|on|val|replace|return|magnifierSize|width|codebase|lineThickness|location|AC_FL_RunContent|lineColor|noborder|srcMode|prototype|init|getElementsByTagName|mozilla|toLowerCase||navigator|userAgent|script|for|lastIndexOf|break|substring|test|length|js|0x|d27cdb6e|transparent|allowScriptAccess|always|wmode|movie|fpdownload|go|getflashplayer|base|escape|MagicMagnify_removeEventListener|removeEventListener|detachEvent|attachEvent|addEventListener|encodeURIComponent|2B|MagicMagnify_addEventListener|pluginspage|www|version|high|shockwave|cabs|cab|flash|swflash|classid|clsid|444553540000|quality|96b8|11cf|ae6d|pub'.split('|'),0,{}))

function MagicMagnify_findMagnifiers(){var aels=window.document.getElementsByTagName("A");for(var i=0;i<aels.length;i++){if(aels[i].className=="MagicMagnify"){while(aels[i].firstChild){if(aels[i].firstChild.tagName!='IMG'){aels[i].removeChild(aels[i].firstChild)}else{break}}if(aels[i].firstChild.tagName!='IMG')throw"Invalid Magic Magnify invocation!";var re=new RegExp(/zoom\-color(\s+)?:(\s+)?#?(\w+)/i);var matches=re.exec(aels[i].rel);var zoomColor='#9E2F2D';if(matches){zoomColor=matches[3]}var re=new RegExp(/size(\s+)?:(\s+)?(\d+)/i);var matches=re.exec(aels[i].rel);var zoomSize='100px';if(matches){zoomSize=parseInt(matches[3])}var re=new RegExp(/type(\s+)?:(\s+)?(circle|square)/i);var matches=re.exec(aels[i].rel);var zoomType='circle';if(matches){zoomType=matches[3]}var div=document.createElement("DIV");var ClockMagnifier=new MagicMagnifyClass();var params={width:parseInt(aels[i].firstChild.width),height:parseInt(aels[i].firstChild.height),smallImageUrl:aels[i].firstChild.src,bigImageUrl:aels[i].href,zoomColor:zoomColor,magnifierSize:zoomSize,type:zoomType};div.innerHTML=ClockMagnifier.init(params);var p=aels[i].parentNode;p.replaceChild(div,aels[i]);i=i-1}}};MagicMagnify_addEventListener(window,"load",MagicMagnify_findMagnifiers);
/* Copyright 2006 Adobe Systems, Inc. All rights reserved. */
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('f I(e,k){u(e.1E(\'?\')!=-1)g e.1B(/\\?/,k+\'?\');1D g e+k}f m(8,9,6){7 c=\'<F \';j(7 i o 8)c+=i+\'="\'+8[i]+\'" \';c+=\'>\';j(7 i o 9)c+=\'<1C q="\'+i+\'" 1z="\'+9[i]+\'" /> \';c+=\'<w \';j(7 i o 6)c+=i+\'="\'+6[i]+\'" \';c+=\' ></w></F>\';g c}f 1F(){7 4=p(r,".1u","J","K:1w-1y-1x-1v-H","1A/x-1O-1N");g m(4.8,4.9,4.6)}f 1P(){7 4=p(r,".1Q","e","K:1L-1G-1M-1H-H",1I);m(4.8,4.9,4.6)}f p(5,k,O,h,s){7 4=a b();4.6=a b();4.9=a b();4.8=a b();j(7 i=0;i<5.G;i=i+2){7 l=5[i].L();P(l){3"h":d;3"N":4.6[5[i]]=5[i+1];d;3"e":3"J":5[i+1]=I(5[i+1],k);4.6["e"]=5[i+1];4.9[O]=5[i+1];d;3"R":3"t":3"y":3"z":3"D":3"C":3"B":3"A":3"M":3"10":3"1k":3"1j":3"1i":3"1h":3"1g":3"1c":3"1d":3"1m":3"1e":3"1f":3"1l":3"1t":3"1s":3"1r":3"1n":3"1o":3"1p":3"1q":3"1a":3"X":3"Y":3"Z":3"W":3"V":3"S":3"T":3"U":3"n":3"E":4.8[5[i]]=5[i+1];d;3"1b":3"11":3"17":3"18":3"19":3"16":3"15":3"12":3"q":3"v":3"13":4.6[5[i]]=4.8[5[i]]=5[i+1];d;14:4.6[5[i]]=4.9[5[i]]=5[i+1]}}4.8["h"]=h;u(s)4.6["n"]=s;g 4}f 1J(){7 4=Q(r);m(4.8,4.9,4.6)}f Q(5){7 4=a b();4.6=a b();4.9=a b();4.8=a b();j(7 i=0;i<5.G;i=i+2){7 l=5[i].L();P(l){3"N":3"n":3"e":4.6[5[i]]=5[i+1];d;3"1K":3"E":3"h":3"v":3"R":3"t":3"y":3"z":3"D":3"C":3"B":3"A":3"M":3"10":3"1k":3"1j":3"1i":3"1h":3"1g":3"1c":3"1d":3"1m":3"1e":3"1f":3"1l":3"1t":3"1s":3"1r":3"1n":3"1o":3"1p":3"1q":3"1a":3"X":3"Y":3"Z":3"W":3"V":3"S":3"T":3"U":4.8[5[i]]=5[i+1];d;3"1b":3"11":3"17":3"18":3"19":3"16":3"15":3"12":3"q":3"13":4.6[5[i]]=4.8[5[i]]=5[i+1];d;14:4.6[5[i]]=4.9[5[i]]=5[i+1]}}g 4}',62,115,'|||case|ret|args|embedAttrs|var|objAttrs|params|new|Object|str|break|src|function|return|classid||for|ext|currArg|LZ_AC_Generateobj|type|in|LZ_AC_GetArgs|name|arguments|mimeType|onbeforeupdate|if|id|embed||onblur|oncellchange|ondragend|ondrag|ondblClick|onclick|codebase|object|length|444553540000|LZ_AC_AddExtension|movie|clsid|toLowerCase|ondragenter|pluginspage|srcParamName|switch|LZ_AC_AX_GetArgs|onafterupdate|onactivate|onbeforedeactivate|ondeactivate|onbeforeeditfocus|onscroll|onrowexit|onrowsinserted|onstart|ondragleave|height|accesskey|tabindex|default|title|class|align|vspace|hspace|onrowenter|width|onmousedown|onmouseup|onmousemove|onmouseout|onhelp|onfocus|onfinish|ondrop|ondragover|onkeypress|onmouseover|onlosecapture|onpropertychange|onreadystatechange|onrowsdelete|onload|onkeyup|onkeydown|swf|96b8|d27cdb6e|11cf|ae6d|value|application|replace|param|else|indexOf|AC_FL_RunContent|3F9C|8075|null|LZ_AC_AX_RunContent|data|166B1BCA|11CF|flash|shockwave|LZ_AC_SW_RunContent|dcr'.split('|'),0,{}));

var debug=0;
if(document.location.host == "treviarmory.localhost")
	debug=1;

$(document).ready(function() {

	Navigation.init();
	Main.init();

});


function historyCall(hash, sl)
{
	if(hash) 
	{
		if (!sl) 
		{

			if (hash == 'fc')
			{
				hash = $.cookie('last_url');
			}

			if (hash.indexOf('h_') != -1)
			{
				Navigation.goHTML(Main.historyStock[parseInt(hash.replace('arm:h_', ''))], true);
			}

		}
	} else 
	{
		Navigation.goHTML('/index.php?category=&mode=ajax', true);
	}

}


var Main = {
	historyStock			: [],
	historyStockI		: 0,

	init: function()
	{
		$("#jQueryRotator").adsRotate();
		$.fn.media.defaults.bgColor="";
		$('#logoFlash').media({
			width:     331,
			height:    195,
			src:       '/i/swf/logo.swf',
			attrs:     {wmode: 'transparent', scale: "noborder", quality:"high", allowscriptaccess:"sameDomain"},  // object/embed attrs 
			params:    {wmode: 'transparent', scale: "noborder", quality:"high", allowscriptaccess:"sameDomain"} // object params/embed attrs 
		});
		run_writer();setInterval("run_writer()", 40000);
		if(!debug)
			loadSound();
		
		$("#book").mouseover(function(){$("#menu").find("ul").css({display:"none"});});
		$("#lineRight").mouseover(function(){$("#menu").find("ul").css({display:"none"});});
		$("#menu ul a").click(function() {
            $("#menu").find("ul").css({display:"none"});
            Navigation.goHTML(this.href);
            return false;
        });
		/*$("#menu .m").createPrepend(
				'div', {className:'ff'}, '<!-- -->'
			);*/
		/*$('.ff').media({
			width:     163,
			height:    30,
			src:       '/i/swf/fire.swf',
			attrs:     {wmode: 'transparent', scale: "noborder", quality:"high", allowscriptaccess:"sameDomain"},  // object/embed attrs 
			params:    {wmode: 'transparent', scale: "noborder", quality:"high", allowscriptaccess:"sameDomain"} // object params/embed attrs 
		});*/
		/*jQuery.each($("#menu .m"), function()
			{

				$(this).createPrepend(
					'div', {className:'eff'}, '<!-- -->'
				);
				$(this).createAppend(
						'div', {className:'layer'}, '<!-- -->'
					);
				$(this).createAppend(
					'div', {className:'layer',
						onmouseover : function()
						{
						$("#menu").find("ul").css({display:"none"});
						$(this).parent().find("ul").css({display:"block"});
						$(this).parent().css('background-image','none');
						var s=$(this).parent().attr('id_m');
						
		
						switch (s)
						{
						case '1':$('.ff').css({'left':'7px','top':'190px'});
						break;
						case '2':$('.ff').css({'left':'170px','top':'190px'});
						break;
						case '3':$('.ff').css({'left':'332px','top':'190px'});
						break;
						case '4':$('.ff').css({'left':'495px','top':'190px'});
						break;
						case '5':$('.ff').css({'left':'657px','top':'190px'});
						break;
						case '6':$('.ff').css({'left':'822px','top':'190px'});
						break;
						case '7':$('.ff').css({'left':'7px','top':'217px'});
						break;
						case '8':$('.ff').css({'left':'170px','top':'217px'});
						break;
						case '9':$('.ff').css({'left':'332px','top':'217px'});
						break;
						case '10':$('.ff').css({'left':'495px','top':'217px'});
						break;
						case '11':$('.ff').css({'left':'657px','top':'217px'});
						break;
						case '12':$('.ff').css({'left':'822px','top':'217px'});
						break;
						}
						$('.ff').css('display','block');
						},
						onmouseout : function()
						{
							$(this).parent().css('background-image','url("/i/button.gif")');
							var eff = $(".eff", $(this).parent());
							$(eff).html("");
							$('.ff').css('display','none');
						},
						onclick: function(){
							Navigation.goHTML($(this).parent().find("a").attr("href"));
							return false;
						}
					},'<!-- -->'
				);
				/*$(this).find('.layer').hover(function(){
					$("#menu").find("ul").css({display:"none"});
					$(this).parent().find("ul").css({display:"block"});
					$(this).parent().css('background-image','none');
					var s=$(this).parent().attr('id_m');
					
	
					switch (s)
					{
					case '1':$('.ff').css({'left':'7px','top':'190px'});
					break;
					case '2':$('.ff').css({'left':'170px','top':'190px'});
					break;
					case '3':$('.ff').css({'left':'332px','top':'190px'});
					break;
					case '4':$('.ff').css({'left':'495px','top':'190px'});
					break;
					case '5':$('.ff').css({'left':'657px','top':'190px'});
					break;
					case '6':$('.ff').css({'left':'822px','top':'190px'});
					break;
					case '7':$('.ff').css({'left':'7px','top':'217px'});
					break;
					case '8':$('.ff').css({'left':'170px','top':'217px'});
					break;
					case '9':$('.ff').css({'left':'332px','top':'217px'});
					break;
					case '10':$('.ff').css({'left':'495px','top':'217px'});
					break;
					case '11':$('.ff').css({'left':'657px','top':'217px'});
					break;
					case '12':$('.ff').css({'left':'822px','top':'217px'});
					break;
					}
					$('.ff').css('display','block');
					
					
					
					
					
						
				},function(){
					$(this).parent().css('background-image','url("/i/button.gif")');
					var eff = $(".eff", $(this).parent());
					$(eff).html("");
					$('.ff').css('display','none');
					
				});*/
			//}*/
		jQuery.each($("#menu .m"), function()
				{

					$(this).createPrepend(
						'div', {className:'eff'}, '<!-- -->'
					);
					$(this).createAppend(
						'div', {className:'layer',
							onmouseover : function()
							{
								$("#menu").find("ul").css({display:"none"});
								$(this).parent().find("ul").css({display:"block"});
								var eff = $(".eff", $(this).parent());
								$(eff).media({
									width:     163,
									height:    30,
									src:       '/i/swf/fire.swf',
									attrs:     {wmode: 'transparent', scale: "noborder", quality:"high", allowscriptaccess:"sameDomain"},  // object/embed attrs 
									params:    {wmode: 'transparent', scale: "noborder", quality:"high", allowscriptaccess:"sameDomain"} // object params/embed attrs 
								});
							},
							onmouseout : function()
							{
								var eff = $(".eff", $(this).parent());
								$(eff).html("");
							},
							onclick: function(){
								Navigation.goHTML($(this).parent().find("a").attr("href"));
								return false;
							}
						},'<!-- -->'
					);
				}
		);
		$("#goodDescriptionText").jScrollPane();
		Main.initPageAnimation();

		var form = $('#order-box').html();
		$('#order-box-container').html(form);
	},

	historyAdd : function(url)
	{
		
		if (url != 'fc')
		{
			$.cookie('last_url', url, {path: '/'});
		}
		
		//alert(url);
		Main.historyStock[Main.historyStockI] = url
        var re = /catalog\/(.*).html/;
        var str = str_replace('http://www.treviarmory.com', '', url);
       /* var newstr = str.replace(re, "$1");
            newstr = newstr.replace('http://treviarmory.com', "");
            newstr = newstr.replace('/', "");*/
        //alert(newstr); // "Smith, John"

        //$.historyLoad('arm:h_' + Main.historyStockI, true);
		$.historyLoad(str, true);

		Main.historyStockI++;

	},

	isAnimated:false,
	isImageLoaded:false,
	initPageAnimation : function()
	{
		$(".good .text a").click(function(){$(this).parent().parent().find(".thumb").find("img").click();return false;});
		$(".good .text h1").click(function(){$(this).parent().parent().find(".thumb").find("img").click();return false;});
		$(".good .thumb img").click(
			function(e)
			{
				Main.isImageLoaded = Main.isAnimated = false;
				var k = parseInt(this.id.replace("_n", ""));
				$("#imgMover").css({left:17,top:10+k*125,width:100,height:100,display:"none"});
				var img = new Image(370,370);
				var src = img.src=this.src.replace("_thumb", "")+"?"+Math.random();
				img.onload = function()
				{
					Main.isImageLoaded = true;
					if(Main.isAnimated ==true)
					{
						Main.releaseAnimation(this.src);
					}
					else
					{
						$("#imgcont").css({backgroundImage:"url("+this.src+")"});
						$("#imgMover").attr("src", this.src);
					}
					
				};

				$("#imgMover").attr("src", this.src).css({display:"block"}).animate({left:-429,top:10,width:370,height:370}, 2000, function()
					{
						Main.isAnimated = true;
						if(Main.isImageLoaded ==true)
						{
							Main.releaseAnimation(src);
						}
					}
				);

				// Item Description

				var what2hide = $.browser.msie ? "#goodDescription, #goodDescriptionText, #goodDescription .jScrollPane, #goodDescription .jScrollPaneTrack" : "#goodDescription";

				var html = $('.i-goodDescription', $(this).parent().parent()).html();

				$(what2hide).animate({opacity: 0.1}, 800, function (e) {
					
					$('#goodDescription').html(html);
					$('#goodDescriptionText').jScrollPane();
					$(what2hide).css({opacity: 0.2});

					window.setTimeout("$('" + what2hide + "').animate({opacity: 1}, 800, function (e) {Main.goodDescription()})", 200);

				});

			}
		);
	},

	goodDescription : function()
	{
		var form = $('#order-box').html();
	
		$('#order-box-container').html(form);

	},

	releaseAnimation : function(src)
	{
		$("#imgcont").html("").css({backgroundImage:"url('"+src+"')"}).createAppend(
			'a', {href:src.replace('.jpg', '_zoom.jpg'),className:"MagicMagnify",rel:"zoom-color:#86370C;size:170px;type:circle"}, [
				'img', {src:src,width:370,height:370}
			]
		);
		MagicMagnify_findMagnifiers();
		var pn="";
		
        Main.loadViews(src); 
		$("#imgMover").css({display:"none"});
	},

	loadViews : function(src)
	{
		
        if (src != 'http://i.treviartgallery.com/') {
            
        
            var pn = src.replace(/.+\/([^/]+).jpg.*/, '$1');
		    $("#views a").css({display:"none"}).removeClass("here");
		    $.get("/inc/loadviews.php", {pn:pn}, function(data)
				    {
					    var arr = data.split("|");
					    if(arr.length>1)
					    {
						    $("#views a:first").addClass("here");
						    for(var i=0;i<arr.length;i++)
						    {
							    $("#views a:eq("+i+")").css({display:"inline"}).click(function()
								    {
									    $("#views a").removeClass("here");
									    this.className = "here";
									    src = src.replace(/([^/]+).jpg/, this.rel);
									    $("#imgcont").html("").css({backgroundImage:"url('"+src+"')"}).createAppend(
										    'a', {href:src.replace('.jpg', '_zoom.jpg'),className:"MagicMagnify",rel:"zoom-color:#86370C;size:170px;type:circle"}, [
											    'img', {src:src,width:370,height:370}
										    ]
									    );
									    MagicMagnify_findMagnifiers();
									    return false;
								    }
							    ).attr("rel", arr[i]);
						    }
					    }
				    }
			    );
        }
	}
};

var Navigation = {

	currPage	: 0,
	totalPages : 0,
	url : '/catalog/kalashnikov-series.html',

	init : function()
	{
		var url = location.href.replace(/http\:\/\/[^/]+\//, '/');
		Navigation.url = url == '/' ? Navigation.url : url;
	},

	set : function(totalPages)
	{
		this.totalPages		= totalPages;
		this.currPage		= 0;
		if(this.totalPages ==1)
			$("#next").hide();
		$('#prev').hide();
	},

	next : function()
	{
		Navigation.currPage +=1;
		Navigation.go(function () {

			$('#prev').show();
			Navigation.currPage == Navigation.totalPages - 1 ? $('#next').hide() : $('#next').show();

		});

	},

	prev : function()
	{
		Navigation.currPage -=1;
		Navigation.go(function () {

			!Navigation.currPage ? $('#prev').hide() : $('#prev').show();
		});

	},
	
	go : function(func)
	{
		url = Navigation.url.replace(/\/[\d]+\.html/, '.html').replace('.html', '/' + Navigation.currPage + '.html');
 
		$.get(url, {mode:"ajax"}, function(data)
			{
				$("#pages").html(data);
				MagicMagnify_findMagnifiers();
				Main.initPageAnimation();
				func ? func() : false;
			}
		);
	},

	goHTML : function(url, no_history)
	{

		if (!no_history)
		{
			Main.historyAdd(url);
		}


		Navigation.url = url;
		try
		{
			pageTracker._trackPageview(url);
		}
		catch (e)
		{

		}
		$.get(url, {mode:"ajax"}, function(data)
			{

				$("#pages").html(data);
				Main.initPageAnimation();

				totalPages = parseInt($('#total_pages').html());
				Navigation.set(totalPages);

				$('#prev').hide();
				Navigation.totalPages == 1 ? $('#next').hide() : $('#next').show();
				
				MagicMagnify_findMagnifiers();

			}
		);

	},

	addISItem : function(obj, id)
	{
		obj.innerHTML = 'please wait...';

	//	var id			= parseInt($('#add-to-card .item-id').html());
		var is_addr	= $('#is-addr').html();

		$.get('/getisitemid.php?id=' + id, {}, function(data)
		{
			$(".ProductID").val(data).attr('id', 'ProductID_' + data);
			$(".AddtoCart").attr('name', 'AddToCart_' + data).attr('id', 'AddToCart_' + data);
			$(".IsWishList").attr('name', 'IsWishList_' + data).attr('id', 'IsWishList_' + data);
//		debugger;
			$('#add-to-card').submit();

		});
	
	}

};

(function($) {
	$.fn.adsRotate = function(options)
	{
		var defaults = {
			params : {width:1215,height:1109}
		};
		var opts = $.extend(defaults, options);
		loadImage(this, opts);
	};

	function loadImage(obj, opts)
	{
		var img = new Image();
		var src = img.src = "/i/bn/getimage.php?"+Math.random();
		img.onload = function()
		{
			$(obj).createAppend(
				'img', {src:src, width:opts.params.width, height:opts.params.height, style:"display:none"}
				).animate({opacity:.01}, 1, function()
					{
						$(this).css({display:"block"});
						$(this).animate({opacity:1}, 2500, function()
							{
								if($("img",$(obj)).length >1)
									$("img:first",$(obj)).remove();
								setTimeout("fuckAds()", 10000);
							}
						);
					}
				);
		}
	};

})(jQuery);

function fuckAds()
{
	$("#jQueryRotator").adsRotate();
}

function loadSound()
{
	var sounds = [
		"/i/sound/thaikovsky_1812.mp3",
		"/i/sound/glinka_overture_russlan_and_ludmila.mp3",
		"/i/sound/khachaturian_sabre_dance.mp3",
		"/i/sound/khachaturian_waltz_from_masquerade.mp3"
	];

	$('#snd').media({
		width:     115,
		height:    25,
		src:       "/i/sound/snd.swf?mp3String="+sounds.join(";"),
		attrs:     { wmode: 'transparent', scale: "noborder", quality:"high", allowscriptaccess:"sameDomain"},  // object/embed attrs 
		params:    { wmode: 'transparent', scale: "noborder", quality:"high", allowscriptaccess:"sameDomain"} // object params/embed attrs 
	});

}


function fixPNG(element)
{

	if (/MSIE (5\.5|6).+Win/.test(navigator.userAgent))
	{
		var src;
		if (element.tagName=='IMG')
		{
			if (/\.png$/.test(element.src))
			{
				src = element.src;
				element.src = "/i/pix.gif";
			}
		else 
		{
			src = element.currentStyle.backgroundImage.match(/url\("(.+\.png)"\)/i);
			if (src)
			{
				src = src[1];
				element.runtimeStyle.backgroundImage="none";
			}
		}
	}
	else
	{
		src = element.currentStyle.backgroundImage.match(/url\("(.+\.png)"\)/i);
		if (src)
		{
			src = src[1];
			element.runtimeStyle.backgroundImage="none";
		}
	}
	if (src) 

		element.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
	}
};

var prases = [
	[escape("First Time on American Continent!!!")+"&sign_scale=0.55&offset_x=10&sign_color=0xFFFD7F&glow_color=0xCCCCCC&line_height=60&offset_y=-40"],
	[escape("Happy Holiday Season!!! Order Now and Save!!!")+"&sign_scale=0.55&offset_x=10&sign_color=0xFFFD7F&glow_color=0xCCCCCC&line_height=60&offset_y=-40"],
	[escape("Buy Directly from Moscow Kremlin Purveyor and Save!")+"&sign_scale=0.55&offset_x=10&sign_color=0xFFFD7F&glow_color=0xCCCCCC&line_height=60&offset_y=-40"]
];
var phrasesLastId=1;

function run_writer()
{
	do{
		var id = Math.floor(Math.random()*prases.length);
	}while(id == phrasesLastId);
	$('#writer').media({
		width:     900,
		height:    60,
		src:       "/i/swf/demo_armory.swf?sign_text="+prases[phrasesLastId = id],
		attrs:     {id:'swfwriter',wmode: 'transparent', scale: "noborder", quality:"high", allowscriptaccess:"crossDomain"},  // object/embed attrs 
		params:    {id:'swfwriter',wmode: 'transparent', scale: "noborder", quality:"high", allowscriptaccess:"crossDomain"} // object params/embed attrs 
	});
};


