

//------------------------jquery.media.js-------------------------------------
/*
 * jQuery Media Plugin for converting elements into rich media content.
 *
 * Examples and documentation at: http://malsup.com/jquery/media/
 * Copyright (c) 2007-2008 M. Alsup
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * @author: M. Alsup
 * @version: 0.92 (24-SEP-2009)
 * @requires jQuery v1.1.2 or later
 * $Id: jquery.media.js 2460 2007-07-23 02:53:15Z malsup $
 *
 * Supported Media Players:
 *    - Flash
 *    - Quicktime
 *    - Real Player
 *    - Silverlight
 *    - Windows Media Player
 *    - iframe
 *
 * Supported Media Formats:
 *     Any types supported by the above players, such as:
 *     Video: asf, avi, flv, mov, mpg, mpeg, mp4, qt, smil, swf, wmv, 3g2, 3gp
 *     Audio: aif, aac, au, gsm, mid, midi, mov, mp3, m4a, snd, rm, wav, wma
 *     Other: bmp, html, pdf, psd, qif, qtif, qti, tif, tiff, xaml
 *
 * Thanks to Mark Hicken and Brent Pedersen for helping me debug this on the Mac!
 * Thanks to Dan Rossi for numerous bug reports and code bits!
 * Thanks to Skye Giordano for several great suggestions!
 * Thanks to Richard Connamacher for excellent improvements to the non-IE behavior!
 */
;(function($) {

/**
 * Chainable method for converting elements into rich media.
 *
 * @param options
 * @param callback fn invoked for each matched element before conversion
 * @param callback fn invoked for each matched element after conversion
 */
$.fn.media = function(options, f1, f2) {
    if (options == 'undo') {
        return this.each(function() {
            var $this = $(this);
            var html = $this.data('media.origHTML');
            if (html)
                $this.replaceWith(html);
        });
    }
    
    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.toLowerCase()) || [''];

        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);
            
            if (o.canUndo) {
                var $temp = $('<div></div>').append(this);
                $div.data('media.origHTML', $temp.html()); // store original markup
            }
            
            // 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 = {
    standards:  false,      // use object tags only (no embeds for non-IE browsers)
    canUndo:    true,       // tells plugin to store the original markup so it can be reverted via: $(sel).mediaUndo()
    width:        400,
    height:        400,
    autoplay:    0,               // normalized cross-player setting
    bgColor:    '#ffffff',     // background color
    params:        { wmode: 'transparent'},    // added to object element as param elements; added to embed element as attrs
    attrs:        {},            // added to object and embed elements as attrs
    flvKeyName: 'file',     // key used for object src param (thanks to Andrea Ercolino)
    flashvars:    {},            // added to flash content as flashvars param/attr
    flashVersion:    '7',    // required flash version
    expressInstaller: null,    // src for express installer

    // 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',
        title:         'Flash',
        types:         'flv,mp3,swf',
        mimetype:     'application/x-shockwave-flash',
        pluginspage: 'http://www.adobe.com/go/getflashplayer',
        ieAttrs: {
            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
        }
    },
    quicktime: {
        name:         'quicktime',
        title:         'QuickTime',
        mimetype:     'video/quicktime',
        pluginspage: 'http://www.apple.com/quicktime/download/',
        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',
        ieAttrs: {
            classid:  'clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B',
            codebase: 'http://www.apple.com/qtactivex/qtplugin.cab'
        }
    },
    realplayer: {
        name:          'real',
        title:          'RealPlayer',
        types:          'ra,ram,rm,rpm,rv,smi,smil',
        mimetype:      'audio/x-pn-realaudio-plugin',
        pluginspage:  'http://www.real.com/player/',
        autoplayAttr: 'autostart',
        ieAttrs: {
            classid: 'clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA'
        }
    },
    winmedia: {
        name:          'winmedia',
        title:          'Windows Media',
        types:          'asx,asf,avi,wma,wmv',
        mimetype:      $.browser.mozilla && isFirefoxWMPPluginInstalled() ? 'application/x-ms-wmp' : 'application/x-mplayer2',
        pluginspage:  'http://www.microsoft.com/Windows/MediaPlayer/',
        autoplayAttr: 'autostart',
        oUrl:          'url',
        ieAttrs: {
            classid:  'clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6',
            type:      'application/x-oleobject'
        }
    },
    // 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(/,/ig,'|') + ')\\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 = options;
    var c = meta;

    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 library if possible
$.fn.media.swf = function(el, opts) {
    if (!window.SWFObject && !window.swfobject) {
        // 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 + '>');

    // swfobject v2+
    if (window.swfobject) {
        $(el).after($div).appendTo($div);
        if (!el.id) el.id = 'movie_player_' + counter++;

        // replace el with swfobject content
        swfobject.embedSWF(opts.src, el.id, opts.width, opts.height, opts.flashVersion,
            opts.expressInstaller, opts.flashvars, opts.params, opts.attrs);
    }
    // swfobject < v2
    else {
        $(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;
    var key = opts.flvKeyName;
    src = encodeURIComponent(src);
    opts.src = player;
    opts.src = opts.src + '?'+key+'=' + (src);
    var srcObj = {};
    srcObj[key] = src;
    opts.flashvars = $.extend({}, srcObj, 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.ieAttrs || {}) {
            var v = o.ieAttrs[key];
            if (key == 'codebase' && window.location.protocol == 'https:')
                v = v.replace('http','https');
            a.push(key + '="'+v+'" ');
        }
        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 if (o.standards) {
        // Rewritten to be standards compliant by Richard Connamacher
        var a = ['<object type="' + o.mimetype +'" width="' + opts.width + '" height="' + opts.height +'"'];
        if (opts.src) a.push(' data="' + opts.src + '" ');
        a.push('>');
        a.push('<param name="' + (o.oUrl || 'src') +'" value="' + opts.src + '">');
        for (var key in opts.params) {
            if (key == 'wmode' && player != 'flash') // FF3/Quicktime borks on wmode
                continue;
            a.push('<param name="'+ key +'" value="' + opts.params[key] + '">');
        }
        // Alternate HTML
        a.push('<div><p><strong>'+o.title+' Required</strong></p><p>'+o.title+' is required to view this media. <a href="'+o.pluginspage+'">Download Here</a>.</p></div>');
        a.push('</ob'+'ject'+'>');
    }
     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) {
                if (key == 'wmode' && player != 'flash') // FF3/Quicktime borks on wmode
                    continue;
                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-ui-1.7.2.custom.min.js-----------------------
/*
 * jQuery UI 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI
 */
jQuery.ui||(function(c){var i=c.fn.remove,d=c.browser.mozilla&&(parseFloat(c.browser.version)<1.9);c.ui={version:"1.7.2",plugin:{add:function(k,l,n){var m=c.ui[k].prototype;for(var j in n){m.plugins[j]=m.plugins[j]||[];m.plugins[j].push([l,n[j]])}},call:function(j,l,k){var n=j.plugins[l];if(!n||!j.element[0].parentNode){return}for(var m=0;m<n.length;m++){if(j.options[n[m][0]]){n[m][1].apply(j.element,k)}}}},contains:function(k,j){return document.compareDocumentPosition?k.compareDocumentPosition(j)&16:k!==j&&k.contains(j)},hasScroll:function(m,k){if(c(m).css("overflow")=="hidden"){return false}var j=(k&&k=="left")?"scrollLeft":"scrollTop",l=false;if(m[j]>0){return true}m[j]=1;l=(m[j]>0);m[j]=0;return l},isOverAxis:function(k,j,l){return(k>j)&&(k<(j+l))},isOver:function(o,k,n,m,j,l){return c.ui.isOverAxis(o,n,j)&&c.ui.isOverAxis(k,m,l)},keyCode:{BACKSPACE:8,CAPS_LOCK:20,COMMA:188,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38}};if(d){var f=c.attr,e=c.fn.removeAttr,h="http://www.w3.org/2005/07/aaa",a=/^aria-/,b=/^wairole:/;c.attr=function(k,j,l){var m=l!==undefined;return(j=="role"?(m?f.call(this,k,j,"wairole:"+l):(f.apply(this,arguments)||"").replace(b,"")):(a.test(j)?(m?k.setAttributeNS(h,j.replace(a,"aaa:"),l):f.call(this,k,j.replace(a,"aaa:"))):f.apply(this,arguments)))};c.fn.removeAttr=function(j){return(a.test(j)?this.each(function(){this.removeAttributeNS(h,j.replace(a,""))}):e.call(this,j))}}c.fn.extend({remove:function(){c("*",this).add(this).each(function(){c(this).triggerHandler("remove")});return i.apply(this,arguments)},enableSelection:function(){return this.attr("unselectable","off").css("MozUserSelect","").unbind("selectstart.ui")},disableSelection:function(){return this.attr("unselectable","on").css("MozUserSelect","none").bind("selectstart.ui",function(){return false})},scrollParent:function(){var j;if((c.browser.msie&&(/(static|relative)/).test(this.css("position")))||(/absolute/).test(this.css("position"))){j=this.parents().filter(function(){return(/(relative|absolute|fixed)/).test(c.curCSS(this,"position",1))&&(/(auto|scroll)/).test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0)}else{j=this.parents().filter(function(){return(/(auto|scroll)/).test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0)}return(/fixed/).test(this.css("position"))||!j.length?c(document):j}});c.extend(c.expr[":"],{data:function(l,k,j){return !!c.data(l,j[3])},focusable:function(k){var l=k.nodeName.toLowerCase(),j=c.attr(k,"tabindex");return(/input|select|textarea|button|object/.test(l)?!k.disabled:"a"==l||"area"==l?k.href||!isNaN(j):!isNaN(j))&&!c(k)["area"==l?"parents":"closest"](":hidden").length},tabbable:function(k){var j=c.attr(k,"tabindex");return(isNaN(j)||j>=0)&&c(k).is(":focusable")}});function g(m,n,o,l){function k(q){var p=c[m][n][q]||[];return(typeof p=="string"?p.split(/,?\s+/):p)}var j=k("getter");if(l.length==1&&typeof l[0]=="string"){j=j.concat(k("getterSetter"))}return(c.inArray(o,j)!=-1)}c.widget=function(k,j){var l=k.split(".")[0];k=k.split(".")[1];c.fn[k]=function(p){var n=(typeof p=="string"),o=Array.prototype.slice.call(arguments,1);if(n&&p.substring(0,1)=="_"){return this}if(n&&g(l,k,p,o)){var m=c.data(this[0],k);return(m?m[p].apply(m,o):undefined)}return this.each(function(){var q=c.data(this,k);(!q&&!n&&c.data(this,k,new c[l][k](this,p))._init());(q&&n&&c.isFunction(q[p])&&q[p].apply(q,o))})};c[l]=c[l]||{};c[l][k]=function(o,n){var m=this;this.namespace=l;this.widgetName=k;this.widgetEventPrefix=c[l][k].eventPrefix||k;this.widgetBaseClass=l+"-"+k;this.options=c.extend({},c.widget.defaults,c[l][k].defaults,c.metadata&&c.metadata.get(o)[k],n);this.element=c(o).bind("setData."+k,function(q,p,r){if(q.target==o){return m._setData(p,r)}}).bind("getData."+k,function(q,p){if(q.target==o){return m._getData(p)}}).bind("remove",function(){return m.destroy()})};c[l][k].prototype=c.extend({},c.widget.prototype,j);c[l][k].getterSetter="option"};c.widget.prototype={_init:function(){},destroy:function(){this.element.removeData(this.widgetName).removeClass(this.widgetBaseClass+"-disabled "+this.namespace+"-state-disabled").removeAttr("aria-disabled")},option:function(l,m){var k=l,j=this;if(typeof l=="string"){if(m===undefined){return this._getData(l)}k={};k[l]=m}c.each(k,function(n,o){j._setData(n,o)})},_getData:function(j){return this.options[j]},_setData:function(j,k){this.options[j]=k;if(j=="disabled"){this.element[k?"addClass":"removeClass"](this.widgetBaseClass+"-disabled "+this.namespace+"-state-disabled").attr("aria-disabled",k)}},enable:function(){this._setData("disabled",false)},disable:function(){this._setData("disabled",true)},_trigger:function(l,m,n){var p=this.options[l],j=(l==this.widgetEventPrefix?l:this.widgetEventPrefix+l);m=c.Event(m);m.type=j;if(m.originalEvent){for(var k=c.event.props.length,o;k;){o=c.event.props[--k];m[o]=m.originalEvent[o]}}this.element.trigger(m,n);return !(c.isFunction(p)&&p.call(this.element[0],m,n)===false||m.isDefaultPrevented())}};c.widget.defaults={disabled:false};c.ui.mouse={_mouseInit:function(){var j=this;this.element.bind("mousedown."+this.widgetName,function(k){return j._mouseDown(k)}).bind("click."+this.widgetName,function(k){if(j._preventClickEvent){j._preventClickEvent=false;k.stopImmediatePropagation();return false}});if(c.browser.msie){this._mouseUnselectable=this.element.attr("unselectable");this.element.attr("unselectable","on")}this.started=false},_mouseDestroy:function(){this.element.unbind("."+this.widgetName);(c.browser.msie&&this.element.attr("unselectable",this._mouseUnselectable))},_mouseDown:function(l){l.originalEvent=l.originalEvent||{};if(l.originalEvent.mouseHandled){return}(this._mouseStarted&&this._mouseUp(l));this._mouseDownEvent=l;var k=this,m=(l.which==1),j=(typeof this.options.cancel=="string"?c(l.target).parents().add(l.target).filter(this.options.cancel).length:false);if(!m||j||!this._mouseCapture(l)){return true}this.mouseDelayMet=!this.options.delay;if(!this.mouseDelayMet){this._mouseDelayTimer=setTimeout(function(){k.mouseDelayMet=true},this.options.delay)}if(this._mouseDistanceMet(l)&&this._mouseDelayMet(l)){this._mouseStarted=(this._mouseStart(l)!==false);if(!this._mouseStarted){l.preventDefault();return true}}this._mouseMoveDelegate=function(n){return k._mouseMove(n)};this._mouseUpDelegate=function(n){return k._mouseUp(n)};c(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);(c.browser.safari||l.preventDefault());l.originalEvent.mouseHandled=true;return true},_mouseMove:function(j){if(c.browser.msie&&!j.button){return this._mouseUp(j)}if(this._mouseStarted){this._mouseDrag(j);return j.preventDefault()}if(this._mouseDistanceMet(j)&&this._mouseDelayMet(j)){this._mouseStarted=(this._mouseStart(this._mouseDownEvent,j)!==false);(this._mouseStarted?this._mouseDrag(j):this._mouseUp(j))}return !this._mouseStarted},_mouseUp:function(j){c(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=false;this._preventClickEvent=(j.target==this._mouseDownEvent.target);this._mouseStop(j)}return false},_mouseDistanceMet:function(j){return(Math.max(Math.abs(this._mouseDownEvent.pageX-j.pageX),Math.abs(this._mouseDownEvent.pageY-j.pageY))>=this.options.distance)},_mouseDelayMet:function(j){return this.mouseDelayMet},_mouseStart:function(j){},_mouseDrag:function(j){},_mouseStop:function(j){},_mouseCapture:function(j){return true}};c.ui.mouse.defaults={cancel:null,distance:1,delay:0}})(jQuery);;/*
 * jQuery UI Draggable 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Draggables
 *
 * Depends:
 *    ui.core.js
 */
(function(a){a.widget("ui.draggable",a.extend({},a.ui.mouse,{_init:function(){if(this.options.helper=="original"&&!(/^(?:r|a|f)/).test(this.element.css("position"))){this.element[0].style.position="relative"}(this.options.addClasses&&this.element.addClass("ui-draggable"));(this.options.disabled&&this.element.addClass("ui-draggable-disabled"));this._mouseInit()},destroy:function(){if(!this.element.data("draggable")){return}this.element.removeData("draggable").unbind(".draggable").removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled");this._mouseDestroy()},_mouseCapture:function(b){var c=this.options;if(this.helper||c.disabled||a(b.target).is(".ui-resizable-handle")){return false}this.handle=this._getHandle(b);if(!this.handle){return false}return true},_mouseStart:function(b){var c=this.options;this.helper=this._createHelper(b);this._cacheHelperProportions();if(a.ui.ddmanager){a.ui.ddmanager.current=this}this._cacheMargins();this.cssPosition=this.helper.css("position");this.scrollParent=this.helper.scrollParent();this.offset=this.element.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};a.extend(this.offset,{click:{left:b.pageX-this.offset.left,top:b.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.originalPosition=this._generatePosition(b);this.originalPageX=b.pageX;this.originalPageY=b.pageY;if(c.cursorAt){this._adjustOffsetFromHelper(c.cursorAt)}if(c.containment){this._setContainment()}this._trigger("start",b);this._cacheHelperProportions();if(a.ui.ddmanager&&!c.dropBehaviour){a.ui.ddmanager.prepareOffsets(this,b)}this.helper.addClass("ui-draggable-dragging");this._mouseDrag(b,true);return true},_mouseDrag:function(b,d){this.position=this._generatePosition(b);this.positionAbs=this._convertPositionTo("absolute");if(!d){var c=this._uiHash();this._trigger("drag",b,c);this.position=c.position}if(!this.options.axis||this.options.axis!="y"){this.helper[0].style.left=this.position.left+"px"}if(!this.options.axis||this.options.axis!="x"){this.helper[0].style.top=this.position.top+"px"}if(a.ui.ddmanager){a.ui.ddmanager.drag(this,b)}return false},_mouseStop:function(c){var d=false;if(a.ui.ddmanager&&!this.options.dropBehaviour){d=a.ui.ddmanager.drop(this,c)}if(this.dropped){d=this.dropped;this.dropped=false}if((this.options.revert=="invalid"&&!d)||(this.options.revert=="valid"&&d)||this.options.revert===true||(a.isFunction(this.options.revert)&&this.options.revert.call(this.element,d))){var b=this;a(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){b._trigger("stop",c);b._clear()})}else{this._trigger("stop",c);this._clear()}return false},_getHandle:function(b){var c=!this.options.handle||!a(this.options.handle,this.element).length?true:false;a(this.options.handle,this.element).find("*").andSelf().each(function(){if(this==b.target){c=true}});return c},_createHelper:function(c){var d=this.options;var b=a.isFunction(d.helper)?a(d.helper.apply(this.element[0],[c])):(d.helper=="clone"?this.element.clone():this.element);if(!b.parents("body").length){b.appendTo((d.appendTo=="parent"?this.element[0].parentNode:d.appendTo))}if(b[0]!=this.element[0]&&!(/(fixed|absolute)/).test(b.css("position"))){b.css("position","absolute")}return b},_adjustOffsetFromHelper:function(b){if(b.left!=undefined){this.offset.click.left=b.left+this.margins.left}if(b.right!=undefined){this.offset.click.left=this.helperProportions.width-b.right+this.margins.left}if(b.top!=undefined){this.offset.click.top=b.top+this.margins.top}if(b.bottom!=undefined){this.offset.click.top=this.helperProportions.height-b.bottom+this.margins.top}},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var b=this.offsetParent.offset();if(this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])){b.left+=this.scrollParent.scrollLeft();b.top+=this.scrollParent.scrollTop()}if((this.offsetParent[0]==document.body)||(this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&a.browser.msie)){b={top:0,left:0}}return{top:b.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:b.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var b=this.element.position();return{top:b.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:b.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}else{return{top:0,left:0}}},_cacheMargins:function(){this.margins={left:(parseInt(this.element.css("marginLeft"),10)||0),top:(parseInt(this.element.css("marginTop"),10)||0)}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e=this.options;if(e.containment=="parent"){e.containment=this.helper[0].parentNode}if(e.containment=="document"||e.containment=="window"){this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,a(e.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(a(e.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]}if(!(/^(document|window|parent)$/).test(e.containment)&&e.containment.constructor!=Array){var c=a(e.containment)[0];if(!c){return}var d=a(e.containment).offset();var b=(a(c).css("overflow")!="hidden");this.containment=[d.left+(parseInt(a(c).css("borderLeftWidth"),10)||0)+(parseInt(a(c).css("paddingLeft"),10)||0)-this.margins.left,d.top+(parseInt(a(c).css("borderTopWidth"),10)||0)+(parseInt(a(c).css("paddingTop"),10)||0)-this.margins.top,d.left+(b?Math.max(c.scrollWidth,c.offsetWidth):c.offsetWidth)-(parseInt(a(c).css("borderLeftWidth"),10)||0)-(parseInt(a(c).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,d.top+(b?Math.max(c.scrollHeight,c.offsetHeight):c.offsetHeight)-(parseInt(a(c).css("borderTopWidth"),10)||0)-(parseInt(a(c).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}else{if(e.containment.constructor==Array){this.containment=e.containment}}},_convertPositionTo:function(f,h){if(!h){h=this.position}var c=f=="absolute"?1:-1;var e=this.options,b=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,g=(/(html|body)/i).test(b[0].tagName);return{top:(h.top+this.offset.relative.top*c+this.offset.parent.top*c-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(g?0:b.scrollTop()))*c)),left:(h.left+this.offset.relative.left*c+this.offset.parent.left*c-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():g?0:b.scrollLeft())*c))}},_generatePosition:function(e){var h=this.options,b=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,i=(/(html|body)/i).test(b[0].tagName);if(this.cssPosition=="relative"&&!(this.scrollParent[0]!=document&&this.scrollParent[0]!=this.offsetParent[0])){this.offset.relative=this._getRelativeOffset()}var d=e.pageX;var c=e.pageY;if(this.originalPosition){if(this.containment){if(e.pageX-this.offset.click.left<this.containment[0]){d=this.containment[0]+this.offset.click.left}if(e.pageY-this.offset.click.top<this.containment[1]){c=this.containment[1]+this.offset.click.top}if(e.pageX-this.offset.click.left>this.containment[2]){d=this.containment[2]+this.offset.click.left}if(e.pageY-this.offset.click.top>this.containment[3]){c=this.containment[3]+this.offset.click.top}}if(h.grid){var g=this.originalPageY+Math.round((c-this.originalPageY)/h.grid[1])*h.grid[1];c=this.containment?(!(g-this.offset.click.top<this.containment[1]||g-this.offset.click.top>this.containment[3])?g:(!(g-this.offset.click.top<this.containment[1])?g-h.grid[1]:g+h.grid[1])):g;var f=this.originalPageX+Math.round((d-this.originalPageX)/h.grid[0])*h.grid[0];d=this.containment?(!(f-this.offset.click.left<this.containment[0]||f-this.offset.click.left>this.containment[2])?f:(!(f-this.offset.click.left<this.containment[0])?f-h.grid[0]:f+h.grid[0])):f}}return{top:(c-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(i?0:b.scrollTop())))),left:(d-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():i?0:b.scrollLeft())))}},_clear:function(){this.helper.removeClass("ui-draggable-dragging");if(this.helper[0]!=this.element[0]&&!this.cancelHelperRemoval){this.helper.remove()}this.helper=null;this.cancelHelperRemoval=false},_trigger:function(b,c,d){d=d||this._uiHash();a.ui.plugin.call(this,b,[c,d]);if(b=="drag"){this.positionAbs=this._convertPositionTo("absolute")}return a.widget.prototype._trigger.call(this,b,c,d)},plugins:{},_uiHash:function(b){return{helper:this.helper,position:this.position,absolutePosition:this.positionAbs,offset:this.positionAbs}}}));a.extend(a.ui.draggable,{version:"1.7.2",eventPrefix:"drag",defaults:{addClasses:true,appendTo:"parent",axis:false,cancel:":input,option",connectToSortable:false,containment:false,cursor:"auto",cursorAt:false,delay:0,distance:1,grid:false,handle:false,helper:"original",iframeFix:false,opacity:false,refreshPositions:false,revert:false,revertDuration:500,scope:"default",scroll:true,scrollSensitivity:20,scrollSpeed:20,snap:false,snapMode:"both",snapTolerance:20,stack:false,zIndex:false}});a.ui.plugin.add("draggable","connectToSortable",{start:function(c,e){var d=a(this).data("draggable"),f=d.options,b=a.extend({},e,{item:d.element});d.sortables=[];a(f.connectToSortable).each(function(){var g=a.data(this,"sortable");if(g&&!g.options.disabled){d.sortables.push({instance:g,shouldRevert:g.options.revert});g._refreshItems();g._trigger("activate",c,b)}})},stop:function(c,e){var d=a(this).data("draggable"),b=a.extend({},e,{item:d.element});a.each(d.sortables,function(){if(this.instance.isOver){this.instance.isOver=0;d.cancelHelperRemoval=true;this.instance.cancelHelperRemoval=false;if(this.shouldRevert){this.instance.options.revert=true}this.instance._mouseStop(c);this.instance.options.helper=this.instance.options._helper;if(d.options.helper=="original"){this.instance.currentItem.css({top:"auto",left:"auto"})}}else{this.instance.cancelHelperRemoval=false;this.instance._trigger("deactivate",c,b)}})},drag:function(c,f){var e=a(this).data("draggable"),b=this;var d=function(i){var n=this.offset.click.top,m=this.offset.click.left;var g=this.positionAbs.top,k=this.positionAbs.left;var j=i.height,l=i.width;var p=i.top,h=i.left;return a.ui.isOver(g+n,k+m,p,h,j,l)};a.each(e.sortables,function(g){this.instance.positionAbs=e.positionAbs;this.instance.helperProportions=e.helperProportions;this.instance.offset.click=e.offset.click;if(this.instance._intersectsWith(this.instance.containerCache)){if(!this.instance.isOver){this.instance.isOver=1;this.instance.currentItem=a(b).clone().appendTo(this.instance.element).data("sortable-item",true);this.instance.options._helper=this.instance.options.helper;this.instance.options.helper=function(){return f.helper[0]};c.target=this.instance.currentItem[0];this.instance._mouseCapture(c,true);this.instance._mouseStart(c,true,true);this.instance.offset.click.top=e.offset.click.top;this.instance.offset.click.left=e.offset.click.left;this.instance.offset.parent.left-=e.offset.parent.left-this.instance.offset.parent.left;this.instance.offset.parent.top-=e.offset.parent.top-this.instance.offset.parent.top;e._trigger("toSortable",c);e.dropped=this.instance.element;e.currentItem=e.element;this.instance.fromOutside=e}if(this.instance.currentItem){this.instance._mouseDrag(c)}}else{if(this.instance.isOver){this.instance.isOver=0;this.instance.cancelHelperRemoval=true;this.instance.options.revert=false;this.instance._trigger("out",c,this.instance._uiHash(this.instance));this.instance._mouseStop(c,true);this.instance.options.helper=this.instance.options._helper;this.instance.currentItem.remove();if(this.instance.placeholder){this.instance.placeholder.remove()}e._trigger("fromSortable",c);e.dropped=false}}})}});a.ui.plugin.add("draggable","cursor",{start:function(c,d){var b=a("body"),e=a(this).data("draggable").options;if(b.css("cursor")){e._cursor=b.css("cursor")}b.css("cursor",e.cursor)},stop:function(b,c){var d=a(this).data("draggable").options;if(d._cursor){a("body").css("cursor",d._cursor)}}});a.ui.plugin.add("draggable","iframeFix",{start:function(b,c){var d=a(this).data("draggable").options;a(d.iframeFix===true?"iframe":d.iframeFix).each(function(){a('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>').css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1000}).css(a(this).offset()).appendTo("body")})},stop:function(b,c){a("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)})}});a.ui.plugin.add("draggable","opacity",{start:function(c,d){var b=a(d.helper),e=a(this).data("draggable").options;if(b.css("opacity")){e._opacity=b.css("opacity")}b.css("opacity",e.opacity)},stop:function(b,c){var d=a(this).data("draggable").options;if(d._opacity){a(c.helper).css("opacity",d._opacity)}}});a.ui.plugin.add("draggable","scroll",{start:function(c,d){var b=a(this).data("draggable");if(b.scrollParent[0]!=document&&b.scrollParent[0].tagName!="HTML"){b.overflowOffset=b.scrollParent.offset()}},drag:function(d,e){var c=a(this).data("draggable"),f=c.options,b=false;if(c.scrollParent[0]!=document&&c.scrollParent[0].tagName!="HTML"){if(!f.axis||f.axis!="x"){if((c.overflowOffset.top+c.scrollParent[0].offsetHeight)-d.pageY<f.scrollSensitivity){c.scrollParent[0].scrollTop=b=c.scrollParent[0].scrollTop+f.scrollSpeed}else{if(d.pageY-c.overflowOffset.top<f.scrollSensitivity){c.scrollParent[0].scrollTop=b=c.scrollParent[0].scrollTop-f.scrollSpeed}}}if(!f.axis||f.axis!="y"){if((c.overflowOffset.left+c.scrollParent[0].offsetWidth)-d.pageX<f.scrollSensitivity){c.scrollParent[0].scrollLeft=b=c.scrollParent[0].scrollLeft+f.scrollSpeed}else{if(d.pageX-c.overflowOffset.left<f.scrollSensitivity){c.scrollParent[0].scrollLeft=b=c.scrollParent[0].scrollLeft-f.scrollSpeed}}}}else{if(!f.axis||f.axis!="x"){if(d.pageY-a(document).scrollTop()<f.scrollSensitivity){b=a(document).scrollTop(a(document).scrollTop()-f.scrollSpeed)}else{if(a(window).height()-(d.pageY-a(document).scrollTop())<f.scrollSensitivity){b=a(document).scrollTop(a(document).scrollTop()+f.scrollSpeed)}}}if(!f.axis||f.axis!="y"){if(d.pageX-a(document).scrollLeft()<f.scrollSensitivity){b=a(document).scrollLeft(a(document).scrollLeft()-f.scrollSpeed)}else{if(a(window).width()-(d.pageX-a(document).scrollLeft())<f.scrollSensitivity){b=a(document).scrollLeft(a(document).scrollLeft()+f.scrollSpeed)}}}}if(b!==false&&a.ui.ddmanager&&!f.dropBehaviour){a.ui.ddmanager.prepareOffsets(c,d)}}});a.ui.plugin.add("draggable","snap",{start:function(c,d){var b=a(this).data("draggable"),e=b.options;b.snapElements=[];a(e.snap.constructor!=String?(e.snap.items||":data(draggable)"):e.snap).each(function(){var g=a(this);var f=g.offset();if(this!=b.element[0]){b.snapElements.push({item:this,width:g.outerWidth(),height:g.outerHeight(),top:f.top,left:f.left})}})},drag:function(u,p){var g=a(this).data("draggable"),q=g.options;var y=q.snapTolerance;var x=p.offset.left,w=x+g.helperProportions.width,f=p.offset.top,e=f+g.helperProportions.height;for(var v=g.snapElements.length-1;v>=0;v--){var s=g.snapElements[v].left,n=s+g.snapElements[v].width,m=g.snapElements[v].top,A=m+g.snapElements[v].height;if(!((s-y<x&&x<n+y&&m-y<f&&f<A+y)||(s-y<x&&x<n+y&&m-y<e&&e<A+y)||(s-y<w&&w<n+y&&m-y<f&&f<A+y)||(s-y<w&&w<n+y&&m-y<e&&e<A+y))){if(g.snapElements[v].snapping){(g.options.snap.release&&g.options.snap.release.call(g.element,u,a.extend(g._uiHash(),{snapItem:g.snapElements[v].item})))}g.snapElements[v].snapping=false;continue}if(q.snapMode!="inner"){var c=Math.abs(m-e)<=y;var z=Math.abs(A-f)<=y;var j=Math.abs(s-w)<=y;var k=Math.abs(n-x)<=y;if(c){p.position.top=g._convertPositionTo("relative",{top:m-g.helperProportions.height,left:0}).top-g.margins.top}if(z){p.position.top=g._convertPositionTo("relative",{top:A,left:0}).top-g.margins.top}if(j){p.position.left=g._convertPositionTo("relative",{top:0,left:s-g.helperProportions.width}).left-g.margins.left}if(k){p.position.left=g._convertPositionTo("relative",{top:0,left:n}).left-g.margins.left}}var h=(c||z||j||k);if(q.snapMode!="outer"){var c=Math.abs(m-f)<=y;var z=Math.abs(A-e)<=y;var j=Math.abs(s-x)<=y;var k=Math.abs(n-w)<=y;if(c){p.position.top=g._convertPositionTo("relative",{top:m,left:0}).top-g.margins.top}if(z){p.position.top=g._convertPositionTo("relative",{top:A-g.helperProportions.height,left:0}).top-g.margins.top}if(j){p.position.left=g._convertPositionTo("relative",{top:0,left:s}).left-g.margins.left}if(k){p.position.left=g._convertPositionTo("relative",{top:0,left:n-g.helperProportions.width}).left-g.margins.left}}if(!g.snapElements[v].snapping&&(c||z||j||k||h)){(g.options.snap.snap&&g.options.snap.snap.call(g.element,u,a.extend(g._uiHash(),{snapItem:g.snapElements[v].item})))}g.snapElements[v].snapping=(c||z||j||k||h)}}});a.ui.plugin.add("draggable","stack",{start:function(b,c){var e=a(this).data("draggable").options;var d=a.makeArray(a(e.stack.group)).sort(function(g,f){return(parseInt(a(g).css("zIndex"),10)||e.stack.min)-(parseInt(a(f).css("zIndex"),10)||e.stack.min)});a(d).each(function(f){this.style.zIndex=e.stack.min+f});this[0].style.zIndex=e.stack.min+d.length}});a.ui.plugin.add("draggable","zIndex",{start:function(c,d){var b=a(d.helper),e=a(this).data("draggable").options;if(b.css("zIndex")){e._zIndex=b.css("zIndex")}b.css("zIndex",e.zIndex)},stop:function(b,c){var d=a(this).data("draggable").options;if(d._zIndex){a(c.helper).css("zIndex",d._zIndex)}}})})(jQuery);;/*
 * jQuery UI Droppable 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Droppables
 *
 * Depends:
 *    ui.core.js
 *    ui.draggable.js
 */
(function(a){a.widget("ui.droppable",{_init:function(){var c=this.options,b=c.accept;this.isover=0;this.isout=1;this.options.accept=this.options.accept&&a.isFunction(this.options.accept)?this.options.accept:function(e){return e.is(b)};this.proportions={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight};a.ui.ddmanager.droppables[this.options.scope]=a.ui.ddmanager.droppables[this.options.scope]||[];a.ui.ddmanager.droppables[this.options.scope].push(this);(this.options.addClasses&&this.element.addClass("ui-droppable"))},destroy:function(){var b=a.ui.ddmanager.droppables[this.options.scope];for(var c=0;c<b.length;c++){if(b[c]==this){b.splice(c,1)}}this.element.removeClass("ui-droppable ui-droppable-disabled").removeData("droppable").unbind(".droppable")},_setData:function(b,c){if(b=="accept"){this.options.accept=c&&a.isFunction(c)?c:function(e){return e.is(c)}}else{a.widget.prototype._setData.apply(this,arguments)}},_activate:function(c){var b=a.ui.ddmanager.current;if(this.options.activeClass){this.element.addClass(this.options.activeClass)}(b&&this._trigger("activate",c,this.ui(b)))},_deactivate:function(c){var b=a.ui.ddmanager.current;if(this.options.activeClass){this.element.removeClass(this.options.activeClass)}(b&&this._trigger("deactivate",c,this.ui(b)))},_over:function(c){var b=a.ui.ddmanager.current;if(!b||(b.currentItem||b.element)[0]==this.element[0]){return}if(this.options.accept.call(this.element[0],(b.currentItem||b.element))){if(this.options.hoverClass){this.element.addClass(this.options.hoverClass)}this._trigger("over",c,this.ui(b))}},_out:function(c){var b=a.ui.ddmanager.current;if(!b||(b.currentItem||b.element)[0]==this.element[0]){return}if(this.options.accept.call(this.element[0],(b.currentItem||b.element))){if(this.options.hoverClass){this.element.removeClass(this.options.hoverClass)}this._trigger("out",c,this.ui(b))}},_drop:function(c,d){var b=d||a.ui.ddmanager.current;if(!b||(b.currentItem||b.element)[0]==this.element[0]){return false}var e=false;this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function(){var f=a.data(this,"droppable");if(f.options.greedy&&a.ui.intersect(b,a.extend(f,{offset:f.element.offset()}),f.options.tolerance)){e=true;return false}});if(e){return false}if(this.options.accept.call(this.element[0],(b.currentItem||b.element))){if(this.options.activeClass){this.element.removeClass(this.options.activeClass)}if(this.options.hoverClass){this.element.removeClass(this.options.hoverClass)}this._trigger("drop",c,this.ui(b));return this.element}return false},ui:function(b){return{draggable:(b.currentItem||b.element),helper:b.helper,position:b.position,absolutePosition:b.positionAbs,offset:b.positionAbs}}});a.extend(a.ui.droppable,{version:"1.7.2",eventPrefix:"drop",defaults:{accept:"*",activeClass:false,addClasses:true,greedy:false,hoverClass:false,scope:"default",tolerance:"intersect"}});a.ui.intersect=function(q,j,o){if(!j.offset){return false}var e=(q.positionAbs||q.position.absolute).left,d=e+q.helperProportions.width,n=(q.positionAbs||q.position.absolute).top,m=n+q.helperProportions.height;var g=j.offset.left,c=g+j.proportions.width,p=j.offset.top,k=p+j.proportions.height;switch(o){case"fit":return(g<e&&d<c&&p<n&&m<k);break;case"intersect":return(g<e+(q.helperProportions.width/2)&&d-(q.helperProportions.width/2)<c&&p<n+(q.helperProportions.height/2)&&m-(q.helperProportions.height/2)<k);break;case"pointer":var h=((q.positionAbs||q.position.absolute).left+(q.clickOffset||q.offset.click).left),i=((q.positionAbs||q.position.absolute).top+(q.clickOffset||q.offset.click).top),f=a.ui.isOver(i,h,p,g,j.proportions.height,j.proportions.width);return f;break;case"touch":return((n>=p&&n<=k)||(m>=p&&m<=k)||(n<p&&m>k))&&((e>=g&&e<=c)||(d>=g&&d<=c)||(e<g&&d>c));break;default:return false;break}};a.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(e,g){var b=a.ui.ddmanager.droppables[e.options.scope];var f=g?g.type:null;var h=(e.currentItem||e.element).find(":data(droppable)").andSelf();droppablesLoop:for(var d=0;d<b.length;d++){if(b[d].options.disabled||(e&&!b[d].options.accept.call(b[d].element[0],(e.currentItem||e.element)))){continue}for(var c=0;c<h.length;c++){if(h[c]==b[d].element[0]){b[d].proportions.height=0;continue droppablesLoop}}b[d].visible=b[d].element.css("display")!="none";if(!b[d].visible){continue}b[d].offset=b[d].element.offset();b[d].proportions={width:b[d].element[0].offsetWidth,height:b[d].element[0].offsetHeight};if(f=="mousedown"){b[d]._activate.call(b[d],g)}}},drop:function(b,c){var d=false;a.each(a.ui.ddmanager.droppables[b.options.scope],function(){if(!this.options){return}if(!this.options.disabled&&this.visible&&a.ui.intersect(b,this,this.options.tolerance)){d=this._drop.call(this,c)}if(!this.options.disabled&&this.visible&&this.options.accept.call(this.element[0],(b.currentItem||b.element))){this.isout=1;this.isover=0;this._deactivate.call(this,c)}});return d},drag:function(b,c){if(b.options.refreshPositions){a.ui.ddmanager.prepareOffsets(b,c)}a.each(a.ui.ddmanager.droppables[b.options.scope],function(){if(this.options.disabled||this.greedyChild||!this.visible){return}var e=a.ui.intersect(b,this,this.options.tolerance);var g=!e&&this.isover==1?"isout":(e&&this.isover==0?"isover":null);if(!g){return}var f;if(this.options.greedy){var d=this.element.parents(":data(droppable):eq(0)");if(d.length){f=a.data(d[0],"droppable");f.greedyChild=(g=="isover"?1:0)}}if(f&&g=="isover"){f.isover=0;f.isout=1;f._out.call(f,c)}this[g]=1;this[g=="isout"?"isover":"isout"]=0;this[g=="isover"?"_over":"_out"].call(this,c);if(f&&g=="isout"){f.isout=0;f.isover=1;f._over.call(f,c)}})}}})(jQuery);;
//------------------------jquery-ui-dialog.js---------------------------------
/* jQuery UI Resizable 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Resizables
 *
 * Depends:
 *    ui.core.js
 */
(function(c){c.widget("ui.resizable",c.extend({},c.ui.mouse,{_init:function(){var e=this,j=this.options;this.element.addClass("ui-resizable");c.extend(this,{_aspectRatio:!!(j.aspectRatio),aspectRatio:j.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:j.helper||j.ghost||j.animate?j.helper||"ui-resizable-helper":null});if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)){if(/relative/.test(this.element.css("position"))&&c.browser.opera){this.element.css({position:"relative",top:"auto",left:"auto"})}this.element.wrap(c('<div class="ui-wrapper" style="overflow: hidden;"></div>').css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")}));this.element=this.element.parent().data("resizable",this.element.data("resizable"));this.elementIsWrapper=true;this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")});this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0});this.originalResizeStyle=this.originalElement.css("resize");this.originalElement.css("resize","none");this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"}));this.originalElement.css({margin:this.originalElement.css("margin")});this._proportionallyResize()}this.handles=j.handles||(!c(".ui-resizable-handle",this.element).length?"e,s,se":{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"});if(this.handles.constructor==String){if(this.handles=="all"){this.handles="n,e,s,w,se,sw,ne,nw"}var k=this.handles.split(",");this.handles={};for(var f=0;f<k.length;f++){var h=c.trim(k[f]),d="ui-resizable-"+h;var g=c('<div class="ui-resizable-handle '+d+'"></div>');if(/sw|se|ne|nw/.test(h)){g.css({zIndex:++j.zIndex})}if("se"==h){g.addClass("ui-icon ui-icon-gripsmall-diagonal-se")}this.handles[h]=".ui-resizable-"+h;this.element.append(g)}}this._renderAxis=function(p){p=p||this.element;for(var m in this.handles){if(this.handles[m].constructor==String){this.handles[m]=c(this.handles[m],this.element).show()}if(this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)){var n=c(this.handles[m],this.element),o=0;o=/sw|ne|nw|se|n|s/.test(m)?n.outerHeight():n.outerWidth();var l=["padding",/ne|nw|n/.test(m)?"Top":/se|sw|s/.test(m)?"Bottom":/^e$/.test(m)?"Right":"Left"].join("");p.css(l,o);this._proportionallyResize()}if(!c(this.handles[m]).length){continue}}};this._renderAxis(this.element);this._handles=c(".ui-resizable-handle",this.element).disableSelection();this._handles.mouseover(function(){if(!e.resizing){if(this.className){var i=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)}e.axis=i&&i[1]?i[1]:"se"}});if(j.autoHide){this._handles.hide();c(this.element).addClass("ui-resizable-autohide").hover(function(){c(this).removeClass("ui-resizable-autohide");e._handles.show()},function(){if(!e.resizing){c(this).addClass("ui-resizable-autohide");e._handles.hide()}})}this._mouseInit()},destroy:function(){this._mouseDestroy();var d=function(f){c(f).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};if(this.elementIsWrapper){d(this.element);var e=this.element;e.parent().append(this.originalElement.css({position:e.css("position"),width:e.outerWidth(),height:e.outerHeight(),top:e.css("top"),left:e.css("left")})).end().remove()}this.originalElement.css("resize",this.originalResizeStyle);d(this.originalElement)},_mouseCapture:function(e){var f=false;for(var d in this.handles){if(c(this.handles[d])[0]==e.target){f=true}}return this.options.disabled||!!f},_mouseStart:function(f){var i=this.options,e=this.element.position(),d=this.element;this.resizing=true;this.documentScroll={top:c(document).scrollTop(),left:c(document).scrollLeft()};if(d.is(".ui-draggable")||(/absolute/).test(d.css("position"))){d.css({position:"absolute",top:e.top,left:e.left})}if(c.browser.opera&&(/relative/).test(d.css("position"))){d.css({position:"relative",top:"auto",left:"auto"})}this._renderProxy();var j=b(this.helper.css("left")),g=b(this.helper.css("top"));if(i.containment){j+=c(i.containment).scrollLeft()||0;g+=c(i.containment).scrollTop()||0}this.offset=this.helper.offset();this.position={left:j,top:g};this.size=this._helper?{width:d.outerWidth(),height:d.outerHeight()}:{width:d.width(),height:d.height()};this.originalSize=this._helper?{width:d.outerWidth(),height:d.outerHeight()}:{width:d.width(),height:d.height()};this.originalPosition={left:j,top:g};this.sizeDiff={width:d.outerWidth()-d.width(),height:d.outerHeight()-d.height()};this.originalMousePosition={left:f.pageX,top:f.pageY};this.aspectRatio=(typeof i.aspectRatio=="number")?i.aspectRatio:((this.originalSize.width/this.originalSize.height)||1);var h=c(".ui-resizable-"+this.axis).css("cursor");c("body").css("cursor",h=="auto"?this.axis+"-resize":h);d.addClass("ui-resizable-resizing");this._propagate("start",f);return true},_mouseDrag:function(d){var g=this.helper,f=this.options,l={},p=this,i=this.originalMousePosition,m=this.axis;var q=(d.pageX-i.left)||0,n=(d.pageY-i.top)||0;var h=this._change[m];if(!h){return false}var k=h.apply(this,[d,q,n]),j=c.browser.msie&&c.browser.version<7,e=this.sizeDiff;if(this._aspectRatio||d.shiftKey){k=this._updateRatio(k,d)}k=this._respectSize(k,d);this._propagate("resize",d);g.css({top:this.position.top+"px",left:this.position.left+"px",width:this.size.width+"px",height:this.size.height+"px"});if(!this._helper&&this._proportionallyResizeElements.length){this._proportionallyResize()}this._updateCache(k);this._trigger("resize",d,this.ui());return false},_mouseStop:function(g){this.resizing=false;var h=this.options,l=this;if(this._helper){var f=this._proportionallyResizeElements,d=f.length&&(/textarea/i).test(f[0].nodeName),e=d&&c.ui.hasScroll(f[0],"left")?0:l.sizeDiff.height,j=d?0:l.sizeDiff.width;var m={width:(l.size.width-j),height:(l.size.height-e)},i=(parseInt(l.element.css("left"),10)+(l.position.left-l.originalPosition.left))||null,k=(parseInt(l.element.css("top"),10)+(l.position.top-l.originalPosition.top))||null;if(!h.animate){this.element.css(c.extend(m,{top:k,left:i}))}l.helper.height(l.size.height);l.helper.width(l.size.width);if(this._helper&&!h.animate){this._proportionallyResize()}}c("body").css("cursor","auto");this.element.removeClass("ui-resizable-resizing");this._propagate("stop",g);if(this._helper){this.helper.remove()}return false},_updateCache:function(d){var e=this.options;this.offset=this.helper.offset();if(a(d.left)){this.position.left=d.left}if(a(d.top)){this.position.top=d.top}if(a(d.height)){this.size.height=d.height}if(a(d.width)){this.size.width=d.width}},_updateRatio:function(g,f){var h=this.options,i=this.position,e=this.size,d=this.axis;if(g.height){g.width=(e.height*this.aspectRatio)}else{if(g.width){g.height=(e.width/this.aspectRatio)}}if(d=="sw"){g.left=i.left+(e.width-g.width);g.top=null}if(d=="nw"){g.top=i.top+(e.height-g.height);g.left=i.left+(e.width-g.width)}return g},_respectSize:function(k,f){var i=this.helper,h=this.options,q=this._aspectRatio||f.shiftKey,p=this.axis,s=a(k.width)&&h.maxWidth&&(h.maxWidth<k.width),l=a(k.height)&&h.maxHeight&&(h.maxHeight<k.height),g=a(k.width)&&h.minWidth&&(h.minWidth>k.width),r=a(k.height)&&h.minHeight&&(h.minHeight>k.height);if(g){k.width=h.minWidth}if(r){k.height=h.minHeight}if(s){k.width=h.maxWidth}if(l){k.height=h.maxHeight}var e=this.originalPosition.left+this.originalSize.width,n=this.position.top+this.size.height;var j=/sw|nw|w/.test(p),d=/nw|ne|n/.test(p);if(g&&j){k.left=e-h.minWidth}if(s&&j){k.left=e-h.maxWidth}if(r&&d){k.top=n-h.minHeight}if(l&&d){k.top=n-h.maxHeight}var m=!k.width&&!k.height;if(m&&!k.left&&k.top){k.top=null}else{if(m&&!k.top&&k.left){k.left=null}}return k},_proportionallyResize:function(){var j=this.options;if(!this._proportionallyResizeElements.length){return}var f=this.helper||this.element;for(var e=0;e<this._proportionallyResizeElements.length;e++){var g=this._proportionallyResizeElements[e];if(!this.borderDif){var d=[g.css("borderTopWidth"),g.css("borderRightWidth"),g.css("borderBottomWidth"),g.css("borderLeftWidth")],h=[g.css("paddingTop"),g.css("paddingRight"),g.css("paddingBottom"),g.css("paddingLeft")];this.borderDif=c.map(d,function(k,m){var l=parseInt(k,10)||0,n=parseInt(h[m],10)||0;return l+n})}if(c.browser.msie&&!(!(c(f).is(":hidden")||c(f).parents(":hidden").length))){continue}g.css({height:(f.height()-this.borderDif[0]-this.borderDif[2])||0,width:(f.width()-this.borderDif[1]-this.borderDif[3])||0})}},_renderProxy:function(){var e=this.element,h=this.options;this.elementOffset=e.offset();if(this._helper){this.helper=this.helper||c('<div style="overflow:hidden;"></div>');var d=c.browser.msie&&c.browser.version<7,f=(d?1:0),g=(d?2:-1);this.helper.addClass(this._helper).css({width:this.element.outerWidth()+g,height:this.element.outerHeight()+g,position:"absolute",left:this.elementOffset.left-f+"px",top:this.elementOffset.top-f+"px",zIndex:++h.zIndex});this.helper.appendTo("body").disableSelection()}else{this.helper=this.element}},_change:{e:function(f,e,d){return{width:this.originalSize.width+e}},w:function(g,e,d){var i=this.options,f=this.originalSize,h=this.originalPosition;return{left:h.left+e,width:f.width-e}},n:function(g,e,d){var i=this.options,f=this.originalSize,h=this.originalPosition;return{top:h.top+d,height:f.height-d}},s:function(f,e,d){return{height:this.originalSize.height+d}},se:function(f,e,d){return c.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[f,e,d]))},sw:function(f,e,d){return c.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[f,e,d]))},ne:function(f,e,d){return c.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[f,e,d]))},nw:function(f,e,d){return c.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[f,e,d]))}},_propagate:function(e,d){c.ui.plugin.call(this,e,[d,this.ui()]);(e!="resize"&&this._trigger(e,d,this.ui()))},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}));c.extend(c.ui.resizable,{version:"1.7.2",eventPrefix:"resize",defaults:{alsoResize:false,animate:false,animateDuration:"slow",animateEasing:"swing",aspectRatio:false,autoHide:false,cancel:":input,option",containment:false,delay:0,distance:1,ghost:false,grid:false,handles:"e,s,se",helper:false,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:1000}});c.ui.plugin.add("resizable","alsoResize",{start:function(e,f){var d=c(this).data("resizable"),g=d.options;_store=function(h){c(h).each(function(){c(this).data("resizable-alsoresize",{width:parseInt(c(this).width(),10),height:parseInt(c(this).height(),10),left:parseInt(c(this).css("left"),10),top:parseInt(c(this).css("top"),10)})})};if(typeof(g.alsoResize)=="object"&&!g.alsoResize.parentNode){if(g.alsoResize.length){g.alsoResize=g.alsoResize[0];_store(g.alsoResize)}else{c.each(g.alsoResize,function(h,i){_store(h)})}}else{_store(g.alsoResize)}},resize:function(f,h){var e=c(this).data("resizable"),i=e.options,g=e.originalSize,k=e.originalPosition;var j={height:(e.size.height-g.height)||0,width:(e.size.width-g.width)||0,top:(e.position.top-k.top)||0,left:(e.position.left-k.left)||0},d=function(l,m){c(l).each(function(){var p=c(this),q=c(this).data("resizable-alsoresize"),o={},n=m&&m.length?m:["width","height","top","left"];c.each(n||["width","height","top","left"],function(r,t){var s=(q[t]||0)+(j[t]||0);if(s&&s>=0){o[t]=s||null}});if(/relative/.test(p.css("position"))&&c.browser.opera){e._revertToRelativePosition=true;p.css({position:"absolute",top:"auto",left:"auto"})}p.css(o)})};if(typeof(i.alsoResize)=="object"&&!i.alsoResize.nodeType){c.each(i.alsoResize,function(l,m){d(l,m)})}else{d(i.alsoResize)}},stop:function(e,f){var d=c(this).data("resizable");if(d._revertToRelativePosition&&c.browser.opera){d._revertToRelativePosition=false;el.css({position:"relative"})}c(this).removeData("resizable-alsoresize-start")}});c.ui.plugin.add("resizable","animate",{stop:function(h,m){var n=c(this).data("resizable"),i=n.options;var g=n._proportionallyResizeElements,d=g.length&&(/textarea/i).test(g[0].nodeName),e=d&&c.ui.hasScroll(g[0],"left")?0:n.sizeDiff.height,k=d?0:n.sizeDiff.width;var f={width:(n.size.width-k),height:(n.size.height-e)},j=(parseInt(n.element.css("left"),10)+(n.position.left-n.originalPosition.left))||null,l=(parseInt(n.element.css("top"),10)+(n.position.top-n.originalPosition.top))||null;n.element.animate(c.extend(f,l&&j?{top:l,left:j}:{}),{duration:i.animateDuration,easing:i.animateEasing,step:function(){var o={width:parseInt(n.element.css("width"),10),height:parseInt(n.element.css("height"),10),top:parseInt(n.element.css("top"),10),left:parseInt(n.element.css("left"),10)};if(g&&g.length){c(g[0]).css({width:o.width,height:o.height})}n._updateCache(o);n._propagate("resize",h)}})}});c.ui.plugin.add("resizable","containment",{start:function(e,q){var s=c(this).data("resizable"),i=s.options,k=s.element;var f=i.containment,j=(f instanceof c)?f.get(0):(/parent/.test(f))?k.parent().get(0):f;if(!j){return}s.containerElement=c(j);if(/document/.test(f)||f==document){s.containerOffset={left:0,top:0};s.containerPosition={left:0,top:0};s.parentData={element:c(document),left:0,top:0,width:c(document).width(),height:c(document).height()||document.body.parentNode.scrollHeight}}else{var m=c(j),h=[];c(["Top","Right","Left","Bottom"]).each(function(p,o){h[p]=b(m.css("padding"+o))});s.containerOffset=m.offset();s.containerPosition=m.position();s.containerSize={height:(m.innerHeight()-h[3]),width:(m.innerWidth()-h[1])};var n=s.containerOffset,d=s.containerSize.height,l=s.containerSize.width,g=(c.ui.hasScroll(j,"left")?j.scrollWidth:l),r=(c.ui.hasScroll(j)?j.scrollHeight:d);s.parentData={element:j,left:n.left,top:n.top,width:g,height:r}}},resize:function(f,p){var s=c(this).data("resizable"),h=s.options,e=s.containerSize,n=s.containerOffset,l=s.size,m=s.position,q=s._aspectRatio||f.shiftKey,d={top:0,left:0},g=s.containerElement;if(g[0]!=document&&(/static/).test(g.css("position"))){d=n}if(m.left<(s._helper?n.left:0)){s.size.width=s.size.width+(s._helper?(s.position.left-n.left):(s.position.left-d.left));if(q){s.size.height=s.size.width/h.aspectRatio}s.position.left=h.helper?n.left:0}if(m.top<(s._helper?n.top:0)){s.size.height=s.size.height+(s._helper?(s.position.top-n.top):s.position.top);if(q){s.size.width=s.size.height*h.aspectRatio}s.position.top=s._helper?n.top:0}s.offset.left=s.parentData.left+s.position.left;s.offset.top=s.parentData.top+s.position.top;var k=Math.abs((s._helper?s.offset.left-d.left:(s.offset.left-d.left))+s.sizeDiff.width),r=Math.abs((s._helper?s.offset.top-d.top:(s.offset.top-n.top))+s.sizeDiff.height);var j=s.containerElement.get(0)==s.element.parent().get(0),i=/relative|absolute/.test(s.containerElement.css("position"));if(j&&i){k-=s.parentData.left}if(k+s.size.width>=s.parentData.width){s.size.width=s.parentData.width-k;if(q){s.size.height=s.size.width/s.aspectRatio}}if(r+s.size.height>=s.parentData.height){s.size.height=s.parentData.height-r;if(q){s.size.width=s.size.height*s.aspectRatio}}},stop:function(e,m){var p=c(this).data("resizable"),f=p.options,k=p.position,l=p.containerOffset,d=p.containerPosition,g=p.containerElement;var i=c(p.helper),q=i.offset(),n=i.outerWidth()-p.sizeDiff.width,j=i.outerHeight()-p.sizeDiff.height;if(p._helper&&!f.animate&&(/relative/).test(g.css("position"))){c(this).css({left:q.left-d.left-l.left,width:n,height:j})}if(p._helper&&!f.animate&&(/static/).test(g.css("position"))){c(this).css({left:q.left-d.left-l.left,width:n,height:j})}}});c.ui.plugin.add("resizable","ghost",{start:function(f,g){var d=c(this).data("resizable"),h=d.options,e=d.size;d.ghost=d.originalElement.clone();d.ghost.css({opacity:0.25,display:"block",position:"relative",height:e.height,width:e.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass(typeof h.ghost=="string"?h.ghost:"");d.ghost.appendTo(d.helper)},resize:function(e,f){var d=c(this).data("resizable"),g=d.options;if(d.ghost){d.ghost.css({position:"relative",height:d.size.height,width:d.size.width})}},stop:function(e,f){var d=c(this).data("resizable"),g=d.options;if(d.ghost&&d.helper){d.helper.get(0).removeChild(d.ghost.get(0))}}});c.ui.plugin.add("resizable","grid",{resize:function(d,l){var n=c(this).data("resizable"),g=n.options,j=n.size,h=n.originalSize,i=n.originalPosition,m=n.axis,k=g._aspectRatio||d.shiftKey;g.grid=typeof g.grid=="number"?[g.grid,g.grid]:g.grid;var f=Math.round((j.width-h.width)/(g.grid[0]||1))*(g.grid[0]||1),e=Math.round((j.height-h.height)/(g.grid[1]||1))*(g.grid[1]||1);if(/^(se|s|e)$/.test(m)){n.size.width=h.width+f;n.size.height=h.height+e}else{if(/^(ne)$/.test(m)){n.size.width=h.width+f;n.size.height=h.height+e;n.position.top=i.top-e}else{if(/^(sw)$/.test(m)){n.size.width=h.width+f;n.size.height=h.height+e;n.position.left=i.left-f}else{n.size.width=h.width+f;n.size.height=h.height+e;n.position.top=i.top-e;n.position.left=i.left-f}}}}});var b=function(d){return parseInt(d,10)||0};var a=function(d){return !isNaN(parseInt(d,10))}})(jQuery);;
/*
 * jQuery UI Dialog 1.7.2
 *
 * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Dialog
 *
 * Depends:
 *    ui.core.js
 *    ui.draggable.js
 *    ui.resizable.js
 */
(function(c){var b={dragStart:"start.draggable",drag:"drag.draggable",dragStop:"stop.draggable",maxHeight:"maxHeight.resizable",minHeight:"minHeight.resizable",maxWidth:"maxWidth.resizable",minWidth:"minWidth.resizable",resizeStart:"start.resizable",resize:"drag.resizable",resizeStop:"stop.resizable"},a="ui-dialog ui-widget ui-widget-content ui-corner-all ";c.widget("ui.dialog",{_init:function(){this.originalTitle=this.element.attr("title");var l=this,m=this.options,j=m.title||this.originalTitle||"&nbsp;",e=c.ui.dialog.getTitleId(this.element),k=(this.uiDialog=c("<div/>")).appendTo(document.body).hide().addClass(a+m.dialogClass).css({position:"absolute",overflow:"hidden",zIndex:m.zIndex}).attr("tabIndex",-1).css("outline",0).keydown(function(n){(m.closeOnEscape&&n.keyCode&&n.keyCode==c.ui.keyCode.ESCAPE&&l.close(n))}).attr({role:"dialog","aria-labelledby":e}).mousedown(function(n){l.moveToTop(false,n)}),g=this.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(k),f=(this.uiDialogTitlebar=c("<div></div>")).addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix").prependTo(k),i=c('<a href="#"/>').addClass("ui-dialog-titlebar-close ui-corner-all").attr("role","button").hover(function(){i.addClass("ui-state-hover")},function(){i.removeClass("ui-state-hover")}).focus(function(){i.addClass("ui-state-focus")}).blur(function(){i.removeClass("ui-state-focus")}).mousedown(function(n){n.stopPropagation()}).click(function(n){l.close(n);return false}).appendTo(f),h=(this.uiDialogTitlebarCloseText=c("<span/>")).addClass("ui-icon ui-icon-closethick").text(m.closeText).appendTo(i),d=c("<span/>").addClass("ui-dialog-title").attr("id",e).html(j).prependTo(f);f.find("*").add(f).disableSelection();(m.draggable&&c.fn.draggable&&this._makeDraggable());(m.resizable&&c.fn.resizable&&this._makeResizable());this._createButtons(m.buttons);this._isOpen=false;(m.bgiframe&&c.fn.bgiframe&&k.bgiframe());(m.autoOpen&&this.open())},destroy:function(){(this.overlay&&this.overlay.destroy());this.uiDialog.hide();this.element.unbind(".dialog").removeData("dialog").removeClass("ui-dialog-content ui-widget-content").hide().appendTo("body");this.uiDialog.remove();(this.originalTitle&&this.element.attr("title",this.originalTitle))},close:function(f){var d=this;if(false===d._trigger("beforeclose",f)){return}(d.overlay&&d.overlay.destroy());d.uiDialog.unbind("keypress.ui-dialog");(d.options.hide?d.uiDialog.hide(d.options.hide,function(){d._trigger("close",f)}):d.uiDialog.hide()&&d._trigger("close",f));c.ui.dialog.overlay.resize();d._isOpen=false;if(d.options.modal){var e=0;c(".ui-dialog").each(function(){if(this!=d.uiDialog[0]){e=Math.max(e,c(this).css("z-index"))}});c.ui.dialog.maxZ=e}},isOpen:function(){return this._isOpen},moveToTop:function(f,e){if((this.options.modal&&!f)||(!this.options.stack&&!this.options.modal)){return this._trigger("focus",e)}if(this.options.zIndex>c.ui.dialog.maxZ){c.ui.dialog.maxZ=this.options.zIndex}(this.overlay&&this.overlay.$el.css("z-index",c.ui.dialog.overlay.maxZ=++c.ui.dialog.maxZ));var d={scrollTop:this.element.attr("scrollTop"),scrollLeft:this.element.attr("scrollLeft")};this.uiDialog.css("z-index",++c.ui.dialog.maxZ);this.element.attr(d);this._trigger("focus",e)},open:function(){if(this._isOpen){return}var e=this.options,d=this.uiDialog;this.overlay=e.modal?new c.ui.dialog.overlay(this):null;(d.next().length&&d.appendTo("body"));this._size();this._position(e.position);d.show(e.show);this.moveToTop(true);(e.modal&&d.bind("keypress.ui-dialog",function(h){if(h.keyCode!=c.ui.keyCode.TAB){return}var g=c(":tabbable",this),i=g.filter(":first")[0],f=g.filter(":last")[0];if(h.target==f&&!h.shiftKey){setTimeout(function(){i.focus()},1)}else{if(h.target==i&&h.shiftKey){setTimeout(function(){f.focus()},1)}}}));c([]).add(d.find(".ui-dialog-content :tabbable:first")).add(d.find(".ui-dialog-buttonpane :tabbable:first")).add(d).filter(":first").focus();this._trigger("open");this._isOpen=true},_createButtons:function(g){var f=this,d=false,e=c("<div></div>").addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix");this.uiDialog.find(".ui-dialog-buttonpane").remove();(typeof g=="object"&&g!==null&&c.each(g,function(){return !(d=true)}));if(d){c.each(g,function(h,i){c('<button type="button"></button>').addClass("ui-state-default ui-corner-all").text(h).click(function(){i.apply(f.element[0],arguments)}).hover(function(){c(this).addClass("ui-state-hover")},function(){c(this).removeClass("ui-state-hover")}).focus(function(){c(this).addClass("ui-state-focus")}).blur(function(){c(this).removeClass("ui-state-focus")}).appendTo(e)});e.appendTo(this.uiDialog)}},_makeDraggable:function(){var d=this,f=this.options,e;this.uiDialog.draggable({cancel:".ui-dialog-content",handle:".ui-dialog-titlebar",containment:"document",start:function(){e=f.height;c(this).height(c(this).height()).addClass("ui-dialog-dragging");(f.dragStart&&f.dragStart.apply(d.element[0],arguments))},drag:function(){(f.drag&&f.drag.apply(d.element[0],arguments))},stop:function(){c(this).removeClass("ui-dialog-dragging").height(e);(f.dragStop&&f.dragStop.apply(d.element[0],arguments));c.ui.dialog.overlay.resize()}})},_makeResizable:function(g){g=(g===undefined?this.options.resizable:g);var d=this,f=this.options,e=typeof g=="string"?g:"n,e,s,w,se,sw,ne,nw";this.uiDialog.resizable({cancel:".ui-dialog-content",alsoResize:this.element,maxWidth:f.maxWidth,maxHeight:f.maxHeight,minWidth:f.minWidth,minHeight:f.minHeight,start:function(){c(this).addClass("ui-dialog-resizing");(f.resizeStart&&f.resizeStart.apply(d.element[0],arguments))},resize:function(){(f.resize&&f.resize.apply(d.element[0],arguments))},handles:e,stop:function(){c(this).removeClass("ui-dialog-resizing");f.height=c(this).height();f.width=c(this).width();(f.resizeStop&&f.resizeStop.apply(d.element[0],arguments));c.ui.dialog.overlay.resize()}}).find(".ui-resizable-se").addClass("ui-icon ui-icon-grip-diagonal-se")},_position:function(i){var e=c(window),f=c(document),g=f.scrollTop(),d=f.scrollLeft(),h=g;if(c.inArray(i,["center","top","right","bottom","left"])>=0){i=[i=="right"||i=="left"?i:"center",i=="top"||i=="bottom"?i:"middle"]}if(i.constructor!=Array){i=["center","middle"]}if(i[0].constructor==Number){d+=i[0]}else{switch(i[0]){case"left":d+=0;break;case"right":d+=e.width()-this.uiDialog.outerWidth();break;default:case"center":d+=(e.width()-this.uiDialog.outerWidth())/2}}if(i[1].constructor==Number){g+=i[1]}else{switch(i[1]){case"top":g+=0;break;case"bottom":g+=e.height()-this.uiDialog.outerHeight();break;default:case"middle":g+=(e.height()-this.uiDialog.outerHeight())/2}}g=Math.max(g,h);this.uiDialog.css({top:g,left:d})},_setData:function(e,f){(b[e]&&this.uiDialog.data(b[e],f));switch(e){case"buttons":this._createButtons(f);break;case"closeText":this.uiDialogTitlebarCloseText.text(f);break;case"dialogClass":this.uiDialog.removeClass(this.options.dialogClass).addClass(a+f);break;case"draggable":(f?this._makeDraggable():this.uiDialog.draggable("destroy"));break;case"height":this.uiDialog.height(f);break;case"position":this._position(f);break;case"resizable":var d=this.uiDialog,g=this.uiDialog.is(":data(resizable)");(g&&!f&&d.resizable("destroy"));(g&&typeof f=="string"&&d.resizable("option","handles",f));(g||this._makeResizable(f));break;case"title":c(".ui-dialog-title",this.uiDialogTitlebar).html(f||"&nbsp;");break;case"width":this.uiDialog.width(f);break}c.widget.prototype._setData.apply(this,arguments)},_size:function(){var e=this.options;this.element.css({height:0,minHeight:0,width:"auto"});var d=this.uiDialog.css({height:"auto",width:e.width}).height();this.element.css({minHeight:Math.max(e.minHeight-d,0),height:e.height=="auto"?"auto":Math.max(e.height-d,0)})}});c.extend(c.ui.dialog,{version:"1.7.2",defaults:{autoOpen:true,bgiframe:false,buttons:{},closeOnEscape:true,closeText:"close",dialogClass:"",draggable:true,hide:null,height:"auto",maxHeight:false,maxWidth:false,minHeight:150,minWidth:150,modal:false,position:"center",resizable:true,show:null,stack:true,title:"",width:300,zIndex:1000},getter:"isOpen",uuid:0,maxZ:0,getTitleId:function(d){return"ui-dialog-title-"+(d.attr("id")||++this.uuid)},overlay:function(d){this.$el=c.ui.dialog.overlay.create(d)}});c.extend(c.ui.dialog.overlay,{instances:[],maxZ:0,events:c.map("focus,mousedown,mouseup,keydown,keypress,click".split(","),function(d){return d+".dialog-overlay"}).join(" "),create:function(e){if(this.instances.length===0){setTimeout(function(){if(c.ui.dialog.overlay.instances.length){c(document).bind(c.ui.dialog.overlay.events,function(f){var g=c(f.target).parents(".ui-dialog").css("zIndex")||0;return(g>c.ui.dialog.overlay.maxZ)})}},1);c(document).bind("keydown.dialog-overlay",function(f){(e.options.closeOnEscape&&f.keyCode&&f.keyCode==c.ui.keyCode.ESCAPE&&e.close(f))});c(window).bind("resize.dialog-overlay",c.ui.dialog.overlay.resize)}var d=c("<div></div>").appendTo(document.body).addClass("ui-widget-overlay").css({width:this.width(),height:this.height()});(e.options.bgiframe&&c.fn.bgiframe&&d.bgiframe());this.instances.push(d);return d},destroy:function(d){this.instances.splice(c.inArray(this.instances,d),1);if(this.instances.length===0){c([document,window]).unbind(".dialog-overlay")}d.remove();var e=0;c.each(this.instances,function(){e=Math.max(e,this.css("z-index"))});this.maxZ=e},height:function(){if(c.browser.msie&&c.browser.version<7){var e=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight);var d=Math.max(document.documentElement.offsetHeight,document.body.offsetHeight);if(e<d){return c(window).height()+"px"}else{return e+"px"}}else{return c(document).height()+"px"}},width:function(){if(c.browser.msie&&c.browser.version<7){var d=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth);var e=Math.max(document.documentElement.offsetWidth,document.body.offsetWidth);if(d<e){return c(window).width()+"px"}else{return d+"px"}}else{return c(document).width()+"px"}},resize:function(){var d=c([]);c.each(c.ui.dialog.overlay.instances,function(){d=d.add(this)});d.css({width:0,height:0}).css({width:c.ui.dialog.overlay.width(),height:c.ui.dialog.overlay.height()})}});c.extend(c.ui.dialog.overlay.prototype,{destroy:function(){c.ui.dialog.overlay.destroy(this.$el)}})})(jQuery);;
//------------------------flydom.js-------------------------------------------
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}('7.y.p=l(a,b,c){5(b==I&&a.z==A){8(4 i=0;i<a.9;i+=3){7(6).p(a[i],a[i+1]||{},a[i+2]||[])}k 6}4 d=6[0];5(7.Q.R&&a==\'12\'&&b.J){4 a=n.q(\'<\'+a+\' J="\'+b.J+\'" />\')}m{4 a=n.q(a)};5(d.B.u()==\'T\'&&a.B.u()==\'U\'){5(d&&d.C(\'r\')[0]){4 e=d.C(\'r\')[0]}m{4 e=d.o(n.q(\'r\'))};4 a=e.o(a)}m{4 a=d.o(a)};a=K(a,b);5(t c==\'L\'&&c!=v){8(4 i=0;i<c.9;i=i+3){7(a).p(c[i],c[i+1]||{},c[i+2]||[])}}m 5(c!=v){a=M(a,c)};k 7(a)};7.y.V=l(a,b,c){5(b==I&&a.z==A){8(4 i=0;i<a.9;i+=3){7(6).V(a[i],a[i+1]||{},a[i+2]||[])}k 6}4 a=n.q(a);5(6[0].W()==N){4 a=6[0].o(a)};a=K(a,b);5(t c==\'L\'&&c!=v){8(4 i=0;i<c.9;i=i+3){7(a).p(c[i],c[i+1]||{},c[i+2]||[])}}m 5(c!=v){a=M(a,c)};5(6[0].W()==13){4 a=6[0].D(a,6[0].E)};k 7(a)};7.y.14=l(a,b){5(a.z!=A){a=[a]};5(a.9==0){k N};8(4 i=0;i<a.9;i++){4 c=b.X(a[i]);8(4 j=0;j<c.9;j=j+3){7(6).p(c[j],c[j+1],c[j+2])}};k 6};7.y.15=l(a,b){4 c=6[0];5(a.z!=A){a=[a]};5(a.9==0){k N};4 d=n.q(\'16\');8(4 i=0;i<a.9;i++){4 e=b.X(a[i]);8(4 j=0;j<e.9;j=j+3){7(d).p(e[j],e[j+1],e[j+2])}};8(i=d.w.9-1;i>=0;i--){5(7.Q.R&&c.B.u()==\'T\'&&d.w[i].B.u()==\'U\'){5(c.C(\'r\')[0]){4 f=c.C(\'r\')[0];f.D(d.w[i],f.E)}m{4 f=c.D(n.q(\'r\'),c.E);f.o(f.o(d.w[i]))}}m{c.D(d.w[i],c.E)}};k 6};Y.Z.F=l(){4 a=6;4 b={\'17\':\'18\',\'19\':\'1a\',\'1b\':\'1c\',\'8\':\'1d\',\'1e\':\'1f\',\'1g\':\'1h\',\'1i\':\'1j\',\'1k\':\'1l\',\'1m\':\'1n\',\'1o\':\'1p\',\'1q\':\'1r\',\'1s\':\'1t\',\'1u\':\'1v\',\'1w\':\'1x\',\'1y\':\'1z\',\'1A\':\'1B\',\'1C\':\'1D\',\'1E\':\'1F\',\'1G\':\'1H\',\'1I\':\'1J\',\'1K\':\'1L\',\'1M\':\'1N\',\'1O\':\'1P\',\'1Q\':\'1R\',\'1S\':\'1T\',\'1U\':\'1V\',\'1W\':\'1X\',\'1Y\':\'1Z\',\'20\':\'21\',\'22\':\'23\',\'24\':\'25\',\'26\':\'27\',\'28\':\'29\',\'2a\':\'2b\',\'2c\':\'2d\'};5(b[a]!=\'\'&&t b[a]!=\'I\'){k b[a]}5(a.2e(\'-\')>0){4 c=a.G(\'-\');a=c[0];8(i=1;i<c.9;i++){a+=c[i].H(0,1).10()+c[i].H(1).u()}};k a};Y.Z.x=l(){k 6.2f(/^\\s+|\\s+$/g,\'\')};K=l(a,b){8(O 11 b){4 c=O;4 d=b[O];2g(c){2h\'P\':5(t d==\'2i\'){4 e=d.G(\';\');8(4 i=0;i<e.9;i++){5(e[i].x()!=\'\'){4 f=e[i].G(\':\')[0].x();4 g=e[i].G(\':\')[1].x();f=f.F();5(f!=\'\'){a.P[f]=g}}}}m 5(t d==\'L\'){8(f 11 d){4 h=f.F();5(f.x()!=\'\'){a.P[h]=d[f]}}};2j;2k:5(c.H(0,2)==\'2l\'){4 j=c.H(2);d=(t d!=\'l\')?2m(\'f = l() { \'+d+\'}\'):d;7(a).2n(j,d)}m{a[c.F()]=d}}};k a};M=l(a,b){4 c=/(<\\S[^><]*>)|(&.+;)/g;5(b.2o(c)!=v&&a.2p.10()!=\'2q\'){a.2r=b}m{4 d=n.2s(b);a.o(d)};k a};',62,153,'||||var|if|this|jQuery|for|length|||||||||||return|function|else|document|appendChild|createAppend|createElement|tbody||typeof|toLowerCase|null|childNodes|trim|fn|constructor|Array|nodeName|getElementsByTagName|insertBefore|firstChild|toCamelCase|split|substr|undefined|type|__FlyDOM_parseAttrs|object|__FlyDOM_setText|false|attr|style|browser|msie||table|tr|createPrepend|hasChildNodes|apply|String|prototype|toUpperCase|in|input|true|tplAppend|tplPrepend|div|class|className|colspan|colSpan|rowspan|rowSpan|htmlFor|httpequiv|httpEquiv|alink|aLink|vlink|vLink|bgcolor|bgColor|acceptcharset|acceptCharset|selectedindex|selectedIndex|tabindex|tabIndex|selected|defaultSelected|checked|defaultChecked|value|defaultValue|accesskey|accessKey|noshade|noShade|datetime|dateTime|usemap|useMap|lowsrc|lowSrc|longdesc|longDesc|ismap|isMap|codebase|codeBase|codetype|codeType|valuetype|valueType|nohref|noHref|thead|tHead|tfoot|tFoot|cellpadding|cellPadding|cellspacing|cellSpacing|charoff|chOff|valign|vAlign|frameborder|frameBorder|marginheight|marginHeight|marginwidth|marginWidth|noresize|noResize|indexOf|replace|switch|case|string|break|default|on|eval|bind|match|tagName|TEXTAREA|innerHTML|createTextNode'.split('|'),0,{}));
//------------------------scrollpane.js---------------------------------------
/* Copyright (c) 2009 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.js 90 2010-01-25 03:52:10Z kelvin.luck $
 */

/**
 * Replace the vertical scroll bars on any matched elements with a fancy
 * styleable (via CSS) version. With JS disabled the elements will
 * gracefully degrade to the browsers own implementation of overflow:auto.
 * If the mousewheel plugin has been included on the page then the scrollable areas will also
 * respond to the mouse wheel.
 *
 * @example jQuery(".scroll-pane").jScrollPane();
 *
 * @name jScrollPane
 * @type jQuery
 * @param Object    settings    hash with options, described below.
 *                                scrollbarWidth    -    The width of the generated scrollbar in pixels
 *                                scrollbarMargin    -    The amount of space to leave on the side of the scrollbar in pixels
 *                                wheelSpeed        -    The speed the pane will scroll in response to the mouse wheel in pixels
 *                                showArrows        -    Whether to display arrows for the user to scroll with
 *                                arrowSize        -    The height of the arrow buttons if showArrows=true
 *                                animateTo        -    Whether to animate when calling scrollTo and scrollBy
 *                                dragMinHeight    -    The minimum height to allow the drag bar to be
 *                                dragMaxHeight    -    The maximum height to allow the drag bar to be
 *                                animateInterval    -    The interval in milliseconds to update an animating scrollPane (default 100)
 *                                animateStep        -    The amount to divide the remaining scroll distance by when animating (default 3)
 *                                maintainPosition-    Whether you want the contents of the scroll pane to maintain it's position when you re-initialise it - so it doesn't scroll as you add more content (default true)
 *                                tabIndex        -    The tabindex for this jScrollPane to control when it is tabbed to when navigating via keyboard (default 0)
 *                                enableKeyboardNavigation - Whether to allow keyboard scrolling of this jScrollPane when it is focused (default true)
 *                                animateToInternalLinks - Whether the move to an internal link (e.g. when it's focused by tabbing or by a hash change in the URL) should be animated or instant (default false)
 *                                scrollbarOnLeft    -    Display the scrollbar on the left side?  (needs stylesheet changes, see examples.html)
 *                                reinitialiseOnImageLoad - Whether the jScrollPane should automatically re-initialise itself when any contained images are loaded (default false)
 *                                topCapHeight    -    The height of the "cap" area between the top of the jScrollPane and the top of the track/ buttons
 *                                bottomCapHeight    -    The height of the "cap" area between the bottom of the jScrollPane and the bottom of the track/ buttons
 *                                observeHash        -    Whether jScrollPane should attempt to automagically scroll to the correct place when an anchor inside the scrollpane is linked to (default true)
 * @return jQuery
 * @cat Plugins/jScrollPane
 * @author Kelvin Luck (kelvin AT kelvinluck DOT com || http://www.kelvinluck.com)
 */

(function($) {

$.jScrollPane = {
    active : []
};
$.fn.jScrollPane = function(settings)
{
    settings = $.extend({}, $.fn.jScrollPane.defaults, settings);

    var rf = function() { return false; };
    
    return this.each(
        function()
        {
            var $this = $(this);
            var paneEle = this;
            var currentScrollPosition = 0;
            var paneWidth;
            var paneHeight;
            var trackHeight;
            var trackOffset = settings.topCapHeight;
            var $container;
            
            if ($(this).parent().is('.jScrollPaneContainer')) {
                $container = $(this).parent();
                currentScrollPosition = settings.maintainPosition ? $this.position().top : 0;
                var $c = $(this).parent();
                paneWidth = $c.innerWidth();
                paneHeight = $c.outerHeight();
                $('>.jScrollPaneTrack, >.jScrollArrowUp, >.jScrollArrowDown, >.jScrollCap', $c).remove();
                $this.css({'top':0});
            } else {
                $this.data('originalStyleTag', $this.attr('style'));
                // Switch the element's overflow to hidden to ensure we get the size of the element without the scrollbars [http://plugins.jquery.com/node/1208]
                $this.css('overflow', 'hidden');
                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);
                paneWidth = $this.innerWidth();
                paneHeight = $this.innerHeight();
                $container = $('<div></div>')
                    .attr({'className':'jScrollPaneContainer'})
                    .css(
                        {
                            'height':paneHeight+'px', 
                            'width':paneWidth+'px'
                        }
                    );
                if (settings.enableKeyboardNavigation) {
                    $container.attr(
                        'tabindex', 
                        settings.tabIndex
                    );
                }
                $this.wrap($container);
                $container = $this.parent();
                // deal with text size changes (if the jquery.em plugin is included)
                // and re-initialise the scrollPane so the track maintains the
                // correct size
                $(document).bind(
                    'emchange', 
                    function(e, cur, prev)
                    {
                        $this.jScrollPane(settings);
                    }
                );
                
            }
            trackHeight = paneHeight;
            
            if (settings.reinitialiseOnImageLoad) {
                // code inspired by jquery.onImagesLoad: http://plugins.jquery.com/project/onImagesLoad
                // except we re-initialise the scroll pane when each image loads so that the scroll pane is always up to size...
                // TODO: Do I even need to store it in $.data? Is a local variable here the same since I don't pass the reinitialiseOnImageLoad when I re-initialise?
                var $imagesToLoad = $.data(paneEle, 'jScrollPaneImagesToLoad') || $('img', $this);
                var loadedImages = [];
                
                if ($imagesToLoad.length) {
                    $imagesToLoad.each(function(i, val)    {
                        $(this).bind('load readystatechange', function() {
                            if($.inArray(i, loadedImages) == -1){ //don't double count images
                                loadedImages.push(val); //keep a record of images we've seen
                                $imagesToLoad = $.grep($imagesToLoad, function(n, i) {
                                    return n != val;
                                });
                                $.data(paneEle, 'jScrollPaneImagesToLoad', $imagesToLoad);
                                var s2 = $.extend(settings, {reinitialiseOnImageLoad:false});
                                $this.jScrollPane(s2); // re-initialise
                            }
                        }).each(function(i, val) {
                            if(this.complete || this.complete===undefined) { 
                                //needed for potential cached images
                                this.src = this.src; 
                            } 
                        });
                    });
                };
            }

            var p = this.originalSidePaddingTotal;
            var realPaneWidth = paneWidth - settings.scrollbarWidth - settings.scrollbarMargin - p;

            var cssToApply = {
                'height':'auto',
                'width': realPaneWidth + 'px'
            }

            if(settings.scrollbarOnLeft) {
                cssToApply.paddingLeft = settings.scrollbarMargin + settings.scrollbarWidth + 'px';
            } else {
                cssToApply.paddingRight = settings.scrollbarMargin + 'px';
            }

            $this.css(cssToApply);

            var contentHeight = $this.outerHeight();
            var percentInView = paneHeight / contentHeight;
            
            var isScrollable = percentInView < .99;
            $container[isScrollable ? 'addClass' : 'removeClass']('jScrollPaneScrollable');

            if (isScrollable) {
                $container.append(
                    $('<div></div>').addClass('jScrollCap jScrollCapTop').css({height:settings.topCapHeight}),
                    $('<div></div>').attr({'className':'jScrollPaneTrack'}).css({'width':settings.scrollbarWidth+'px'}).append(
                        $('<div></div>').attr({'className':'jScrollPaneDrag'}).css({'width':settings.scrollbarWidth+'px'}).append(
                            $('<div></div>').attr({'className':'jScrollPaneDragTop'}).css({'width':settings.scrollbarWidth+'px'}),
                            $('<div></div>').attr({'className':'jScrollPaneDragBottom'}).css({'width':settings.scrollbarWidth+'px'})
                        )
                    ),
                    $('<div></div>').addClass('jScrollCap jScrollCapBottom').css({height:settings.bottomCapHeight})
                );
                
                var $track = $('>.jScrollPaneTrack', $container);
                var $drag = $('>.jScrollPaneTrack .jScrollPaneDrag', $container);
                
                
                var currentArrowDirection;
                var currentArrowTimerArr = [];// Array is used to store timers since they can stack up when dealing with keyboard events. This ensures all timers are cleaned up in the end, preventing an acceleration bug.
                var currentArrowInc;
                var whileArrowButtonDown = function() 
                {
                    if (currentArrowInc > 4 || currentArrowInc % 4 == 0) {
                        positionDrag(dragPosition + currentArrowDirection * mouseWheelMultiplier);
                    }
                    currentArrowInc++;
                };

                if (settings.enableKeyboardNavigation) {
                    $container.bind(
                        'keydown.jscrollpane',
                        function(e) 
                        {
                            switch (e.keyCode) {
                                case 38: //up
                                    currentArrowDirection = -1;
                                    currentArrowInc = 0;
                                    whileArrowButtonDown();
                                    currentArrowTimerArr[currentArrowTimerArr.length] = setInterval(whileArrowButtonDown, 100);
                                    return false;
                                case 40: //down
                                    currentArrowDirection = 1;
                                    currentArrowInc = 0;
                                    whileArrowButtonDown();
                                    currentArrowTimerArr[currentArrowTimerArr.length] = setInterval(whileArrowButtonDown, 100);
                                    return false;
                                case 33: // page up
                                case 34: // page down
                                    // TODO
                                    return false;
                                default:
                            }
                        }
                    ).bind(
                        'keyup.jscrollpane',
                        function(e) 
                        {
                            if (e.keyCode == 38 || e.keyCode == 40) {
                                for (var i = 0; i < currentArrowTimerArr.length; i++) {
                                    clearInterval(currentArrowTimerArr[i]);
                                }
                                return false;
                            }
                        }
                    );
                }

                if (settings.showArrows) {
                    
                    var currentArrowButton;
                    var currentArrowInterval;

                    var onArrowMouseUp = function(event)
                    {
                        $('html').unbind('mouseup', onArrowMouseUp);
                        currentArrowButton.removeClass('jScrollActiveArrowButton');
                        clearInterval(currentArrowInterval);
                    };
                    var onArrowMouseDown = function() {
                        $('html').bind('mouseup', onArrowMouseUp);
                        currentArrowButton.addClass('jScrollActiveArrowButton');
                        currentArrowInc = 0;
                        whileArrowButtonDown();
                        currentArrowInterval = setInterval(whileArrowButtonDown, 100);
                    };
                    $container
                        .append(
                            $('<a></a>')
                                .attr(
                                    {
                                        'href':'javascript:;', 
                                        'className':'jScrollArrowUp', 
                                        'tabindex':-1
                                    }
                                )
                                .css(
                                    {
                                        'width':settings.scrollbarWidth+'px',
                                        'top':settings.topCapHeight + 'px'
                                    }
                                )
                                .html('Scroll up')
                                .bind('mousedown', function()
                                {
                                    currentArrowButton = $(this);
                                    currentArrowDirection = -1;
                                    onArrowMouseDown();
                                    this.blur();
                                    return false;
                                })
                                .bind('click', rf),
                            $('<a></a>')
                                .attr(
                                    {
                                        'href':'javascript:;', 
                                        'className':'jScrollArrowDown', 
                                        'tabindex':-1
                                    }
                                )
                                .css(
                                    {
                                        'width':settings.scrollbarWidth+'px',
                                        'bottom':settings.bottomCapHeight + 'px'
                                    }
                                )
                                .html('Scroll down')
                                .bind('mousedown', function()
                                {
                                    currentArrowButton = $(this);
                                    currentArrowDirection = 1;
                                    onArrowMouseDown();
                                    this.blur();
                                    return false;
                                })
                                .bind('click', rf)
                        );
                    var $upArrow = $('>.jScrollArrowUp', $container);
                    var $downArrow = $('>.jScrollArrowDown', $container);
                }
                
                if (settings.arrowSize) {
                    trackHeight = paneHeight - settings.arrowSize - settings.arrowSize;
                    trackOffset += settings.arrowSize;
                } else if ($upArrow) {
                    var topArrowHeight = $upArrow.height();
                    settings.arrowSize = topArrowHeight;
                    trackHeight = paneHeight - topArrowHeight - $downArrow.height();
                    trackOffset += topArrowHeight;
                }
                trackHeight -= settings.topCapHeight + settings.bottomCapHeight;
                $track.css({'height': trackHeight+'px', top:trackOffset+'px'})
                
                var $pane = $(this).css({'position':'absolute', 'overflow':'visible'});
                
                var currentOffset;
                var maxY;
                var mouseWheelMultiplier;
                // store this in a seperate variable so we can keep track more accurately than just updating the css property..
                var dragPosition = 0;
                var dragMiddle = percentInView*paneHeight/2;
                
                // pos function borrowed from tooltip plugin and adapted...
                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;
                    $('html').bind('mouseup', onStopDrag).bind('mousemove', updateScroll);
                    if ($.browser.msie) {
                        $('html').bind('dragstart', ignoreNativeDrag).bind('selectstart', ignoreNativeDrag);
                    }
                    return false;
                };
                var onStopDrag = function()
                {
                    $('html').unbind('mouseup', onStopDrag).unbind('mousemove', updateScroll);
                    dragMiddle = percentInView*paneHeight/2;
                    if ($.browser.msie) {
                        $('html').unbind('dragstart', ignoreNativeDrag).unbind('selectstart', ignoreNativeDrag);
                    }
                };
                var positionDrag = function(destY)
                {
                    $container.scrollTop(0);
                    destY = destY < 0 ? 0 : (destY > maxY ? maxY : destY);
                    dragPosition = destY;
                    $drag.css({'top':destY+'px'});
                    var p = destY / maxY;
                    $this.data('jScrollPanePosition', (paneHeight-contentHeight)*-p);
                    $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);
                    $('html').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;
                    $('html').bind('mouseup', onStopTrackClick).bind('mousemove', onTrackMouseMove);
                    trackScrollInterval = setInterval(doTrackScroll, 100);
                    doTrackScroll();
                    return false;
                };
                
                $track.bind('mousedown', onTrackClick);
                
                $container.bind(
                    'mousewheel',
                    function (event, delta) {
                        delta = delta || (event.wheelDelta ? event.wheelDelta / 120 : (event.detail) ?
-event.detail/3 : 0);
                        initDrag();
                        ceaseAnimation();
                        var d = dragPosition;
                        positionDrag(dragPosition - delta * mouseWheelMultiplier);
                        var dragOccured = d != dragPosition;
                        return !dragOccured;
                    }
                );

                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") {
                        // Legal hash values aren't necessarily legal jQuery selectors so we need to catch any
                        // errors from the lookup...
                        try {
                            $e = $(pos, $this);
                        } catch (err) {
                            return;
                        }
                        if (!$e.length) return;
                        pos = $e.offset().top - $this.offset().top;
                    }
                    ceaseAnimation();
                    var maxScroll = contentHeight - paneHeight;
                    pos = pos > maxScroll ? maxScroll : pos;
                    $this.data('jScrollPaneMaxScroll', maxScroll);
                    var destDragPosition = pos/maxScroll * maxY;
                    if (preventAni || !settings.animateTo) {
                        positionDrag(destDragPosition);
                    } else {
                        $container.scrollTop(0);
                        _animateToPosition = destDragPosition;
                        _animateToInterval = setInterval(animateToPosition, settings.animateInterval);
                    }
                };
                $this[0].scrollTo = scrollTo;
                
                $this[0].scrollBy = function(delta)
                {
                    var currentPos = -parseInt($pane.css('top')) || 0;
                    scrollTo(currentPos + delta);
                };
                
                initDrag();
                
                scrollTo(-currentScrollPosition, true);
            
                // Deal with it when the user tabs to a link or form element within this scrollpane
                $('*', this).bind(
                    'focus',
                    function(event)
                    {
                        var $e = $(this);
                        
                        // loop through parents adding the offset top of any elements that are relatively positioned between
                        // the focused element and the jScrollPaneContainer so we can get the true distance from the top
                        // of the focused element to the top of the scrollpane...
                        var eleTop = 0;
                        
                        while ($e[0] != $this[0]) {
                            eleTop += $e.position().top;
                            $e = $e.offsetParent();
                        }
                        
                        var viewportTop = -parseInt($pane.css('top')) || 0;
                        var maxVisibleEleTop = viewportTop + paneHeight;
                        var eleInView = eleTop > viewportTop && eleTop < maxVisibleEleTop;
                        if (!eleInView) {
                            var destPos = eleTop - settings.scrollbarMargin;
                            if (eleTop > viewportTop) { // element is below viewport - scroll so it is at bottom.
                                destPos += $(this).height() + 15 + settings.scrollbarMargin - paneHeight;
                            }
                            scrollTo(destPos);
                        }
                    }
                )
                
                
                if (settings.observeHash) {
                    if (location.hash && location.hash.length > 1) {
                        setTimeout(function(){
                            scrollTo(location.hash);
                        }, $.browser.safari ? 100 : 0);
                    }
                    
                    // use event delegation to listen for all clicks on links and hijack them if they are links to
                    // anchors within our content...
                    $(document).bind('click', function(e){
                        $target = $(e.target);
                        if ($target.is('a')) {
                            var h = $target.attr('href');
                            if (h && h.substr(0, 1) == '#' && h.length > 1) {
                                setTimeout(function(){
                                    scrollTo(h, !settings.animateToInternalLinks);
                                }, $.browser.safari ? 100 : 0);
                            }
                        }
                    });
                }
                
                // Deal with dragging and selecting text to make the scrollpane scroll...
                function onSelectScrollMouseDown(e)
                {
                   $(document).bind('mousemove.jScrollPaneDragging', onTextSelectionScrollMouseMove);
                   $(document).bind('mouseup.jScrollPaneDragging',   onSelectScrollMouseUp);
                  
                }
                
                var textDragDistanceAway;
                var textSelectionInterval;
                
                function onTextSelectionInterval()
                {
                    direction = textDragDistanceAway < 0 ? -1 : 1;
                    $this[0].scrollBy(textDragDistanceAway / 2);
                }

                function clearTextSelectionInterval()
                {
                    if (textSelectionInterval) {
                        clearInterval(textSelectionInterval);
                        textSelectionInterval = undefined;
                    }
                }
                
                function onTextSelectionScrollMouseMove(e)
                {
                    var offset = $this.parent().offset().top;
                    var maxOffset = offset + paneHeight;
                    var mouseOffset = getPos(e, 'Y');
                    textDragDistanceAway = mouseOffset < offset ? mouseOffset - offset : (mouseOffset > maxOffset ? mouseOffset - maxOffset : 0);
                    if (textDragDistanceAway == 0) {
                        clearTextSelectionInterval();
                    } else {
                        if (!textSelectionInterval) {
                            textSelectionInterval  = setInterval(onTextSelectionInterval, 100);
                        }
                    }
                }

                function onSelectScrollMouseUp(e)
                {
                   $(document)
                      .unbind('mousemove.jScrollPaneDragging')
                      .unbind('mouseup.jScrollPaneDragging');
                   clearTextSelectionInterval();
                }

                $container.bind('mousedown.jScrollPane', onSelectScrollMouseDown);

                
                $.jScrollPane.active.push($this[0]);
                
            } else {
                $this.css(
                    {
                        'height':paneHeight+'px',
                        'width':paneWidth-this.originalSidePaddingTotal+'px',
                        'padding':this.originalPadding
                    }
                );
                $this[0].scrollTo = $this[0].scrollBy = function() {};
                // clean up listeners
                $this.parent().unbind('mousewheel').unbind('mousedown.jScrollPane').unbind('keydown.jscrollpane').unbind('keyup.jscrollpane');
            }
            
        }
    )
};

$.fn.jScrollPaneRemove = function()
{
    $(this).each(function()
    {
        $this = $(this);
        var $c = $this.parent();
        if ($c.is('.jScrollPaneContainer')) {
            $this.css(
                {
                    'top':'',
                    'height':'',
                    'width':'',
                    'padding':'',
                    'overflow':'',
                    'position':''
                }
            );
            $this.attr('style', $this.data('originalStyleTag'));
            $c.after($this).remove();
        }
    });
}

$.fn.jScrollPane.defaults = {
    scrollbarWidth : 10,
    scrollbarMargin : 5,
    wheelSpeed : 18,
    showArrows : false,
    arrowSize : 0,
    animateTo : false,
    dragMinHeight : 1,
    dragMaxHeight : 99999,
    animateInterval : 100,
    animateStep: 3,
    maintainPosition: true,
    scrollbarOnLeft: false,
    reinitialiseOnImageLoad: false,
    tabIndex : 0,
    enableKeyboardNavigation: true,
    animateToInternalLinks: false,
    topCapHeight: 0,
    bottomCapHeight: 0,
    observeHash: true
};

// clean up the scrollTo expandos
$(window)
    .bind('unload', function() {
        var els = $.jScrollPane.active; 
        for (var i=0; i<els.length; i++) {
            els[i].scrollTo = els[i].scrollBy = null;
        }
    }
);

})(jQuery);
//------------------------jq.mouseweel.min.js---------------------------------
/* Copyright (c) 2009 Brandon Aaron (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.
 *
 * Version: 3.0.2
 * 
 * Requires: 1.2.2+
 */
(function(c){var a=["DOMMouseScroll","mousewheel"];c.event.special.mousewheel={setup:function(){if(this.addEventListener){for(var d=a.length;d;){this.addEventListener(a[--d],b,false)}}else{this.onmousewheel=b}},teardown:function(){if(this.removeEventListener){for(var d=a.length;d;){this.removeEventListener(a[--d],b,false)}}else{this.onmousewheel=null}}};c.fn.extend({mousewheel:function(d){return d?this.bind("mousewheel",d):this.trigger("mousewheel")},unmousewheel:function(d){return this.unbind("mousewheel",d)}});function b(f){var d=[].slice.call(arguments,1),g=0,e=true;f=c.event.fix(f||window.event);f.type="mousewheel";if(f.wheelDelta){g=f.wheelDelta/120}if(f.detail){g=-f.detail/3}d.unshift(f,g);return c.event.handle.apply(this,d)}})(jQuery);
//------------------------jq.colorbox.min.js----------------------------------
/*    ColorBox v1.3.2 - a full featured, light-weight, customizable lightbox based on jQuery 1.3 */
(function(z){var p="colorbox",n="hover",v=true,O=false,U,l=!z.support.opacity,Q=l&&!window.XMLHttpRequest,T="click.colorbox",w="cbox_open",I="cbox_load",s="cbox_complete",H="cbox_cleanup",m="cbox_closed",L="resize.cbox_resize",E,R,S,d,x,i,b,D,c,M,B,f,q,h,k,J,j,G,r,V,g,e,a,o,y,N,u,K,F,A={transition:"elastic",speed:350,width:O,height:O,innerWidth:O,innerHeight:O,initialWidth:"400",initialHeight:"400",maxWidth:O,maxHeight:O,scalePhotos:v,scrolling:v,inline:O,html:O,iframe:O,photo:O,href:O,title:O,rel:O,opacity:0.6,preloading:v,current:"image {current} of {total}",previous:"previous",next:"next",close:"close",open:O,overlayClose:v,slideshow:O,slideshowAuto:v,slideshowSpeed:2500,slideshowStart:"start slideshow",slideshowStop:"stop slideshow",preloadIMG:v};function C(W,X){X=X==="x"?document.documentElement.clientWidth:document.documentElement.clientHeight;return(typeof W==="string")?Math.round((W.match(/%/)?(X/100)*parseInt(W,10):parseInt(W,10))):W}function t(W){return N.photo||W.match(/\.(gif|png|jpg|jpeg|bmp)(?:\?([^#]*))?(?:#(\.*))?$/i)}function P(){for(var W in N){if(typeof(N[W])==="function"){N[W]=N[W].call(o)}}}U=z.fn.colorbox=function(X,W){if(this.length){this.each(function(){var Y=z(this).data(p)?z.extend({},z(this).data(p),X):z.extend({},A,X);z(this).data(p,Y).addClass("cboxelement")})}else{z(this).data(p,z.extend({},A,X))}z(this).unbind(T).bind(T,function(Z){o=this;N=z(o).data(p);P();F=W||O;var Y=N.rel||o.rel;if(Y&&Y!=="nofollow"){c=z(".cboxelement").filter(function(){var aa=z(this).data(p).rel||this.rel;return(aa===Y)});y=c.index(o);if(y<0){c=c.add(o);y=c.length-1}}else{c=z(o);y=0}if(!u){u=v;K=v;z().bind("keydown.cbox_close",function(aa){if(aa.keyCode===27){aa.preventDefault();U.close()}}).bind("keydown.cbox_arrows",function(aa){if(aa.keyCode===37){aa.preventDefault();G.click()}else{if(aa.keyCode===39){aa.preventDefault();j.click()}}});if(N.overlayClose){E.css({cursor:"pointer"}).one("click",U.close)}o.blur();z.event.trigger(w);r.html(N.close);E.css({opacity:N.opacity}).show();N.w=C(N.initialWidth,"x");N.h=C(N.initialHeight,"y");U.position(0);if(Q){M.bind("resize.cboxie6 scroll.cboxie6",function(){E.css({width:M.width(),height:M.height(),top:M.scrollTop(),left:M.scrollLeft()})}).trigger("scroll.cboxie6")}}U.slideshow();U.load();Z.preventDefault()});if(X&&X.open){z(this).triggerHandler(T)}return this};U.init=function(){function W(X){return z('<div id="cbox'+X+'"/>')}M=z(window);R=z('<div id="colorbox"/>');E=W("Overlay").hide();S=W("Wrapper");d=W("Content").append(B=W("LoadedContent").css({width:0,height:0}),f=W("LoadingOverlay"),q=W("LoadingGraphic"),h=W("Title"),k=W("Current"),J=W("Slideshow"),j=W("Next"),G=W("Previous"),r=W("Close"));S.append(z("<div/>").append(W("TopLeft"),x=W("TopCenter"),W("TopRight")),z("<div/>").append(i=W("MiddleLeft"),d,b=W("MiddleRight")),z("<div/>").append(W("BottomLeft"),D=W("BottomCenter"),W("BottomRight"))).children().children().css({"float":"left"});z("body").prepend(E,R.append(S));if(l){R.addClass("cboxIE");if(Q){E.css("position","absolute")}}d.children().addClass(n).mouseover(function(){z(this).addClass(n)}).mouseout(function(){z(this).removeClass(n)}).hide();V=x.height()+D.height()+d.outerHeight(v)-d.height();g=i.width()+b.width()+d.outerWidth(v)-d.width();e=B.outerHeight(v);a=B.outerWidth(v);R.css({"padding-bottom":V,"padding-right":g}).hide();j.click(U.next);G.click(U.prev);r.click(U.close);d.children().removeClass(n)};U.position=function(ab,Y){var aa,X=document.documentElement.clientHeight,Z=Math.max(X-N.h-e-V,0)/2+M.scrollTop(),W=Math.max(document.documentElement.clientWidth-N.w-a-g,0)/2+M.scrollLeft();aa=(R.width()===N.w+a&&R.height()===N.h+e)?0:ab;S[0].style.width=S[0].style.height="9999px";function ac(ad){x[0].style.width=D[0].style.width=d[0].style.width=ad.style.width;q[0].style.height=f[0].style.height=d[0].style.height=i[0].style.height=b[0].style.height=ad.style.height}R.dequeue().animate({width:N.w+a,height:N.h+e,top:Z,left:W},{duration:aa,complete:function(){ac(this);K=O;S[0].style.width=(N.w+a+g)+"px";S[0].style.height=(N.h+e+V)+"px";if(Y){Y()}},step:function(){ac(this)}})};U.resize=function(aa){if(!u){return}var ab,Z,X,ad,ah,W,af,Y=N.transition==="none"?0:N.speed;M.unbind(L);if(!aa){af=setTimeout(function(){var ai=B.wrapInner("<div style='overflow:auto'></div>").children();N.h=ai.height();B.css({height:N.h});ai.replaceWith(ai.children());U.position(Y)},1);return}B.remove();B=z('<div id="cboxLoadedContent"/>').html(aa);function ae(){N.w=N.w||B.width();return N.w}function ac(){N.h=N.h||B.height();return N.h}B.hide().appendTo(E).css({width:ae(),overflow:N.scrolling?"auto":"hidden"}).css({height:ac()}).prependTo(d);z("#cboxPhoto").css({cssFloat:"none"});if(Q){z("select:not(#colorbox select)").filter(function(){return this.style.visibility!=="hidden"}).css({visibility:"hidden"}).one(H,function(){this.style.visibility="inherit"})}function ag(ai){U.position(ai,function(){if(!u){return}if(l){if(W){B.fadeIn(100)}R[0].style.removeAttribute("filter")}d.children().show();if(N.iframe){B.append("<iframe id='cboxIframe'"+(N.scrolling?" ":"scrolling='no'")+" name='iframe_"+new Date().getTime()+"' frameborder=0 src='"+(N.href||o.href)+"' />")}f.hide();q.hide();J.hide();if(c.length>1){k.html(N.current.replace(/\{current\}/,y+1).replace(/\{total\}/,c.length));j.html(N.next);G.html(N.previous);if(N.slideshow){J.show()}}else{k.hide();j.hide();G.hide()}h.html(N.title||o.title);z.event.trigger(s);if(F){F.call(o)}if(N.transition==="fade"){R.fadeTo(Y,1,function(){if(l){R[0].style.removeAttribute("filter")}})}M.bind(L,function(){U.position(0)})})}if((N.transition==="fade"&&R.fadeTo(Y,0,function(){ag(0)}))||ag(Y)){}if(N.preloading&&c.length>1){Z=y>0?c[y-1]:c[c.length-1];ad=y<c.length-1?c[y+1]:c[0];ah=z(ad).data(p).href||ad.href;X=z(Z).data(p).href||Z.href;if(t(ah)){z("<img />").attr("src",ah)}if(t(X)){z("<img />").attr("src",X)}}};U.load=function(){var X,W,aa,Z=U.resize;K=v;function Y(ad){var ac=z(ad),ae=ac.find("img"),ab=ae.length;(function af(){var ag=new Image();ab=ab-1;if(ab>=0&&N.preloadIMG){ag.onload=af;ag.src=ae[ab].src}else{Z(ac)}}())}o=c[y];N=z(o).data(p);P();z.event.trigger(I);N.h=N.height?C(N.height,"y")-e-V:N.innerHeight?C(N.innerHeight,"y"):O;N.w=N.width?C(N.width,"x")-a-g:N.innerWidth?C(N.innerWidth,"x"):O;N.mw=N.w;N.mh=N.h;if(N.maxWidth){N.mw=C(N.maxWidth,"x")-a-g;N.mw=N.w&&N.w<N.mw?N.w:N.mw}if(N.maxHeight){N.mh=C(N.maxHeight,"y")-e-V;N.mh=N.h&&N.h<N.mh?N.h:N.mh}X=N.href||o.href;f.show();q.show();r.show();if(N.inline){z('<div id="cboxInlineTemp" />').hide().insertBefore(z(X)[0]).bind(I+" "+H,function(){z(this).replaceWith(B.children())});Z(z(X))}else{if(N.iframe){Z(" ")}else{if(N.html){Y(N.html)}else{if(t(X)){W=new Image();W.onload=function(){var ab;W.onload=null;W.id="cboxPhoto";z(W).css({margin:"auto",border:"none",display:"block",cssFloat:"left"});if(N.scalePhotos){aa=function(){W.height-=W.height*ab;W.width-=W.width*ab};if(N.mw&&W.width>N.mw){ab=(W.width-N.mw)/W.width;aa()}if(N.mh&&W.height>N.mh){ab=(W.height-N.mh)/W.height;aa()}}if(N.h){W.style.marginTop=Math.max(N.h-W.height,0)/2+"px"}Z(W);if(c.length>1){z(W).css({cursor:"pointer"}).click(U.next)}if(l){W.style.msInterpolationMode="bicubic"}};W.src=X}else{z("<div />").load(X,function(ab,ac){if(ac==="success"){Y(this)}else{Z(z("<p>Request unsuccessful.</p>"))}})}}}}};U.next=function(){if(!K){y=y<c.length-1?y+1:0;U.load()}};U.prev=function(){if(!K){y=y>0?y-1:c.length-1;U.load()}};U.slideshow=function(){var X,W,Y="cboxSlideshow_";J.bind(m,function(){J.unbind();clearTimeout(W);R.removeClass(Y+"off "+Y+"on")});function Z(){J.text(N.slideshowStop).bind(s,function(){W=setTimeout(U.next,N.slideshowSpeed)}).bind(I,function(){clearTimeout(W)}).one("click",function(){X();z(this).removeClass(n)});R.removeClass(Y+"off").addClass(Y+"on")}X=function(){clearTimeout(W);J.text(N.slideshowStart).unbind(s+" "+I).one("click",function(){Z();W=setTimeout(U.next,N.slideshowSpeed);z(this).removeClass(n)});R.removeClass(Y+"on").addClass(Y+"off")};if(N.slideshow&&c.length>1){if(N.slideshowAuto){Z()}else{X()}}};U.close=function(){z.event.trigger(H);u=O;z().unbind("keydown.cbox_close keydown.cbox_arrows");M.unbind(L+" resize.cboxie6 scroll.cboxie6");E.css({cursor:"auto"}).fadeOut("fast");R.stop(v,O).fadeOut("fast",function(){B.remove();R.css({opacity:1});d.children().hide();z.event.trigger(m)})};U.element=function(){return o};U.settings=A;z(U.init)}(jQuery));

//------------------------jq.cookie.js----------------------------------------
/**
 * 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
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
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;
    }
};
//------------------------jq.history.js---------------------------------------
/*
 * 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 {
            if(typeof(jQuery.historyCallback) == "function")
                jQuery.historyCallback(hash, true);
        }
    }
});


//---------------------------------------------------------------
var debug = 0;//parseInt(document.location.href.indexOf('1') > 0);
var _img = 'http://i.fast.trevicards.com/i/';
var _mp3 = 'http://i.fast.trevicards.com/i/mp3/';
var cat = [];
cat[74]="birthdays";
cat[86]="baby";
cat[87]="wedding";
cat[88]="anniversary";
cat[93]="care-and-concerns";
cat[291]="kalashnikov-e-cards";
cat[295]="tretyakov-gallery";
cat[89]="animated_e-cards";
cat[296]="christmas";
cat[297]="new_year";
cat[298]="valentine_day";
cat[299]="easter";
cat[300]="mothers_day";
cat[301]="fathers_day";
cat[302]="halloween";
cat[303]="thanksgiving";
cat[304]="birthdays";
cat[305]="baby_ecards";
cat[306]="weddings";
cat[307]="anniversary";
cat[308]="famous_people";
cat[309]="care_and_concern";
cat[294]="free-fine-art-cards";
cat[286]="christmas";
cat[277]="new_year";
cat[276]="valentine";
cat[275]="easter";
cat[288]="mothers_day";
cat[287]="fathers_day";
cat[289]="thanksgiving";
cat[285]="holidays";
cat[305]="baby_e-cards";
cat[302]="halloween";
cat[90]="animated_e-cards";
cat[310]="animated_e-cards";
cat[1002]="free-fine-art-cards";
if (document.location.host == "trevicards" + ".klik") {
    debug = 1;
} else if (document.location.host == "fast." + "trevicards" + ".wlad") {
    debug = 1;
    _img = 'http://i.trevicards.wlad/i/';
} else if (document.location.host == "tc" + ".com") {
    debug = 1;
}
fc = 0;
//(new Image()).src=_img +"i/suka.gif";

function hideIndexPanel() {
    $('#send-btn, #btnPreview, #music, #planner, #btnCC, #btnMembers').hide();
    showFrameSlider();
}

function showFrameSlider()
{
    $('#demoFrameSlider').show();
    makeScrollable("div.sc_menu_wrapper", "div.sc_menu");
}


function makeScrollable(wrapper, scrollable){
    // Получаем элементы jQuery
    var wrapper = $(wrapper), scrollable = $(scrollable);
    // Скрываем изображения, пока они не загружены
    scrollable.hide();
    var loading = $('<div class="loading">Загрузка...</div>').appendTo(wrapper);
    // Запускаем фукнцию, которая проверяет загрузку всех изображений
    var interval = setInterval(function(){
        var images = scrollable.find('img');
        var completed = 0;
        // Подсчитываем количество загруженных изображений
        images.each(function(){
            if (this.complete) completed++;    
        });
        if (completed == images.length){
            clearInterval(interval);
            // Таймаут добавлен для устранения проблем с Chrome
            setTimeout(function(){
                loading.hide();
                // Удаляем полоску прокрутки
                wrapper.css({overflow: 'hidden'});                        
                scrollable.slideDown('slow', function(){
                    enable();    
                });                    
            }, 1000);    
        }
    }, 100);
    function enable(){
        // Высота области вверху и внизу, в которой нет реакции на перtмещение курсора мыши
        var inactiveMargin = 99;                    
        // Кэшируем параметры для повышения производительности
        var wrapperWidth = wrapper.width();
        var wrapperHeight = wrapper.height();
        // Используем наружнeю высоту для включения отступов
        var scrollableHeight = scrollable.outerHeight() + 2*inactiveMargin;
        // Не будем кэшировать wrapperOffset, так как она поменяется при измении окна просмотра
        // Можно использовать событие onresize, но овчинка не стоит выделки
        // var wrapperOffset = wrapper.offset();
        // Создаем невидимую подсказку
        var tooltip = $('<div class="sc_menu_tooltip"></div>')
            .css('opacity', 0)
            .appendTo(wrapper);
        // Сохраняем заголовки меню
        scrollable.find('a').each(function(){                
            $(this).data('tooltipText', this.title);                
        });
        // Удаляем подсказки по умолчанию
        scrollable.find('a').removeAttr('title');        
        // Удаляем подсказки по умолчанию в IE
        scrollable.find('img').removeAttr('alt');    
        var lastTarget;
        //Когда пользователь перемещает курсор мыши по меню
        wrapper.mousemove(function(e){
            // Сохраняем цель
            lastTarget = e.target;
            var wrapperOffset = wrapper.offset();
            var tooltipLeft = e.pageX - wrapperOffset.left;
            // Не даем подсказке выходить за рамки меню.
            // Так как свойство overflow имеет значение hidden, мы не сможем их увидеть. 
            tooltipLeft = Math.min(tooltipLeft, wrapperWidth - 75);
            var tooltipTop = e.pageY - wrapperOffset.top + wrapper.scrollTop() - 40;
            // Перемещаем подсказку под курсор мыши, когда мы находимся в верхней части меню
            if (e.pageY - wrapperOffset.top < wrapperHeight/2){
                tooltipTop += 80;
            }                
            tooltip.css({top: tooltipTop, left: tooltipLeft});                
            // Прокручиваем меню
            var top = (e.pageY -  wrapperOffset.top) * (scrollableHeight - wrapperHeight) / wrapperHeight - inactiveMargin;
            if (top < 0){
                top = 0;
            }            
            wrapper.scrollTop(top);
        });

        

        // Устанавливаем интервал, который помогает решить проблему производительтности в IE

        var interval = setInterval(function(){
            if (!lastTarget) return;    
            var currentText = tooltip.text();
            if (lastTarget.nodeName == 'IMG'){                    
                // Данные привязываются к ссылке, а не к изображению
                var newText = $(lastTarget).parent().data('tooltipText');
                // Выводим подсказку с новым текстом
                if (currentText != newText) {
                    tooltip
                        .stop(true)
                        .css('opacity', 0)    
                        .text(newText)
                        .animate({opacity: 1}, 1000);
                }                    
            }
        }, 200);

        

        // Скрываем подсказку, когда курсор мыши покидает меню
        wrapper.mouseleave(function(){
            lastTarget = false;
            tooltip.stop(true).css('opacity', 0).text('');

        });            
        
    }
}


$(document).ready(function() {
    if (debug) {
        $("#potatoCont").css( {
            display : "none"
        });
        $("#body").css( {
            top : "32px"
        });
    }

    Main.init();
    $.historyInit(historyCall);

    $("#logo").click(function() {
        document.location = "http://trevimedia.net";
    });

    $(document).keypress(function(e) {
        if (e.keyCode == 27 && !$(".vk_overlay").hasClass('vk_h')) {
            VK_container = null;
            VK_hide();
            return false;
        }
    }).mousedown(function() {
        if ($("#colorpicker").length && !$("#colorpicker").hasClass('vk_h'))
            tm_colorPicker = setTimeout(colorPicker_hide, 200);
    });
    $("#cover").dropdown( {
        onchange : function(val, el) {
            $("#cover").find("dt a").css( {
                backgroundImage : el.style.backgroundImage
            });
            Card.Cover.Set(el.style.backgroundImage.replace(/.+_([a-z]+)\.gif.+/, "$1"));
        }
    });
    
   
    
    $("#rcat").dropdown( {
        onchange : function(val) {
        $item=$("#menuxml"+" item[tid=" +val+ "]");
        if(($('#menu').attr('rel')==1 || $('#menu').attr('rel')==4 || $('#menu').attr('rel')==9 || !$('#menu').attr('rel')) && !$item.attr('pid'))
            Menu.init(0);
        $('#rcat2 dt span').html('Select Category');
        val=$('#rcat dt span .v').html();
        setCookie("rib_val",val);
        Ribbon.flag=1;
        Ribbon.chcategory(val);
        
        /*
            if (fc)
            {
                Ribbon.chcategory(val);
            }
            else
            {
                fc = 1;
            }
            */
        }
    });
    
    $("#rcat2").dropdown( {
        onchange : function(val) {
        
        $item = $("item[tid=" +val+ "]", '#menuxml');
        if($item.attr('pid')==4 && $('#menu').attr('rel')!=4)
            Menu.init(4);
        if($item.attr('pid')==9 && $('#menu').attr('rel')!=9)
            Menu.init(9);
        $("#text").removeClass('calendar');
        $("#btnCC").removeClass('btnCC');
        $('#rcat dt span').html('Select Category');
            if(parseInt($('#menu').attr('rel')))
            {
                
                setCookie("rib_id",$('#rcat2 dt span .v').html());
                if($('#rcat2 dt span .v').html()==89)
                {
                    Menu.flag=true;
                    Menu.init(0);
                }    
            }    
                
            if(parseInt($('#menu').attr('rel')))
                if((parseInt($('#menu').attr('rel')) !=9 && val!=89))
                {
                //    Menu.init(9);
                }
                else 
                    val2=$('#rcat2 dt span .v').html();
                    Ribbon.flag=1;
                    setCookie("rib_val",val);
                    if($.cookie("id_session")) 
                    {
                        Ribbon.chcategory($('#rcat2 dt span .v').html());//propusk zagruzki lenty
                    }
                    
            }
    });
    
    $("#y_year, #m_year").dropdown( {
        onchange : function(val) {
            Calendar.y = val;
            Calendar.UpdateImage();
        }
    });
    $("#m_month").dropdown( {
        onchange : function(val) {
            Calendar.m = val;
            Calendar.UpdateImage();
        }
    }).removeAttr("style");
    $("#c_layout").dropdown( {
        onchange : function(val) {
            Calendar.layout = val;
            Calendar.UpdateImage();
        }
    });
    $("#c_color").dropdown( {
        onchange : function(val) {
            Calendar.color = val;
            Calendar.UpdateImage();
        }
    });
    $("#dd_music").dropdown( {
        onchange : function(val) {
            if(Card.flag==true)
            return;
            if (val) {
                $id("swfsnd").playSound(_mp3 + val);
            } else {
                $id("swfsnd").stopSound();
            }
            Card.SetMusic(val);
        }
    });
    $("#text_block_cont").jScrollPane( {
        showArrows : true
    });

    $("#ribbon").click(function(){
        
    });
    $('#main_but').click(function(){
        if($(this).find('.mcont').html()=='Animated cards')
        {
            $(this).find('.mcont').html('Still Images');
            Menu.init(9);
            setCookie("rib_id",89);
            Ribbon.chcategory(89);
            $("#text").removeClass('calendar');            
            $("#btnCC").removeClass('btnCC');
    
        }
        else
        {
            $(this).find('.mcont').html('Animated cards');
            $id('swfpageflip').stop_video();
            Menu.init(0);
            $('#menu').attr('rel',-1);
            setCookie("rib_id",295);
            Ribbon.chcategory(295);
        
        }    
    });
    
});


function getCookie(name)
    {
      //  alert(document.cookie);
    var cookie = " " + document.cookie;
    var search = " " + name + "=";
    var setStr = null;
    var offset = 0;
    var end = 0;
    if (cookie.length > 0) {
        offset = cookie.indexOf(search);
        if (offset != -1) {
            offset += search.length;
            end = cookie.indexOf(";", offset)
            if (end == -1) {
                end = cookie.length;
            }
            setStr = unescape(cookie.substring(offset, end));
        }
    }
        
    return(setStr);
    }

function setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}


function moveP() {
    
}
checkCard = function() {

    if ($id('swfpageflip') && typeof ($id('swfpageflip').getCardInfo) == "function") {
        if (!Card.fl_cardInit) {
            loadSWF("puppet", "man_small.swf?" + Math.random(), 189, 930, "swfpuppet");
            
        
        /*    setTimeout(function(){
                
                {
                    $id("swfpuppet").movehand('2-3');
                    
                }
            },6000);*/
            Card.fl_cardInit = true;
            Card.Init();
            Ribbon.init();
            TextControls.Init();
            setTimeout("rotate()", 10000);
            setInterval("rotate();", 25000);
            $("#mli89").click();
        }
        var state = $id('swfpageflip').getCardInfo().toString();
        Card.flipping = state.substr(0, 1);
        Card.page = state.substr(1, 1);
        Card.Update();
    }
};

function historyCall(hash, sl) {
    
    if (hash) {
        var data = Main.historyStock[hash];
        //console.log(data);
        $item = $("item[tid=" +data[0]+ "]", '#menuxml');
        if (!sl)
    {
            
        switch($item.attr('pid'))
        {
            case '1':
                Menu.init(1);
                break;
            case '4':
                Menu.init(4);
            break;
            case '9':
                Menu.init(9);
            break;
            default:
                if(data[0]==89)
                {
                    Menu.init(9);
                    break;
                }
                Menu.init(0);
            break;
        }
            Ribbon.chcategory(data[0], data[1], data[2], 1);    
    }
    return false;
} else {
    // Fp
    Menu.init(0);
}
};

var Main = {

    fcsid : null,

    historyStock : [],
    historyStockI : 0,

    set_sid : function(sid) {
        if ($.cookie("OWN_SID")) {
            OrderCard.sid = $.cookie("OWN_SID");
        } else {
            var date = new Date();
            date.setTime(date.getTime() + (2 * 60 * 60 * 1000));
            $.cookie("OWN_SID", OrderCard.sid = sid, {
                path : '/',
                expires : date
            });
        }
    },

    restoreSession : function() {
        $.pget("/proc/render/restore_session", {
            sid : $.cookie("FCSID") && $.cookie("FCSID").length == 32 ? $.cookie("FCSID") : "12345678901234567890123456789012"
        }, function(d) {
            try {
                eval(d);
            } catch (e) {
                return;
            }
            if (typeof (Card.Last) == "object") {

                Main.fcsid = Card.Last["fcsid"];

                Main.loadAuthBlock();
                $("#btnPreview").attr("href", "/preview/" + Main.fcsid);

                $.fn.media.defaults.flashVersion = "10";
                $.fn.media.defaults.bgColor = "";
                loadSWF("pageflip", "pageflip_loader.swf?fcsid=" + Main.fcsid + "&_r=" + Math.random(), 671, 533);
            }
        });
    },

    loadAuthBlock : function() {
        // Load Auth Block
        $.pget('/proc/login/load_form?fcsid=' + Main.fcsid, null, function(data) {

            if (data) {
                $('#authCont').html(data);
                Registration.init();
            }
        });
    },

    historyAdd : function(cid, id, item_id) {
        if(cid=='sub')
        {    
            //hurl = "animated_e-cards";
        }
        else
        hurl = cat[cid];
        //    console.log(hurl);
        Main.historyStock[hurl] =
            [
                           cid,
                           id,
                           item_id
             ];
        $.historyLoad(hurl, true);
        //console.log(Main.historyStock[hurl]);
        Main.historyStockI++;
    },

    init : function() {
        Main.restoreSession();
        $.fn.media.defaults.flashVersion = "10";
        $.fn.media.defaults.bgColor = "";
        $item=$("#menuxml"+" item[tid=" + $.cookie("rib_id")+ "]");
        Menu.init(0);
        if($item.attr('pid')==1)
        {
            Menu.init(1);
        }
        else if($item.attr('pid')==9)
        {
            Menu.init(9);
        }
        else if($item.attr('pid')==4)
        {
            Menu.init(4);
        }
        else 
        {
            Menu.init(9);
        }
        loadSWF("logo", "logo.swf?" + Math.random(), 300, 97);
        loadSWF("snd", "snd.swf?" + Math.random(), 64, 25);

        if (debug) {
            loadSWF("card", "card_vector.swf", 510, 480, "swfcard");
            Interface.bodyWentBottom = 1;
            tm_checkCard = setInterval("checkCard()", 50);
        }

        $("#drag").draggable( {
            helper : "clone",
            start : function(event) {

            }
        });

    }
};

var Ribbon = 
{
    blocked : false,
    thWidth : 86,
    thHeight : 126,
    ids : [],
    otimer : null,
    flag:0,
    fl:0,
    load:false,
    scrollOn : 3,
    leftIndex : 1,
    rightIndex : 8,
    cid : 89,

    init : function() 
    {

        Ribbon.makeDraggable();
        $("#rArrLeft, #rArrRight").mouseover(function() {
            $(this).addClass("hover");
        }).mouseout(function() {
            $(this).removeClass("hover");
        });
        $("#rArrRight").click(function() {
            Ribbon.left();
        });
        $("#rArrLeft").click(function() {
            Ribbon.right();
        });

        Ribbon.cid = $.cookie("ribbon_cid");
    },

    chcategory : function(cid, id, this_id, nohis) {
        
        if(cid==89)
            Ribbon.flag=0;
            
//        debugger;
        if (id) {
            $item = $("item[id=" + this_id + "]", Menu.xml);
            
            // --
            cid = cid ? cid : $item.attr('tid');
            setCookie("rib_id",cid);
            //debugger;
            Interface.movePuppet(id, this_id);
            
            name = $item.attr('name');
            if((parseInt($item.attr('pid')) == 9) || ($item.attr('tid') == 89) || (parseInt($item.attr('pid')) == 4))
            {           
                $("#text").removeClass('calendar');
                $('#rcat dt span').html('Select Category');
                $('#rcat2 dt span').html(name);
            } else {
                $('#rcat dt span').html(name);
                $('#rcat2 dt span').html('Select Category');
            }
            
            // --
        } else {
            //$item = $("item[tid=" + cid + "]", Menu.xml);
            if(Ribbon.flag==1)
                setCookie("rib_id",cid);
            $item = $("item[tid=" + $.cookie("rib_id")+ "]", Menu.xml);
            name=$item.attr('name');
            this_id = $item.attr('id');
            id = $item.attr('m');
            Interface.movePuppet(id, this_id);
            if((parseInt($item.attr('pid')) == 9) || ($item.attr('tid') == 89) || (parseInt($item.attr('pid')) == 4))
            {
                $("#text").removeClass('calendar');
                $('#rcat dt span').html('Select Category');
                $('#rcat2 dt span').html(name);
            } else {
                $('#rcat dt span').html(name);
                $('#rcat2 dt span').html('Select Category');
            }
        }
        if(Ribbon.flag==1)
            setCookie("rib_id",cid);
        if($item.length >1)
            $item = $($item[1]);
        var name = $item.attr('name');
        var alias_path = $item.attr('alias_path');
        
        
        var pid = $item.attr('pid');
        
        if(cid == 89)
        {
        //    Menu.init(0);
        }
        else {
        
        if((pid == undefined) && parseInt($('#menu').attr('rel')) != -1) {
        
            //Menu.init(0);
        }
        
        if((pid == 1) && (parseInt($('#menu').attr('rel')) !=1) ) {
            
            Menu.init(1);
        }
        }
        /*
        if(pid == 1 && parseInt($('#menu').attr('rel')) !=1 ) {
            Menu.init(1);
        } else 
        */
        
        /*
        else {
            if (this_id > 100) {
                Menu.menuid == 0 ? Menu.init(1) : false;
            } else {
                Menu.menuid == 1 ? Menu.init(0) : false;
            }
        }
        */
        //console.log('pid='+pid);
        if(pid)
            $('#menu').attr('rel', pid);
        else
        {
            $('#menu').attr('rel', -1);
            
        }
        

        if (!nohis) {
            Main.historyAdd(cid, id, this_id);
        }
        
        Ribbon.cid = cid;
        $.cookie("ribbon_cid", cid, {
            path : '/',
            expires : 20
        });

        Ribbon.leftIndex = 1;
        Ribbon.rightIndex = 8;
        Ribbon.thWidth = 86;
        Ribbon.ids = [];
        Ribbon.otimer = null;
    
        $("#ribbon #mask ul").css( {
            left : 0
        });

        if (!debug) {
            try {
                pageTracker._trackPageview("/" + alias_path + ".html");
            } catch (e) {
            }
        }
        if(Ribbon.flag==1)
        {
            setCookie("rib_id",$.cookie("rib_val"));
            
        }
        if($.cookie("rib_id")==90)
        setCookie("rib_id",89);
        $.pget("/proc/ribbon/load_list", {
            //cid : $.cookie("rib_id")
            cid : $.cookie("rib_id")
        }, function(d) {
            // alert(d);
                $("#ribbon #mask ul").html(d);
                if($.cookie("calendar")==1)
                {
                    swap_cal();
                    setCookie("calendar",0);
                }    
                Ribbon.init();
                
            });

        $.pget("/proc/render/get_content", {
            cid : "c" + $.cookie("rib_id")
        }, function(d) {
            $("#text_block_cont").html(d).jScrollPane( {
                showArrows : true
            });
        });
        Ribbon.flag=0;
        
    },

    left : function() {
        
        if (Ribbon.blocked)
            return;
        Ribbon.blocked = true;
        var start = $("#ribbon #mask li").length;
        if (start == Ribbon.rightIndex) {
            $.pget("/proc/ribbon/load_list", {
                cid : Ribbon.cid,
                start : start
            }, function(d) {
                if (/<li/.test(d)) {

                    $("#mask").css( {
                        overflow : "hidden"
                    });

                    var left = parseInt($("#ribbon #mask ul").css("left"));
                    var items = d.match(/<li/gi).length;
                    if (items > Ribbon.scrollOn) {
                        var arr = d.split("<li");
                        delete arr[Ribbon.scrollOn + 1];
                        d = arr.join("<li").replace(/<li$/, '');
                        items--;
                    } else {

                    }

                    Ribbon.rightIndex = start + items;
                    $("#ribbon #mask ul").append(d).animate( {
                        left : -(Ribbon.rightIndex - 8) * 89 - 1
                    }, "slow", "swing", function() {
                        Ribbon.makeDraggable();
                        $("#ribbon #mask li:lt(" + (Ribbon.rightIndex - 8) + ")").css( {
                            display : "none"
                        });
                        $("#mask").css( {
                            overflow : "visible"
                        });
                        Ribbon.blocked = false;
                    });
                } else {
                    Ribbon.blocked = false;
                }
            });
        } else {
            $("#mask").css( {
                overflow : "hidden"
            });
            var left = parseInt($("#ribbon #mask ul").css("left"));
            Ribbon.rightIndex += Ribbon.scrollOn;
            if (Ribbon.rightIndex > $("#ribbon #mask li").length)
                Ribbon.rightIndex = $("#ribbon #mask li").length;
            $("#ribbon #mask li:lt(" + (Ribbon.rightIndex) + ")").css( {
                display : "block"
            });
            $("#ribbon #mask ul").animate( {
                left : -(Ribbon.rightIndex - 8) * 89 - 1
            }, "slow", "swing", function() {

                $("#ribbon #mask li:lt(" + (Ribbon.rightIndex - 8) + ")").css( {
                    display : "none"
                });
                $("#mask").css( {
                    overflow : "visible"
                });
                Ribbon.blocked = false;
            });
        }
    },
    right : function() {
        if (Ribbon.blocked)
            return;
        Ribbon.blocked = true;
        $("#mask").css( {
            overflow : "hidden"
        });
        var left = parseInt($("#ribbon #mask ul").css("left"));
        left = left + 89 * Ribbon.scrollOn + 1;
        if (left > 1)
            left = 1;
        Ribbon.rightIndex -= Ribbon.scrollOn;
        if (Ribbon.rightIndex < 8)
            Ribbon.rightIndex = 8;
        $("#ribbon #mask li:lt(" + (Ribbon.rightIndex) + ")").css( {
            display : "block"
        });
        $("#ribbon #mask ul").animate( {
            left : left
        }, "slow", "swing", function() {

            $("#ribbon #mask li:gt(" + (Ribbon.rightIndex - 1) + ")").css( {
                display : "none"
            });
            $("#ribbon #mask li:lt(" + (Ribbon.rightIndex - 8) + ")").css( {
                display : "none"
            });
            $("#mask").css( {
                overflow : "visible"
            });
            Ribbon.blocked = false;
        });

    },
    removeOpacity : function() {
        if (Card.TitleImage.ID) {
            $("#p1_titleImage").animate( {
                opacity : 0
            }, "fast");
        } else {
            if(!Card.Video.Name) {
                $("#p1_titleImage").animate( {
                    opacity : 1
                }, "fast");
            }
        }
        $("#ribbon #mask li img[class!=img_dragging]").css( {
            opacity : 1
        });
    },
    makeDraggable : function() 
    {
        $img = $('#mask li img').not(".ui-draggable");

        if (true || this.cid != 89)
        {
            $img.draggable( {
                helper : "clone",
                start : function() {
                    $(this).addClass("img_dragging");
                },
                stop : function() {
                    $(this).removeClass("img_dragging").mouseout();
                }
            })
        }

        $img.click(function () {
            $("#p1_titleImage").animate( {
                opacity : 0
            }, "fast");
            if (this.src.indexOf('animate') !== -1) {
                if(typeof $id('swfpageflip').stop_video == 'function') {
                    $id('swfpageflip').stop_video();
                };
                flvname = this.src.match(/\/([^/]+)\.(jpg|gif|png)/)[1] + '.flv';
                flvname = flvname.replace(/[ ']+/g, '_').replace(/\%20/g, '_').replace(/\%27/g, '_');
                Card.Video.Set(flvname);
            } else if($("#text:first").hasClass('calendar')){
                Calendar.SetImage(this.id.replace("img", ""));

            } else {
                if(parseInt(Card.page) == 0) {
                    Card.TitleImage.ID = this.id.replace("img", "");
                    Card.Video.Name = null;
                    Card.flag=false;
                    
                    $id('swfpageflip').setFrameName('');
                    $.pget('/proc/render/set_title_image', {
                        id : Card.TitleImage.ID
                    }, function(d) {
                        $id('swfpageflip').render_title_image();
                            
                    });
                    

                } else {
                    alert("Please, drag`n`drop image\nto card");
                    return false;
                }
            }
            Card.SetCost();
        }).mouseover(function() {
            clearTimeout(Ribbon.otimer);
            $("#p1_titleImage").stop().animate( {
                opacity : 0.5
            }, "fast");
            Ribbon.ids[$(this).parent().attr("id")] = null;
            if (!$.browser.msie) {
                $("#ribbon #mask li img").css( {
                    opacity : 0.8
                });
                $(this).css( {
                    opacity : 1
                });
            }
            $(this).parent().css( {
                zIndex : 2
            });
            $(this).stop().css( {
                zIndex : 2
            }).animate( {
                left : -10,
                width : Ribbon.thWidth + 20,
                top : -10,
                height : Ribbon.thHeight + 20
            }, "fast", function() {
                clearTimeout(Ribbon.otimer);
            }).mouseout(function() {
                if ($(this).hasClass("img_dragging"))
                    return;
                $(this).parent().css( {
                    zIndex : 1
                });
                $(this).stop().animate( {
                    left : 0,
                    width : Ribbon.thWidth,
                    top : 0,
                    height : Ribbon.thHeight
                }, "fast", function() {
                    delete Ribbon.ids[$(this).parent().attr("id")];
                    if (Ribbon.ids.length == 0) {
                        clearTimeout(Ribbon.otimer);
                        Ribbon.otimer = setTimeout(Ribbon.removeOpacity, 300);
                    }
                });
            });
        }).mouseout(function(){
            $("#p1_titleImage").stop().animate( {
                opacity : 0
            }, "fast");
        });
    }
};

var Interface = {

    paths : [
            "one",
            "1-2",
            "2-4",
            "4-3",
            "3-5",
            "5-3",
            "3-4",
            "4-1",
            "1-5"
    ],
    // Координаты расположения человечка 103
    menuPoints : [
            -417, //-314,
            -372, //-269,
            -323, //-220,
            -313, //-210,
            -267, //-164,
            -220, //-117,
            -208, //-105,
            -163, //-60,
            -147, //-18,
            -115, //-12,
            135,  //32,
            173,  //70,
            213,  //110,
            253   //150
    ],
    currStep : 1,
    useColor : "textTitleColor",
    bgCat : [],
    titleCat : [],
    selected : false,
    tid : 0,
    checkPotatoTimer : null,
    bodyWentBottom : 0,
    imageFlowData : "",
    isJavaVMChecked : false,

    checkPotato : function() {
        
        
        if (typeof ($id('swfpotato').getOffset) == "function") {
            var n = $id('swfpotato').getOffset();
            
            if (n == 0) {
                $("#body").stop();
                $("#lace").html("").createAppend('img', {
                    src : _img + 'nitka.gif',
                    width : 10,
                    height : 80
                });
            }
            if (!Interface.bodyWentBottom)
                
                $id("body").style.top = (-662 + n) + "px";

            if (n == 470 && (Interface.bodyWentBottom == 0)) {
                    
                setTimeout("Interface.moveBodyBottom()", 6000);
                Interface.bodyWentBottom = 1;
            }
            if (n == -1) {
                clearInterval(Interface.checkPotatoTimer);
                Interface.truncatePotato();
            }
        }
    },

    initPuppet : function() {
        $("#puppet").animate( {
            top : Interface.menuPoints[0]
        }, 300);
    },

    movePuppet : function(id, menuid) {
        id = parseInt(id);
        var from = Interface.currStep;
        var way = "1-5";
        switch (true) {
        case id <= 2:
            way = "one";
            break;
        case id <= 5:
            way = "1-2";
            break;
        case id <= 8:
            way = "2-3";
            break;
        case id <= 11:
            way = "1-5";
            break;
        default:
            break;
        }
        
        try {
            if(typeof($id("swfpuppet").movehand) == "function")
            {
                $id("swfpuppet").movehand(way);
                
            }
        } catch (e) {

        }

        $("#puppet").animate( {
            top : Interface.menuPoints[id]
        }, 300, function() {
            return false;
        });
        Interface.currStep = id;
    },

    movePuppetDown : function() {
        $id("swfpuppet").movehand("1-5");
        $("#puppet").animate( {
            top : -25
        }, "slow", function(){Interface.bodyWentBottom = 1;});
    },

    shakePuppet : function() {
        var top = -Math.floor(Math.random() * 280);
        var uptime = 300 + Math.floor(Math.random() * 500);
        $("#puppet").animate( {
            top : top
        }, uptime);
    },

    moveBodyBottom : function() {
        $(".body").animate( {
            top : 0
        }, 300);
        $("#lace").remove();
    },

    deleteFirstPotato : function() {
        $("#potato").css( {
            left : "1128px",
            width : "135px",
            top : "832px",
            height : "160px"
        });
        $("#potato").html("").createAppend('img', {
            src : _img + "potato_small.gif",
            width : 90,
            height : 116
        }).show();
    },

    truncatePotato : function() {
        Menu.check=true;
        Interface.checkPotato = function(){};
        $("#potatoCont").attr("class", "truncated");
        tm_checkCard = setInterval("checkCard()", 50);
    }
};

var tm_TitleText = null;
var Card = {
    page : null,
    flag:false,
    flipping : null,
    fl_cardInit : null,
    _prevState : {
        page : 0,
        flipping : 0
    },
    Init : function() {
        setTimeout("Card.Restore()", 2000);
    },
    Restore : function() {
        if ((typeof ($id("swfpageflip").render_title_text) == "function") && (typeof ($id("swfpageflip").render_inner_text_left) == "function") && (typeof ($id("swfpageflip").render_inner_text_right) == "function") && (typeof ($id("swfpageflip").render_bg_p1) == "function")
                && (typeof ($id("swfpageflip").render_bg_p2) == "function") && (typeof ($id("swfpageflip").render_bg_p3) == "function") && (typeof ($id("swfpageflip").render_bg_p4) == "function")) {
            if (Card.TitleText.Text = Card.Last.title_text) {
                Card.TitleText.Align = Card.Last.title_text_alignment;
                Card.TitleText.Color = Card.Last.title_text_color;
                Card.TitleText.Font = Card.Last.title_text_font;
                $id("swfpageflip").render_title_text();
            }
            if (Card.InnerTextLeft.Text = Card.Last.inner_text_left) {
                Card.InnerTextLeft.Align = Card.Last.inner_text_left_alignment;
                Card.InnerTextLeft.Font = Card.Last.inner_text_left_font;
                Card.InnerTextLeft.Color = Card.Last.inner_text_left_color;
                $id("swfpageflip").render_inner_text_left();
            }
            if (Card.InnerTextLeft.Image = Card.Last.inner_text_left_image) {
                $id("swfpageflip").render_inner_text_left();
            }
            if (Card.InnerTextRight.Image = Card.Last.inner_text_right_image) {
                $id("swfpageflip").render_inner_text_right();
            }
            if (Card.InnerTextRight.Text = Card.Last.inner_text_right) {
                Card.InnerTextRight.Align = Card.Last.inner_text_right_alignment;
                Card.InnerTextRight.Font = Card.Last.inner_text_right_font;
                Card.InnerTextRight.Color = Card.Last.inner_text_right_color;
                $id("swfpageflip").render_inner_text_right();
            }
            if (Card.TitleImage.ID = Card.Last.title_image_id) {
                $id('swfpageflip').render_title_image();
            }
            if (Card.Video.Name = Card.Last.video) {
                $id('swfpageflip').render_video();
            }
            Card.TitleImage.Container.Create();
            Card.TitleText.Container.Create();
            if (Card.Cover.Name = Card.Last.background) {
                $id("swfpageflip").render_bg_p1();
                $id("swfpageflip").render_bg_p2();
                $id("swfpageflip").render_bg_p3();
                $id("swfpageflip").render_bg_p4();
            }
            if (Card.Music = Card.Last.mp3) {
                $("#dd_music dd a[rel*='" + Card.Music + "']").click();
            }
            Card.SetCost();
        } else {
            //deb("Card.Restore()");
            setTimeout("Card.Restore()", 2000);
        }
    },
    Update : function() {
        if ((Card.flipping == 1) && (Card._prevState.flipping == 0)) {
            TextControls.Hide();
            if (Card.page == 0) {
                Card.TitleImage.Container.Remove();
                Card.TitleText.Container.Remove();
                Card.InnerTextLeft.Container.Remove();
                Card.InnerTextRight.Container.Remove();
                $("#text").removeClass("card_p2").removeClass("card_p3").removeClass("card_p1");
            } else if (Card.page == 2) {
                Card.InnerTextLeft.Container.Remove();
                Card.InnerTextRight.Container.Remove();
                $("#text").removeClass("card_p2").removeClass("card_p3");
            }
            Card.Cover.Hide();
        } else if ((Card.flipping == 0) && (Card._prevState.flipping == 1)) {
            TextControls.Update();
            Card.Cover.Show();
            if (Card.page == 0) {
                $("#text").addClass("card_p1");
                if(!Card.Video.Name) {
                    Card.TitleImage.Container.Create();
                    Card.TitleText.Container.Create();
                }
            } else if (Card.page == 2) {
                $("#text").addClass("card_p2");
                Card.InnerTextLeft.Container.Create();
                Card.InnerTextRight.Container.Create();
            }
        }
        Card._prevState.flipping = Card.flipping;
        Card._prevState.page = Card.page;
    },

    Cover : {
        Set : function(name) {
            $.pget("/proc/render/set_background", {
                image : name
            }, function(d) {
                if (d == "OK") {
                    Card.Cover.Update();
                }
            });
        },

        Update : function() {
            $id("swfpageflip").render_bg_p1();
            $id("swfpageflip").render_bg_p2();
            $id("swfpageflip").render_bg_p3();
            $id("swfpageflip").render_bg_p4();
        },

        Hide : function() {
            $.browser.msie ? $("#cover").css( {
                display : "none"
            }) : $("#cover").animate( {
                opacity : 0
            }, "fast");
        },

        Show : function() {
            $.browser.msie ? $("#cover").css( {
                display : "block"
            }) : $("#cover").animate( {
                opacity : 1
            }, "fast");
        },
        Name : null
    },

    Translate : function() {
        if ($("#txt").val().length) {
            
            var html_text = '';
            if ( $('#translate-form').find('.txt').size() > 0 ) {
                $('#translate-form').find('.txt').val($("#txt").val());    
            } else {
                $('#translate-form').append('<textarea name="txt" rows="1" cols="1" class="txt" style="display:none;">' + $("#txt").val() + '</textarea>');    
            }
            var param = $('#translate-form').serialize();
            $.ajax({
               type: "POST",
               url: "/proc/card_processor/translate?from=" + $("#tlfrom").val() + "&to=" + $("#tlto").val(),
               data: param,
               success: function(data){
                    $.colorbox( {
                        html:data,
                        //href : "/proc/card_processor/translate?from=" + $("#tlfrom").val() + "&to=" + $("#tlto").val() + "&txt=" + $("#txt").val(),
                        open : true
                    });  
               }
             });
            
            /*$.fn.colorbox( {
                //href : "/proc/card_processor/translate?txt=" + escape($("#txt").val()) + "&from=" + $("#tlfrom").val() + "&to=" + $("#tlto").val(),
                href : "/proc/card_processor/translate?from=" + $("#tlfrom").val() + "&to=" + $("#tlto").val() + "&txt=" + $("#txt").val(),
                open : true
            });*/
        } else {
            alert("Please, enter a text");
        }
    },
    Video: {
        Name : null,
        Set : function(name) {
            if(typeof $id("swfsnd").stopSound == 'function') {
                $id("swfsnd").stopSound();    
            }
            
            $.pget("/proc/render/set_video", {
                video : name
            }, function(d) {
                Card.flag=true;
                if (d == "OK") {
                    Card.Video.Name = name;
                    Card.TitleImage.Container.Hide();
                    Card.TitleText.Container.Hide();
                    $id('swfpageflip').render_video();
                    $("#p1_titleImage").removeClass("vk_h");
                }
            });
        },
        Update : function() {
            $id('swfpageflip').render_video();
        }
    },
    TitleImage : {
        Container : {
            text : "<br/><br/><br/><br/><b>Drag & Drop</b><br/> image here<br/> from carousel below",
            Create : function() {
                if ($("#p1_titleImage").length == 0) {
                    $("#card_cont").createAppend('div', {
                        id : "p1_titleImage"
                    }).css( {
                        opacity : Card.TitleImage.ID || Card.Video.Name? 0 : 1
                    });
                    $("#p1_titleImage").droppable( {
                        drop : function(event, ui) {
                            $id('swfpageflip').stop_video();
                            $("#p1_titleImage").animate( {
                                opacity : 0
                            }, "fast");
                            var src= ui.helper.attr("src");
                            if (src.indexOf('animate') !== -1) {
                                flvname = src.match(/\/([^/]+)\.(jpg|gif|png)/)[1] + '.flv';
                                flvname = flvname.replace(/[ ']+/g, '_').replace(/\%20/g, '_').replace(/\%27/g, '_');
                                Card.Video.Set(flvname);
                            } else {
                                Card.TitleImage.ID = ui.helper.attr("id").replace("img", "");
                                Card.Video.Name = null;
                                Card.flag=false;
                                $id('swfpageflip').stop_video();
                                $.pget('/proc/render/set_title_image', {
                                    id : Card.TitleImage.ID
                                }, function(d) {
                                    $id('swfpageflip').render_title_image();
                                    
                                });
                                
                            }
                            Card.SetCost();
                        }
                    }).css( {
                        opacity : Card.TitleImage.ID || Card.Video.Name? 0 : 1
                    });
                } else {
                    $("#p1_titleImage").removeClass("vk_h");
                }
            },
            Remove : function() {
                $("#p1_titleImage").addClass("vk_h");
            },
            Hide : function() {
                $("#p1_titleImage").stop().animate( {
                    opacity : 0
                });
            }
        },
        ID : null
    },

    SetCost : function(id) {
        
        id = id ? id : Card.TitleImage.ID;
        $disc = $('#i-discount');
        discount = $disc.length ? parseInt($disc.html()) / 100 : 0;
        $freecards = $('#i-freecards');
        freecount = $freecards.length ? parseInt($freecards.html()) : 0;
        $freeallow = $('#f-a' + id);
        freeallow = $freeallow.length && freecount ? parseInt($freeallow.html()) : 0;
        $cost = $("#cost" + id);
        cost = $cost.length ? parseFloat($cost.html()) : 1.99; // First
        // Category Bug
        cost = Math.round(cost * (1 - discount) * 100) / 100; // with discount
        //console.log(cost);
        
        // Set for card
        if (cost && !freeallow) {
            $(".btnSend").css( {
                backgroundPosition : "0 -58px"
            }).html('$' + cost);
        } else {
            $(".btnSend").css( {
                backgroundPosition : "0 0"
            }).html('');
        }

        // Set for calendar
        $('#btnSendCalendar').html('$' + (cost ? cost : 1.99));
    },

    TitleText : {
        Container : {
            Create : function() {
                if ($("#p1_titleTextLayer").length == 0) {
                    $("#card_cont").createAppend('div', {
                        id : 'p1_titleTextLayer',
                        onmouseover : function() {
                            Card.TitleText.Container.Show();
                        },
                        onmouseout : function() {
                            Card.TitleText.Container.Hide();
                        },
                        onclick : function() {
                            Card.TitleText.Container.Hide();
                            Card.TitleText.Container.LoadVK();
                        }
                    });
                    $("#p1_titleTextLayer").css( {
                        opacity : Card.TitleText.Text || Card.Video.Name ? 0.3 : 1
                    });
                } else {
                    $("#p1_titleTextLayer").removeClass("vk_h");
                }
            },
            Remove : function() {
                $("#p1_titleTextLayer").addClass("vk_h");
            },
            Hide : function() {
                if (Card.TitleText.Text || Card.Video.Name) {
                    $("#p1_titleTextLayer").stop().animate( {
                        opacity : 0
                    }, function() {
                        if (Card.TitleText.Text)
                            $id('swfpageflip').show_title_text();
                    });

                }
            },
            Show : function() {
                $id('swfpageflip').hide_title_text();
                $("#p1_titleTextLayer").stop().animate( {
                    opacity : 0.6
                }, "fast");
            },
            LoadVK : function() {
                VK_load("p1_textTitle");
            }
        },
        Text : "",
        Align : "center",
        Color : "red",
        Font : "",
        FontSize : 20,
        Image : false
    },
    
    InnerTextLeft : {
        Container : {
            Create : function() {
                if ($("#p2_textLayerLeft").length == 0) {
                    $("#card_cont").createAppend('div', {
                        id : 'p2_textLayerLeft',
                        onclick : function() {
                            $("#text").addClass('card_p2').removeClass("card_p3");
                            Card.InnerTextLeft.Container.Hide();
                            $.colorbox( {
                                href : "/proc/boxes/choose_content_type",
                                open : true
                            });
                        },
                        onmouseover : function() {
                            if (Card.InnerTextLeft.Text || Card.InnerTextLeft.Image) {
                                $id("swfpageflip").hide_inner_text_left();
                                Card.InnerTextLeft.Container.Show(0.3);
                            }
                        },
                        onmouseout : function() {
                            if (Card.InnerTextLeft.Text || Card.InnerTextLeft.Image) {
                                $id("swfpageflip").show_inner_text_left();
                                Card.InnerTextLeft.Container.Hide();
                            }
                        }
                    }).css( {
                        opacity : Card.InnerTextLeft.Text || Card.InnerTextLeft.Image ? 0 : 0.7
                    });
                    $("#p2_textLayerLeft").droppable( {
                        drop : function(event, ui) {
                            $("#p2_textLayerLeft").animate( {
                                opacity : 0
                            }, "fast");
                            Card.InnerTextLeft.ID = ui.helper.attr("id").replace("img", "");
                            $.pget('/proc/render/set_inner_text_left_image_id', {
                                id : Card.InnerTextLeft.ID
                            }, function(d) {
                                $id("swfpageflip").render_inner_text_left();
                            });
                        }
                    });
                } else {
                    $("#p2_textLayerLeft").removeClass("vk_h");
                }
            },

            Remove : function() {
                $("#p2_textLayerLeft").addClass("vk_h");
            },

            Hide : function() {
                if (Card.InnerTextLeft.Text || Card.InnerTextLeft.Image) {
                    $("#p2_textLayerLeft").stop().animate( {
                        opacity : 0
                    }, "fast", function() {
                        if (Card.InnerTextLeft.Text) {

                        }
                    });
                }
            },

            Show : function(o) {
                $("#p2_textLayerLeft").stop().animate( {
                    opacity : o ? o : 0.7
                }, "fast");
            },

            LoadVK : function() {
                VK_load("p2_textInnerLeft");
            }
        },
        Text : "",
        Align : "center",
        Color : "red",
        Font : "",
        FontSize : 20,
        Image : false,
        ID : null
    },

    InnerTextRight : {
        Container : {
            Create : function() {
                if (!$("#p3_textLayerRight").length) {
                    //$('#p3_textLayerRight').colorbox();
                    $("#card_cont").createAppend('a', {
                        id : 'p3_textLayerRight',
                        href: '/proc/boxes/choose_content_type',
                        onclick : function() {
                            $("#text").removeClass("card_p2").addClass("card_p3");
                            Card.InnerTextRight.Container.Hide();
                            $.colorbox( {
                                href : "/proc/boxes/choose_content_type",
                                open : true
                            });
                            
                            return false;
                        },
                        onmouseover : function() {
                            if (Card.InnerTextRight.Text || Card.InnerTextRight.Image) {
                                $id("swfpageflip").hide_inner_text_right();
                                Card.InnerTextRight.Container.Show(0.3);
                            }
                        },
                        onmouseout : function() {
                            if (Card.InnerTextRight.Text || Card.InnerTextRight.Image) {
                                $id("swfpageflip").show_inner_text_right();
                                Card.InnerTextRight.Container.Hide();
                            }
                        }
                    }).css( {
                        opacity : Card.InnerTextRight.Text || Card.InnerTextRight.Image ? 0 : 0.7
                    });
                    
                    $("#p3_textLayerRight").droppable( {
                        drop : function(event, ui) {
                            $("#p3_textLayerRight").animate( {
                                opacity : 0
                            }, "fast");
                            Card.InnerTextRight.ID = ui.helper.attr("id").replace("img", "");
                            $.pget('/proc/render/set_inner_text_right_image_id', {
                                id : Card.InnerTextRight.ID
                            }, function(d) {
                                $id("swfpageflip").render_inner_text_right();
                            });
                        }
                    });
                } else {
                    $("#p3_textLayerRight").removeClass("vk_h");
                }
            },

            Remove : function() {
                $("#p3_textLayerRight").addClass("vk_h");
            },

            Hide : function() {
                if (Card.InnerTextRight.Text || Card.InnerTextRight.Image) {
                    $("#p3_textLayerRight").stop().animate( {
                        opacity : 0
                    }, "fast");
                }
            },

            Show : function(o) {
                $("#p3_textLayerRight").stop().animate( {
                    opacity : o ? o : 0.7
                }, "fast");
            },

            LoadVK : function() {
                VK_load("p3_textLayerRight");
            }
        },

        Text : "",
        Align : "center",
        Color : "red",
        Font : "",
        FontSize : 20,
        ID : null
    },
    SetMusic : function(mp3) {
        
        $.pget("/proc/render/set_music", {
            mp3 : mp3
        });
        Card.Music = mp3;
    },
    Music : null
};

VK_container = null;
VK_unload_tm = null;
VK_hiding = false;
tm_VKLoading = null;
VK_load = function(className) {
    VK_container = className;
    if ($(".vk_overlay").length == 0) {
        $(".ribbonCont").css( {
            zIndex : 1
        });
        // Adding Overlay
        $("#text").createAppend('div', {
            onmouseover : function() {
                clearTimeout(VK_unload_tm);
            }
        }).addClass("vk_overlay").css( {
            opacity : 0.9
        }).addClass(className);

        // Adding Controls Container
        $("#text").createAppend('div').addClass("vk_container").createAppend('textarea', {
            id : 'txt',
            onchange : function() {
                // alert(1);
            }
        }).focus().val();

        // buttons
        $(".vk_container").createAppend('div').addClass('bt_ok').click(function() {
            VK_hide();
        });
        $(".vk_container").createAppend('div').addClass('bt_clear').click(function() {
            $("#txt").val('');
        });
        $(".vk_container").createAppend('div').addClass('bt_cancel').click(function() {
            VK_container = null;
            VK_hide();
        });

        // quotes

        $(".vk_container").createAppend('div', {
            id : 'vk'
        }).css( {
            zIndex : 13
        }).addClass("vk_cont");
        $("#text").createAppend('div', {
            onmouseover : function() {
                //VK_unload_tm = setTimeout(VK_hide, 2000);
            },
            onclick : function() {
                clearTimeout(VK_unload_tm);
                VK_hide();
            }
        }).addClass("vk_unloader");
        tm_VKLoading = setInterval(function() {
            if ($id('virtualKeyboard')) {
                clearInterval(tm_VKLoading);
                return;
            }
            VirtualKeyboard.toggle('txt', 'vk');
        }, 1500);
        $(".vk_container").createAppend('div', {
            id : "tl"
        }).load("/proc/boxes/get_translate_form");
    } else {
        clearTimeout(VK_unload_tm);
        $(".vk_overlay, .vk_container, .vk_unloader").removeClass("vk_h");
    }
    
    $('.bt_ok_l').removeClass('bt_ok_l');
    $('.bt_clear_l').removeClass('bt_clear_l');
    $('.bt_cancel_l').removeClass('bt_cancel_l');
    
    
    switch (VK_container) {
    case "p1_textTitle":
        $('#txt').val(Card.TitleText.Text);
        $('.bt_ok').addClass('bt_ok_l');
        $('.bt_clear').addClass('bt_clear_l');
        $('.bt_cancel').addClass('bt_cancel_l');
        break;
    case "p2_textInnerLeft":
        $('#txt').val(Card.InnerTextLeft.Text);
        break;
    case "p3_textLayerRight":
        $('#txt').val(Card.InnerTextRight.Text);
        break;
    }
    if ((className != "p1_textTitle") && ($(".vk_quotes").length == 0)) {
        Quotes.init();
    }

};

VK_hide = function() {
    if (!VK_hiding) {
        VK_hiding = true;
        switch (VK_container) {
        case "p1_textTitle":
            // Card.TitleText.Container.Show();
            $.ppost('/proc/render/set_title_text', {
                text : $('#txt').val()
            }, function(d) {
                if (d == "OK") {
                    Card.TitleText.Text = $('#txt').val();
                    $id('swfpageflip').render_title_text();
                    Card.TitleText.Container.Hide();
                    TextControls.Update();
                } else {
                    Card.TitleText.Text = null;
                }
            });
            break;
        case "p2_textInnerLeft":
            $.ppost('/proc/render/set_inner_text_left', {
                text : $('#txt').val()
            }, function(d) {
                if (d == "OK") {
                    Card.InnerTextLeft.Text = $('#txt').val();
                    $id('swfpageflip').render_inner_text_left();
                    Card.InnerTextLeft.Container.Hide();
                    Card.InnerTextLeft.Image = false;
                    TextControls.Update();
                } else {
                    Card.InnerTextLeft.Text = null;
                    Card.InnerTextLeft.Container.Show();
                }
            });
            break;
        case "p3_textLayerRight":
            $.ppost('/proc/render/set_inner_text_right', {
                text : $('#txt').val()
            }, function(d) {
                if (d == "OK") {
                    Card.InnerTextRight.Text = $('#txt').val();
                    $id('swfpageflip').render_inner_text_right();
                    Card.InnerTextRight.Container.Hide();
                    Card.InnerTextRight.Image = false;
                    TextControls.Update();
                } else {
                    Card.InnerTextRight.Text = null;
                    Card.InnerTextRight.Container.Show();
                }
            });
            break;
        default:
            VK_hide_internal();
        }
        VK_hide_internal();
        VK_hiding = false;
    }
};

VK_hide_internal = function() {
    if ($(".vk_overlay").length == 1) {
        $(".vk_overlay, .vk_container, .vk_unloader").addClass("vk_h");
        $(".ribbonCont").css( {
            zIndex : 12
        });
        $("#text").focus();
    }
};

var TextControls = {
    Init : function() {
        $(".font").click(function() {
            if ($(this).parent().hasClass('right')) {
                $(".flist").addClass('flist_right').removeClass('flist_left');
            } else if ($(this).parent().hasClass('left')) {
                $(".flist").addClass('flist_left').removeClass('flist_right');
            }
            $(".flist").toggle();
            return false;
        });
        $(".fontsize").click(function() {
            if ($(this).parent().hasClass('right')) {
                $(".flistsize").addClass('flistsize_right').removeClass('flistsize_left');
            } else if ($(this).parent().hasClass('left')) {
                $(".flistsize").addClass('flistsize_left').removeClass('flistsize_right');
            }
            $(".flistsize").toggle();
            return false;
        });
        $(".flist a").click(function() {
            var val = $(this).find('span').html();
            if (Card.page == 0) {
                Card.TitleText.Font = val;
                $("#p_control .right .font").html($(this).html());
                var txt = "titleText";
            } else if (Card.page == 2) {
                if ($(".flist").hasClass('flist_left')) {
                    Card.InnerTextLeft.Font = val;
                    $("#p_control .left .font").html($(this).html());
                    var txt = "innerTextLeft";
                } else {
                    Card.InnerTextRight.Font = val;
                    $("#p_control .right .font").html($(this).html());
                    var txt = "innerTextRight";
                }
            }
            $(".flist").hide();
            TextControls.SetTextFont(txt, val);
            return false;
        });
        $(".flistsize a").click(function() {
            var val = $(this).find('span').html();
            if (Card.page == 0) {
                Card.TitleText.FontSize = val;
                $("#p_control .right .fontsize").html($(this).html());
                var txt = "titleText";
            } else if (Card.page == 2) {
                if ($(".flistsize").hasClass('flistsize_left')) {
                    Card.InnerTextLeft.FontSize = val;
                    $("#p_control .left .fontsize").html($(this).html());
                    var txt = "innerTextLeft";
                } else {
                    Card.InnerTextRight.FontSize = val;
                    $("#p_control .right .fontsize").html($(this).html());
                    var txt = "innerTextRight";
                }
            }
            $(".flistsize").hide();
            TextControls.SetTextFontSize(txt, val);
            return false;
        });
        $("#p_control .txt_left").click(function() {
            if (!$(this).hasClass('txt_left_sel')) {
                $(this).parent().find('div').removeClass('txt_center_sel').removeClass('txt_right_sel');
                $(this).addClass('txt_left_sel');
                var txt = "titleText";
                if (Card.page == 2) {
                    txt = $(this).parent().hasClass('left') ? "innerTextLeft" : "innerTextRight";
                }
                TextControls.SetTextAlignment(txt, "northwest");
            }
        });
        $("#p_control .txt_center").click(function() {
            if (!$(this).hasClass('txt_center_sel')) {
                $(this).parent().find('div').removeClass('txt_left_sel').removeClass('txt_right_sel');
                $(this).addClass('txt_center_sel');
                var txt = "titleText";
                if (Card.page == 2) {
                    txt = $(this).parent().hasClass('left') ? "innerTextLeft" : "innerTextRight";
                }
                TextControls.SetTextAlignment(txt, "north");
            }
        });
        $("#p_control .txt_right").click(function() {
            if (!$(this).hasClass('txt_right_sel')) {
                $(this).parent().find('div').removeClass('txt_center_sel').removeClass('txt_left_sel');
                $(this).addClass('txt_right_sel');
                var txt = "titleText";
                if (Card.page == 2) {
                    txt = $(this).parent().hasClass('left') ? "innerTextLeft" : "innerTextRight";
                }
                TextControls.SetTextAlignment(txt, "northeast");
            }
        });
        $("#p_control .txt_color").click(function() {

        });
        $("#p_control .left, #p_control .right").css( {
            display : 'none'
        });
        $(".txt_color").click(function() {
            colorPicker_show($(this).parents('.left').length ? "left" : "right");
        });
        TextControls.Update();
    },

    Update : function() {
        $("#p_control").find('div.b').removeClass('txt_center_sel').removeClass('txt_left_sel').removeClass('txt_right_sel');
        if (Card.page == 0) {
            if (Card.TitleText.Text) {
                $("#p_control .right").css( {
                    display : "block"
                }).animate( {
                    opacity : 1
                }, "fast").find('.txt_' + Card.TitleText.Align).addClass('txt_' + Card.TitleText.Align + '_sel');
            }
        } else if (Card.page == 2) {
            if (Card.InnerTextLeft.Text && !Card.InnerTextLeft.Image) {
                $("#p_control .left").css( {
                    display : "block"
                }).animate( {
                    opacity : 1
                }, "fast").find('.txt_' + Card.InnerTextLeft.Align).addClass('txt_' + Card.InnerTextLeft.Align + '_sel');
            }
            if (Card.InnerTextRight.Text && !Card.InnerTextRight.Image) {
                $("#p_control .right").css( {
                    display : "block"
                }).animate( {
                    opacity : 1
                }, "fast").find('.txt_' + Card.InnerTextRight.Align).addClass('txt_' + Card.InnerTextRight.Align + '_sel');
            }
        }
    },

    Hide : function() {
        $("#p_control .left, #p_control .right").animate( {
            opacity : 0
        }, function() {
            $("#p_control .left, #p_control .right").css( {
                display : "none"
            });
        });
    },

    SetTextAlignment : function(txt, mode) {
        var m = mode == "north" ? "center" : (mode == "northeast" ? "right" : "left");
        $.pget("/proc/render/set_text_alignment", {
            txt : txt,
            mode : mode
        }, function(d) {
            if (d == "OK") {
                if (txt == "titleText") {
                    Card.TitleText.Align = m;
                    $id("swfpageflip").render_title_text();
                } else if (txt == "innerTextLeft") {
                    Card.InnerTextLeft.Align = m;
                    $id("swfpageflip").render_inner_text_left();
                } else if (txt == "innerTextRight") {
                    Card.InnerTextRight.Align = m;
                    $id("swfpageflip").render_inner_text_right();
                }
            }
        });
    },

    SetTextFont : function(txt, font) {
        $.pget("/proc/render/set_text_font", {
            txt : txt,
            font : font
        }, function(d) {
            if (d == "OK") {
                if (txt == "titleText") {
                    Card.TitleText.Font = font;
                    $id("swfpageflip").render_title_text();
                } else if (txt == "innerTextLeft") {
                    Card.InnerTextLeft.Font = font;
                    $id("swfpageflip").render_inner_text_left();
                } else if (txt == "innerTextRight") {
                    Card.InnerTextRight.Font = font;
                    $id("swfpageflip").render_inner_text_right();
                }
            }
        });
    },
    

    SetTextColor : function(txt, color) {
        $.pget("/proc/render/set_text_color", {
            txt : txt,
            color : color
        }, function(d) {
            if (d == "OK") {
                if (txt == "titleText") {
                    Card.TitleText.Color = color;
                    $id("swfpageflip").render_title_text();
                } else if (txt == "innerTextLeft") {
                    Card.InnerTextLeft.Color = color;
                    $id("swfpageflip").render_inner_text_left();
                } else if (txt == "innerTextRight") {
                    Card.InnerTextRight.Color = color;
                    $id("swfpageflip").render_inner_text_right();
                }
            }
        });
    },

    SetTextFontSize : function(txt, size) {
        $.pget("/proc/render/set_text_font_size", {
            txt : txt,
            size : size
        }, function(d) {
            if (d == "OK") {
                if (txt == "titleText") {
                    Card.TitleText.FontSize = size;
                    $id("swfpageflip").render_title_text();
                } else if (txt == "innerTextLeft") {
                    Card.InnerTextLeft.FontSize = size;
                    $id("swfpageflip").render_inner_text_left();
                } else if (txt == "innerTextRight") {
                    Card.InnerTextRight.FontSize = size;
                    $id("swfpageflip").render_inner_text_right();
                }
            }
        });
    }
};

var Quotes = {
    init : function() {
        $(".vk_container").createAppend('div').addClass('vk_quotes');
        $.pget("/proc/quotes/load_list", function(d) {
            $('.vk_quotes').html(d);
            $('#quote_cat').dropdown( {
                onchange : function(v, el) {
                    $.pget("/proc/quotes/load_quotes", {
                        cid : v
                    }, function(d) {
                        $("#q_block").html(d);
                        $("#quote_list").jScrollPane( {
                            showArrows : true
                        });
                    });
                }
            });
            $('#quote_list').jScrollPane( {
                showArrows : true
            });
            $(".quote").mouseover(function() {
                $(this).addClass("here");
            }).mouseout(function() {
                $(this).removeClass("here");
            });
        });
    },

    loadQuotes : function(id, pageNo) {
        $.pget("/proc/quotes/load_quotes", {
            cid : id,
            pageNo : pageNo
        }, function(d) {
            $("#q_block").html(d);
            $("#quote_list").jScrollPane( {
                showArrows : true
            });
        });
        return false;
    },

    paste : function(txt) {
        $("#txt").val(txt.replace(/\<br[^\>]*>/gi, "\n"));
    }
};

var Sender = {

    loadSendDialod : function() {
        $.ppost('/proc/card_processor/check', {}, function(d) {

            
            if(d!=0)
            {    
                $.colorbox( {
                    html :d,
                    open : true
                });
            }
            else
            {
                $.colorbox( {
            href : '/proc/boxes/send_card?fcsid=' + Main.fcsid,
            open : true
            }, function(){
            //debugger;
            $("#sender_name").val(Planner.formData.sname);
            $("#sender_email").val(Planner.formData.smail);
            $("#reciever_email").val(Planner.formData.rmail);
            $("#reciever_name").val(Planner.formData.rname);
            Planner.formData.chkcopy?$("#send_copy").attr('checked', true):$("#send_copy").removeAttr('checked');
            Planner.formData.chknotify?$("#know").attr('checked', true):$("#know").removeAttr('checked');
            $("#time").val(Planner.date);
            });
            }        
            
            });
        
                    
        
    },

    send : function(authed) {
        

        $sender_email = '';
        $sender_name = '';

        if (!authed) {
            $sender_name = $("input[name=sender_name]");
            if (!$sender_name.val()) {
                eForm.setError($sender_name, 'field is required', 'sender');
                return false;
            }
            $sender_email = $("input[name=sender_email]");
            if (!$sender_email.val()) {
                eForm.setError($sender_email, 'field is required', 'sender');
                return false;
            }
        }

        $reciever_name = $("input[name=reciever_name]");
        if (!$reciever_name.val()) {
            eForm.setError($reciever_name, 'field is required', authed ? null : 'reciever');
            return false;
        }
        $reciever_email = $("input[name=reciever_email]");
        if (!$reciever_email.val()) {
            eForm.setError($reciever_email, 'field is required', authed ? null : 'reciever');
            return false;
        }

        $.ppost("/proc/card_processor/store", {
            sender_email : $sender_email ? $sender_email.val() : '',
            sender_name : $sender_name ? $sender_name.val() : '',
            reciever_email : $reciever_email.val(),
            reciever_name : $reciever_name.val(),
            send_copy : $("#send_copy:checked").length,
            know : $("#know:checked").length,
            sdate: $("#time").val()

        }, function(d) {
            
            
            if (d.indexOf('<error') != -1) {
                eForm.setError(d);
            } else {
                $.colorbox( {
                    html : d,
                    open : true
                }, function() {
                    $ISform = $('#add-to-card');
                    if ($ISform.length) {
                        $('#add-to-card').submit();
                    } else {
                        Main.loadAuthBlock();
                    }
                });
            }
        });
         $.colorbox.close(); 
    }
};

String.prototype.hasHighUTFCode = function() {
    for ( var i = 0; i < this.length; i++) {
        if (this.charCodeAt(i) > 223)
            return true;
    }
    return false;
};

loadSWF = function(cont_id, fname, w, h, id) {
    if (!id)
        id = "swf" + cont_id;

    $('#' + cont_id).media( {
        width : w,
        height : h,
        src : '/i/swf/' + fname,
        attrs : {
            id : id,
            wmode : 'transparent',
            scale : "default",
            quality : "high",
            allowscriptaccess : "always"
        },
        params : {
            id : id,
            wmode : 'transparent',
            scale : "default",
            quality : "high",
            allowscriptaccess : "always"
        }
    });
};

var tm_colorPicker = null;
function colorPicker_show(cl) {
    clearTimeout(tm_colorPicker);
    colorPicker_hide();
    if ($("#colorpicker").length == 0) {
        $("#text").createAppend('div', {
            id : "colorpicker"
        }).addClass("cp_" + cl);
        for ( var i = 0; i < palette.length; i += 2) {
            $("#colorpicker").createAppend('div').addClass('c').attr('title', palette[i + 1]).css( {
                backgroundColor : palette[i]
            }).click(function() {
                if (Card.page == 0)
                    var txt = "titleText";
                else if (Card.page == 2)
                    var txt = cl == "left" ? "innerTextLeft" : "innerTextRight";
                TextControls.SetTextColor(txt, $(this).attr('title'));
                colorPicker_hide();
            });
        }
    } else {
        $("#colorpicker").removeClass('vk_h').addClass('cp_' + cl);
    }
};

function colorPicker_hide() {
    clearTimeout(tm_colorPicker);
    $("#colorpicker").remove();
}

function colorPicker_remove() {
    $(".colorpicker").empty().css( {
        display : "none"
    });
}

function obj2url(obj) {
    var url = "";
    for ( var key in obj) {
        url += key + "=" + escape(obj[key]) + "&";
    }
    return url;
}

jQuery.extend( {
    pget : function(url, params, callback) {
        var p = typeof (params) == "object" ? params : null;
        var cb = typeof (params) == "function" ? params : (typeof (callback) == "function" ? callback : null);
        if (Main.fcsid) {
            if (!p)
                p = {};
            p['fcsid'] = Main.fcsid;
        }
        $.get(url, p, function(data) {
            // TODO :data = _global_message_process(data);
                if (typeof (cb) == "function")
                    cb(data);
            });
    },
    ppost : function(url, params, callback) {
        var p = typeof (params) == "object" ? params : null;
        var cb = typeof (params) == "function" ? params : (typeof (callback) == "function" ? callback : null);
        if (Main.fcsid) {
            if (!p)
                p = {};
            p['fcsid'] = Main.fcsid;
        }
        $.post(url, p, function(data) {
            // TODO :data = _global_message_process(data);
                if (typeof (cb) == "function")
                    cb(data);
            });
    }
});

function $id(id) {
    return document.getElementById(id);
}

function deb(s) {
    if (debug) {
        $("#dbg").html($("#dbg").html() + s + "<br/>").css( {
            display : "block"
        });
    }
}

var palette = new Array('#F0F8FF', 'aliceblue', '#FAEBD7', 'antiquewhite', '#00FFFF', 'aqua', '#7FFFD4', 'aquamarine', '#F0FFFF', 'azure', '#F5F5DC', 'beige', '#FFE4C4', 'bisque', '#191970', 'MidnightBlue', '#FFEBCD', 'blanchedalmond', '#0000FF', 'blue', '#8A2BE2', 'blueviolet', '#A52A2A', 'brown',
        '#DEB887', 'burlywood', '#5F9EA0', 'cadetblue', '#7FFF00', 'chartreuse', '#D2691E', 'chocolate', '#FF7F50', 'coral', '#6495ED', 'cornflowerblue', '#FFF8DC', 'cornsilk', '#DC143C', 'crimson', '#00FFFF', 'cyan', '#00008B', 'darkblue', '#008B8B', 'darkcyan', '#B8860B', 'darkgoldenrod',
        '#A9A9A9', 'darkgray', '#006400', 'darkgreen', '#BDB76B', 'darkkhaki', '#8B008B', 'darkmagenta', '#556B2F', 'darkolivegreen', '#FF8C00', 'darkorange', '#9932CC', 'darkorchid', '#8B0000', 'darkred', '#E9967A', 'darksalmon', '#8FBC8F', 'darkseagreen', '#483D8B', 'darkslateblue', '#2F4F4F',
        'darkslategray', '#00CED1', 'darkturquoise', '#9400D3', 'darkviolet', '#FF1493', 'deeppink', '#00BFBF', 'deepskyblue', '#696969', 'dimgray', '#1E90FF', 'dodgerblue', '#B22222', 'firebrick', '#FFFAF0', 'floralwhite', '#228B22', 'forestgreen', '#FF00FF', 'fuchsia', '#DCDCDC', 'gainsboro',
        '#F8F8FF', 'ghostwhite', '#FFD700', 'gold', '#DAA520', 'goldenrod', '#808080', 'gray', '#008000', 'green', '#ADFF2F', 'greenyellow', '#F0FFF0', 'honeydew', '#FF69B4', 'hotpink', '#CD5C5C', 'indianred', '#4B0082', 'indigo', '#FFFFF0', 'ivory', '#F0E68C', 'khaki', '#E6E6FA', 'lavender',
        '#FFF0F5', 'lavenderblush', '#7CFC00', 'lawngreen', '#FFFACD', 'lemonchiffon', '#ADD8E6', 'lightblue', '#F08080', 'lightcoral', '#E0FFFF', 'lightcyan', '#FAFAD2', 'lightgoldenrodyellow', '#90EE90', 'lightgreen', '#D3D3D3', 'lightgrey', '#FFB6C1', 'lightpink', '#FFA07A', 'lightsalmon',
        '#20B2AA', 'lightseagreen', '#87CEFA', 'lightskyblue', '#778899', 'lightslategrey', '#B0C4DE', 'lightsteelblue', '#FFFFE0', 'lightyellow', '#00FF00', 'lime', '#32CD32', 'limegreen', '#FAF0E6', 'linen', '#FF00FF', 'magenta', '#800000', 'maroon', '#66CDAA', 'mediumaquamarine', '#0000CD',
        'mediumblue', '#BA55D3', 'mediumorchid', '#9370DB', 'mediumpurple', '#3CB371', 'mediumseagreen', '#7B68EE', 'mediumslateblue', '#00FA9A', 'mediumspringgreen', '#48D1CC', 'mediumturquoise', '#C71585', 'mediumvioletred', '#191970', 'midnightblue', '#F5FFFA', 'mintcream', '#FFE4E1',
        'mistyrose', '#FFE4B5', 'moccasin', '#FFDEAD', 'navajowhite', '#000080', 'navy', '#FDF5E6', 'oldlace', '#808000', 'olive', '#6B8E23', 'olivedrab', '#FFA500', 'orange', '#FF4500', 'orangered', '#DA70D6', 'orchid', '#EEE8AA', 'palegoldenrod', '#98FB98', 'palegreen', '#AFEEEE',
        'paleturquoise', '#DB7093', 'palevioletred', '#FFEFD5', 'papayawhip', '#FFDAB9', 'peachpuff', '#CD853F', 'peru', '#FFC0CB', 'pink', '#DDA0DD', 'plum', '#B0E0E6', 'powderblue', '#800080', 'purple', '#FF0000', 'red', '#BC8F8F', 'rosybrown', '#4169E1', 'royalblue', '#8B4513', 'saddlebrown',
        '#FA8072', 'salmon', '#F4A460', 'sandybrown', '#2E8B57', 'seagreen', '#FFF5EE', 'seashell', '#A0522D', 'sienna', '#C0C0C0', 'silver', '#87CEEB', 'skyblue', '#6A5ACD', 'slateblue', '#708090', 'slategray', '#FFFAFA', 'snow', '#00FF7F', 'springgreen', '#4682B4', 'steelblue', '#D2B48C', 'tan',
        '#008080', 'teal', '#D8BFD8', 'thistle', '#FF6347', 'tomato', '#40E0D0', 'turquoise', '#EE82EE', 'violet', '#F5DEB3', 'wheat', '#FFFFFF', 'white', '#F5F5F5', 'whitesmoke', '#FFFF00', 'yellow', '#9ACD32', 'yellowgreen');

var eForm = {

    setError : function(data, text, boxissue) {

        if (typeof (data) == 'object' && text) {
            // --
            this.markBlock(text, boxissue);
            this.markField(data);
        } else if (error = data.match(/\<error f\=.([^>'"]+).*\>(.*)\<.error\>/)) {
            f = error[1];
            text = error[2];
            boxissue = data.match(/\<error.*is\=.([^>'"]+).*\>/)
            boxissue = boxissue ? boxissue[1] : null;

            this.markBlock(text, boxissue);

            items = f.split(/\|/);

            for (i = 0; i < items.length; i++) {
                $f = $('#' + items[i]);

                if ($f.length) {
                    this.markField($f);
                }
            }
        }

        return false;
    },

    markBlock : function(text, boxissue) {

        // reset several rest
        boxissue ? this.reset(boxissue) : false;

        $block = $('#box-block' + (boxissue ? ('-' + boxissue) : ''));
        $block.addClass('error');
        $h1 = $block.find('h1');
        $h1.attr('title', $h1.html()).html('Error: ' + text);
    },

    reset : function(boxissue) {

        $.each($('div.error'), function() {

            $this = $(this);
            $this.removeClass('error');

            $h1 = $this.find('h1');
            $h1.attr('title') ? $h1.html($h1.attr('title')) : false;

        });

    },

    markField : function($f) {

        $f.addClass('error').bind('focus', function() {
            $(this).removeClass('error');
        });
    }

};

var Registration = {

    init : function() {

        $("#btnMembers").click(function() {
            $.colorbox( {
                href : "/proc/boxes/login",
                open : true
            });
        });
        $(".addBalance").colorbox();

        Card.SetCost();
    },
    new_reg:function(){
    /*    $.fn.colorbox( {
                href : "/proc/boxes/new_reg",
                open : true
            });*/
    $.ppost('/proc/boxes/new_reg', {}, function(d) {
            if(d!=0)
            {    
                $.colorbox( {
                    html :d,
                    width:800,
                    height:900,
                    open : true
                });
            }
        });
    },
    auth : function() {

        login = email = $('#auth_login').val();
        if (!login) {
            eForm.setError($('#auth_login'), 'field is required');
            return false;
        }

        pass = $('#auth_pass').val();
        if (!pass) {
            eForm.setError($('#auth_pass'), 'field is required');
            return false;
        }

        $.pget("/proc/login/auth", {
            login : login,
            pass : pass

        }, function(data) {

            if (data.indexOf('<') == -1) {
                // error
                alert(data);

            } else if (data.indexOf('<error') != -1) {
                eForm.setError(data);

            } else {

                if ($('#issingin_frame').length) {
                    // Sign into ShoppingCart
                jQuery('#EMail').val(email);
                jQuery('#Password').val(pass);
                $('#issingin_form').submit();
            }

            if ($('#gallery_frame').length) {
                // Sign into artgallery
                jQuery('#AGemail').val(email);
                $('#gallery_form').submit();
            }

            // Balance data
            $('#authCont').html(data);
            $.colorbox.close();
            /*$.pget('/proc/login/login_form', {}, function(d) {
                        alert(d);
                    });*/
            
            $.ppost('/proc/login/login_form', {login : login,
            pass : pass}, function(d) {
            if(d!=0)
            {    
                $.colorbox( {
                    html :d,
                    open : true
                });
            }
        });

            Registration.init();

        }

    }    );
    },

    logout : function() {
        $.colorbox( {
            href : '/proc/boxes/logout',
            open : true
        });

        $.pget("/proc/login/logout", null, function(data) {

            if (data.indexOf('<') != -1) {
                $('#authCont').html(data);
                Registration.init();
            }

            $.colorbox.close();

        });
    },

    setAddBalanceProductId : function(id) {
        $('#ProductID').val(id);
        $('#AddToCart').attr('name', 'AddToCart_' + id);
    },

    addBalanceTransaction : function() {
        
        var id = $('#ProductID').val();

        $('#membership-table').css( {
            display : 'none'
        });
        $('#order').css( {
            display : 'none'
        });

        $('#redirect-message').css( {
            display : 'block',
            textDecoration : 'blink'
        });
        
        $.pget("/proc/login/addbalance", {
            is_id : id
        }, function(data) {
            
            $('#form_m').submit();
            

        });

    },

    addBalanceDialog : function() {

        $.colorbox( {
            href : '/proc/boxes/addbalance?fcsid=' + Main.fcsid,
            open : true
        });
    },

    checkAutoLogin : function() {
        $.pget("/proc/login/check_autologin", null, function(data) {

            if (data == '1') {
                $.pget("/proc/login/load_form", null, function(data) {

                    if (data) {
                        $('#authCont').html(data);
                    }
                });
            } else {
                window.setTimeout('Registration.checkAutoLogin()', 5000);
            }

        });

    }

};

var Calendar = {
    m : (new Date()).getMonth() + 1,
    y : (new Date()).getFullYear() + 1,
    period : $("#t_r1:checked").length ? "m" : "y",
    layout : 1,
    color : 1,

    SetImage : function(id) {
        Card.SetCost();
        Card.TitleImage.ID=id;
        $.pget("/proc/render/set_calendar_image", {
            id : id
        }, function(d) {
            if (d == "OK") {
                Calendar.UpdateImage();
            }
        });
    },

    UpdateImage : function() {
        $("#cal_loader").animate( {
            opacity : 1
        }, "fast");
        $.pget("/proc/render/set_calendar_mode", {
            m : Calendar.m,
            y : Calendar.y,
            period : Calendar.period,
            layout : Calendar.layout,
            color : Calendar.color
        }, function(d) {
            if (d == "OK") {
                Calendar.LoadImage();
            }
        });
    },

    LoadImage : function() {
        var img = new Image();
        img.onload = function() {
            $("#cal_img").attr("src", this.src);
            $("#cal_loader").stop().animate( {
                opacity : 0
            }, "fast");
        };
        img.src = "/proc/render/get_calendar_image?fcsid=" + Main.fcsid + "&_r=" + Math.random();
    },

    SetMode : function(m) {
        switch (m) {
        case "y":
            $("#calendar_control").addClass('yearly').removeClass('monthly');
            this.period = "y";
            break;
        case "m":
            $("#calendar_control").removeClass('yearly').addClass('monthly');
            this.period = "m";
            break;
        }
        Calendar.UpdateImage();
    },

    GetInfo : function() {
        $.colorbox( {
            href : '/proc/boxes/calendar?fcsid=' + Main.fcsid,
            open : true
        });
    },

    Buy : function() {

        $name = $("#cname");
        if ($name.length && !$name.val()) {
            eForm.setError($name, 'field is required');
            return false;
        }

        $email = $("#cemail");
        if ($email.length && !$email.val()) {
            eForm.setError($email, 'field is required');
            return false;
        }

        $.ppost("/proc/calendar_processor/store", {
            name : $name.val(),
            email : $email.val()
        }, function(data) {

            if (data.indexOf('<error') != -1) {
                eForm.setError(data);

            } else {
                $.colorbox( {
                    html : data,
                    open : true
                }, function() {

                    $ISform = $('#add-to-card');

                    if ($ISform.length) {
                        $('#add-to-card').submit();
                    } else {
                        Main.loadAuthBlock();
                    }
                });
            }
        });
    }
};

var Planner = {
        m : null,
        y : null,
        type: null,
        date: null,
        formData: {smail:null, sname:null, rmail:null, rname:null, chkcopy:null, chknotify:null},
        open : function(m, y, type) {
            this.formData = {smail:null, sname:null, rmail:null, rname:null, chkcopy:null, chknotify:null};
            this.m = m; this.y = y;
            if(this.m==undefined || this.y == undefined) {
                this.m = (new Date()).getMonth()+1;
                this.y = (new Date()).getFullYear();
            }
            this.date="";
            if(type == undefined) {
                this.type = 'event';
            } else {
                this.type = 'card';
                with(this.formData) {
                    sname= $("#sender_name").val();
                    smail= $("#sender_email").val();
                    rmail= $("#reciever_email").val();
                    rname= $("#reciever_name").val();
                    chkcopy= $("#send_copy:checked").length;
                    chknotify= $("#know:checked").length;
                }
            }
            $.colorbox( {
                href : "/proc/planner/reminder?month="+this.m+"&year="+this.y+"&fcsid=" + Main.fcsid+"&_r"+Math.random(),
                open : true
            }, function() {
                $('.rem_day')
                .mouseover(function(){
                    if($(this).find('.e').length == 0) {
                        this.style.background="url("+_img+"/add.gif) no-repeat";
                    }
                })
                .mouseout(function(){this.style.background="none"});
                
                $('.rem_day:has(.e)').find('.addSmall').click(function(){
                    if(Planner.type == 'card') {
                        Planner.date = $(this).parents('.rem_day').find('.d').attr('rel');
                        Sender.loadSendDialod();
                    } else {
                        $.colorbox( {
                            href : "/proc/planner/rm_add?date="+$(this).parents('.rem_day').find('.d').attr('rel')+'&fcsid='+Main.fcsid+"&type="+this.type+"&_r"+Math.random(),
                            open : true
                        });
                    }
                });
                $('.rem_day:not(:has(.e))').click(function(){
                    if(Planner.type == 'card') {
                        Planner.date = $(this).find('.d').attr('rel');
                        Sender.loadSendDialod();
                    } else {
                        $.colorbox( {
                            href : "/proc/planner/rm_add?date="+$(this).find('.d').attr('rel')+'&fcsid='+Main.fcsid+"&type="+this.type+"&_r"+Math.random(),
                            open : true
                        });
                    }
                });
                $('.rem_day:not(:has(.e))').find('.addSmall').remove();
            });
            return false;
        },
        
        save : function(id) {
            $.post("/proc/planner/rm_save", {
                'id' : id == undefined ? 0 : id,
                'rem_title': $('#rem_title').val(),
                'rem_type': $('#rem_type').val(),
                'rem_notes':$('#rem_notes').val(),
                'rem_alarmDays':$('#rem_alarmDays').val(),
                'rem_rec':$('#rem_rec').val(),
                'rem_calendar': $('#rem_calendar').val(),
                'fcsid' : Main.fcsid,
                '_r':Math.random()
            }, function(){
                Planner.open(Planner.m, Planner.y);
            });
        },
        edit : function(id) {
            $.colorbox( {
                href : "/proc/planner/rm_edit?id="+id+"&fcsid="+Main.fcsid+"&_r"+Math.random(),
                open : true
            }, function() {
                
            });
        },
        
        del : function(id) {
            $.get("/proc/planner/rm_del", {id:id, fcsid:Main.fcsid, _r:Math.random()}, function(){
                Planner.open(Planner.m, Planner.y);
            });
        }
}

var Menu = {

    xml : $("#menuxml"),
    menuid : 0,
    menuImage : _img + "menu.gif",

    niImg : '',
    niBg : '',
    flag:true,
    crc : "",
    sid : null,
    check:false,

    historyStock : [],
    historyStockI : 0,

    init : function(id) {
        if(id==9 || id==4)
            $('#main_but').find('.mcont').html("Still Images");
        else if(id==1 || id==0)
            $('#main_but').find('.mcont').html("Animated cards");
        

            //Menu.flag=true;
        if(Menu.check==true)
            {
            Interface.bodyWentBottom = 1;
            //return 
            }
        
        var mid = 0;
        
        Menu.xml = $("#menuxml");
        if (id == 0) {    
            var items = $("root > item", Menu.xml);
            
        } else {
            var items = $("item[pid=" + id + "]", Menu.xml);
            
        }
        
        
        // debugger;
        Menu.menuid = id;
        $("#menu").html("");
        
        if(id==1 || id==4)
        Menu.menuShowBackButton(id != 0);

        for (i = 0; i < items.length; i++) {
            
            $("#menu").createAppend('div', {
                className : "m",
                id : "m" + i
            }, [
                    'img',
                    {
                        src : Menu.menuImage
                    }
            ]);
            if ($(items[i]).attr("bgid")) {
                Interface.bgCat[$(items[i]).attr("id")] = $(items[i]).attr("bgid");
                $("#bgCont").css( {
                    display : "block"
                });
            } else {
                $("#bgCont").css( {
                    display : "none"
                });
            }
            Interface.titleCat[$(items[i]).attr("id")] = $(items[i]).attr("tid");
            var mid = $(items[i]).attr("id");
            $("#m" + i).createAppend('div', {
                className : "mcont"
            }, [
                    'a',
                    {
                        href : "/" + $(items[i]).attr("alias_path") + ".html",
                        id : "a_" + mid,
                        onclick : function() {
                            if(Interface.bodyWentBottom == 0)
                                return false;
                            var href = this.href;
                            var id = $(this).parent().parent().attr("id").replace("m", "");
                            var this_id = this.id.replace("a_", "");

                            Menu.changeCategory(href, id, this_id, true);

                            return false;
                        }
                    },
                    $(items[i]).attr("name")
            ]);
            
            if (debug)
                {
                
                Menu.menuItemShow(i);
                }
            else
                {
            
            
                setTimeout("Menu.menuItemShow(" + i + ");", i * 300);
                }

            if (i == items.length - 1 && $("#puppet > *").length == 0) {
                // setTimeout('loadSWF("puppet", "man_small.swf?' +
                // Math.random() + '", 189, 930, "swfpuppet");', i * 700);
                
            
                if(getCookie('id_session'))
                {
                Interface.checkPotatoTimer = setInterval("Interface.checkPotato()", 100);
                $("#body").css( {top : "0px"});
                Interface.truncatePotato();
                setTimeout("Interface.moveBodyBottom()", 6000);
                Interface.bodyWentBottom = 1;
                $("#lace").hide();
                $('#potatoCont').show();
                loadSWF("potato", "potato.swf?" + Math.random(), 870, 670);
                $("#potatoCont").attr("class", "truncated");
                }
                else{
                    Ribbon.load=true;//zagruzka stranizy 1-y raz
                setTimeout(function() {
                    if (!debug && (id==0)) {
                        $("#body").animate( {
                            top : -650
                        }, 3000, function() {
                            $('#selSound').css( {
                                display : "none"
                            });
                            $("#body").animate( {
                                top : -800
                            }, 3000);
                            loadSWF("potato", "potato_small2.swf?" + Math.random(), 870, 670);
                            Interface.checkPotatoTimer = setInterval("Interface.checkPotato()", 100);
                            setCookie('id_session',true);
                            //setTimeout('Menu.flag=true',3500);
                            
                        });
                    }
                //}, i * 600);
                }, 600);
                    }
            }
        }
        
        setTimeout('Ribbon.load=false',28000);
        
    },

    changeCategory : function(href, id, this_id, his) {
        

        /*
         * if (his) { Main.historyAdd(href, id, this_id); }
         * if(Interface.bodyWentBottom != 1) return false;
         */
        if (this_id == "207") {
            
            Ribbon.chcategory(0, id, this_id);
            return;    
        }
        if (this_id == "10") {
            $("#mli295").click();
            swap_cal();
        } else {
            //$("#text").removeClass('calendar');
            if ($("item[id=" + this_id + "] > *", Menu.xml).length) {
                Menu.init(this_id);
                //Main.historyAdd('sub', false, false);
                if($("#a_211").length)
                    $("#a_211").click();
                else
                    $("#menu .m:first a").click();
            } else {

                Ribbon.chcategory(0, id, this_id);
                
            }
        }
    },

    menuShowBackButton : function(isShow) // true, false
    {
        isShow ? $("#menu").createAppend('div', {
            className : "btnBack",
            id : "btnBack"
        }, [
                'img',
                {
                    src : _img + "back1.gif",
                    onclick : function() {
                        Menu.menuBack();
                    },
                    onload : function() {
                        this.style.width = "94px";
                        this.style.height = "32px";
                    }
                }
        ]) : $("#btnBack").remove();
    },

    menuBack : function() {
        var Menu_menuid = $("item[id=" + Menu.menuid + "]", Menu.xml).parent().attr("id");
        if(Menu.menuid==4)
            Menu.init(9);
        else
        Menu.init(Menu_menuid);
    },

    menuItemShow : function(id) {
        
        // Инициализация меню
        $("#m" + id).css( {
            top : id * 44 + 100,
            opacity : 0
        }).animate( {
            top : (id * 44 + 175),
            opacity : 1
        },280, function() {
            if (id == 8 && $(this).find('a').text() == 'Calendars') {
                $("#menu").createPrepend("img", {
                    src : _img + "new.gif",
                    width : 79,
                    height : 49,
                    style : "position:absolute;left:140px;top:517px;cursor:pointer;z-index:12",
                    onclick : function() {
                        $("#a_10").click();
                    }
                });
                $("#menu").createPrepend("div", {
                    width : 79,
                    height : 49,
                    style : "position: absolute; cursor: pointer; z-index: 13; left: 169px; font-size: 14px; top: 531px; color: #D5991C;",
                    onclick : function() {
                        $("#a_10").click();
                    }
                    
                }, '2012');
            }
            /*if (id == 8 && $(this).find('a').text()=='Animated E-Cards') {
                $("#menu").createPrepend("img", {
                    src : "/inc/img/video.jpg",
                    width : 45,
                    height : 45,
                    style : "position:absolute;left:179px;top:600px;cursor:pointer;z-index:12",
                    onclick : function() {
                        $("#a_10").click();
                    }
                });
            }*/
        });
    }

};

swap_cc = function() {
    
    //if($('#main_but').find('.mcont').html()=='Still Images')
    {
        Menu.init(0);
        setCookie("rib_id",295);
        Ribbon.chcategory(295);
/*        $.pget("/proc/ribbon/load_list", {
            cid : 295
        }, function(d) {
                $("#ribbon #mask ul").html(d);
                Ribbon.init();
            });
        $.pget("/proc/render/get_content", {
            cid : "c" + 295
        }, function(d) {
            $("#text_block_cont").html(d).jScrollPane( {
                showArrows : true
            });
        });
        $('#rcat dt span').html('Tretyakov Gallery');
        $('#rcat2 dt span').html('Select Category');
    */    
        
    }
    $("#cal_loader").animate( {
        opacity : 1
    }, "fast");
    Card.TitleImage.ID=121;
    if ($("#btnCC").toggleClass('btnCC').hasClass('btnCC')) {
        $("#text").addClass('calendar');
        //console.log($("#ribbon #mask li").html());
        if (Card.TitleImage.ID)
            setTimeout("Calendar.SetImage(121)",1000);
        else
        {
            setTimeout("Calendar.SetImage(121)",1000);
            
        }
        
        $("#calendar_cont #layer").droppable( {
            drop : function(event, ui) {
                Calendar.SetImage(ui.helper.attr("id").replace("img", ""));
            }
        });
    }  else {
        $("#text").removeClass('calendar');
    }
};


swap_cal = function() {
    if(!$("#text").hasClass('calendar')) {
        if ($("#btnCC").toggleClass('btnCC').hasClass('btnCC')) {
            $("#text").addClass('calendar');
            Card.TitleImage.ID=121;
            if (Card.TitleImage.ID)
                setTimeout("Calendar.SetImage(121)",1000);
            else
                setTimeout("Calendar.SetImage(121)",1000);
            $("#calendar_cont #layer").droppable( {
                drop : function(event, ui) {
                    Calendar.SetImage(ui.helper.attr("id").replace("img", ""));
                }
            });
        }
    }
}

function obj2url(obj) {
    var url = "";
    for ( var key in obj) {
        url += key + "=" + escape(obj[key]) + "&";
    }
}

var bnid = 0;
function rotate() {
    banners = [
            '/i/bnet/jewel01.swf?clickTAG=http://trevijewelry.com&clickTARGET=_blank',
            '/i/bnet/armory01.swf?clickTAG=http://treviarmory.com&clickTARGET=_blank'
    ];

    $("#bn").media( {
        width : 320,
        height : 140,
        src : banners[(bnid++) % banners.length],
        attrs : {
            id : "bnswf",
            wmode : 'transparent',
            scale : "noborder",
            quality : "high",
            allowscriptaccess : "sameDomain"
        },
        params : {
            id : "bnswf",
            wmode : 'transparent',
            scale : "noborder",
            quality : "high",
            allowscriptaccess : "sameDomain"
        }
    });
};

_global_loaded_modules = new Array();
function _global_load_module(name, params) {
    if (typeof (_global_loaded_modules[name]) == "undefined") {
        var head = document.getElementsByTagName("head")[0];
        script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = name + "?" + params + "&_r" + Math.random();
        head.appendChild(script);
        _global_loaded_modules.push(name);
    }
};
(function($) {
    jQuery.fn.dropdown = function(options) {
        $.fn.dropdown.defaults = {
            onchange : new Function()
        };
        var opts = $.extend( {}, $.fn.dropdown.defaults, options);

        $(document).click(function(e) {
            if (!$(e.target).parents().hasClass("__dd-dt-list"))
                $(".dropdown dd ul").hide();
        });

        return this.each(function() {
            if ($(this).hasClass("__dd-dt-list"))
                return;
            ($this = $(this)).addClass("__dd-dt-list").show();

            var a = $this.find("dt a").append('<div class="dd_arrow"><!-- --></div>').click(function() {
                $(this).parents('dl.dropdown').find("dd ul").toggle();
                return false;
            });

            $this.find("dd ul li a").click(function() {
                var o = $.meta ? $.extend( {}, opts, $this.data()) : opts;
                $(this).parents('dl.dropdown').find("dt a span").html(this.innerHTML);
                o.onchange($(this).find("span:last").html(), this);
                $(this).parents('dl.dropdown').find("dd ul").hide();
                return false;
            });
        });
    };
})(jQuery);


function fun2()
{
    $.pget('/proc/render/get_title_image',{},function(data){
        
    });
        


    

}

function showFrame() {
    $('#car-1').hide();
    $('#car-2').css({
        'visibility':'visible'
    }).show();
    $('.showFrame').hide();
    $('.showMainMenu').show();
}

function showMainMenu() {
    $('#car-1').show();
    $('#car-2').hide();
    $('.showFrame').show();
    $('.showMainMenu').hide();
}

function renderFrameImg(frameName) {
    //alert(frameName + ' ' + Card.Last.fcsid);
    $id('swfpageflip').setFrameName(frameName + '_print.png');
    //$id('swfpageflip').render_title_image_frame(frameName + '_print.png');
    return false;
}
