/*
* Autocomplete - jQuery plugin 1.0.2 
*
* Copyright (c) 2007 Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, Jörn Zaefferer
*
* Dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
*
* Revision: $Id: jquery.autocomplete.js 5747 2008-06-25 18:30:55Z joern.zaefferer $
*
*/

;(function($) {

$.fn.extend({
autocomplete: function(urlOrData, options) {
var isUrl = typeof urlOrData == "string";
options = $.extend({}, $.Autocompleter.defaults, {
url: isUrl ? urlOrData : null,
data: isUrl ? null : urlOrData,
delay: isUrl ? $.Autocompleter.defaults.delay : 10,
max: options && !options.scroll ? 10 : 150
}, options);

// if highlight is set to false, replace it with a do-nothing function
options.highlight = options.highlight || function(value) { return value; };

// if the formatMatch option is not specified, then use formatItem for backwards compatibility
options.formatMatch = options.formatMatch || options.formatItem;

return this.each(function() {
new $.Autocompleter(this, options);
});
},
result: function(handler) {
return this.bind("result", handler);
},
search: function(handler) {
return this.trigger("search", [handler]);
},
flushCache: function() {
return this.trigger("flushCache");
},
setOptions: function(options){
return this.trigger("setOptions", [options]);
},
unautocomplete: function() {
return this.trigger("unautocomplete");
}
});

$.Autocompleter = function(input, options) {

var KEY = {
UP: 38,
DOWN: 40,
DEL: 46,
TAB: 9,
RETURN: 13,
ESC: 27,
COMMA: 188,
PAGEUP: 33,
PAGEDOWN: 34,
BACKSPACE: 8
};

// Create $ object for input element
var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);

var timeout;
var previousValue = "";
var cache = $.Autocompleter.Cache(options);
var hasFocus = 0;
var lastKeyPressCode;
var config = {
mouseDownOnSelect: false
};
var select = $.Autocompleter.Select(options, input, selectCurrent, config);

var blockSubmit;

// prevent form submit in opera when selecting with return key
$.browser.opera && $(input.form).bind("submit.autocomplete", function() {
if (blockSubmit) {
blockSubmit = false;
return false;
}
});

// only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
$input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
// track last key pressed
lastKeyPressCode = event.keyCode;
switch(event.keyCode) {

case KEY.UP:
event.preventDefault();
if ( select.visible() ) {
select.prev();
} else {
onChange(0, true);
}
break;

case KEY.DOWN:
event.preventDefault();
if ( select.visible() ) {
select.next();
} else {
onChange(0, true);
}
break;

case KEY.PAGEUP:
event.preventDefault();
if ( select.visible() ) {
select.pageUp();
} else {
onChange(0, true);
}
break;

case KEY.PAGEDOWN:
event.preventDefault();
if ( select.visible() ) {
select.pageDown();
} else {
onChange(0, true);
}
break;

// matches also semicolon
case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
case KEY.TAB:
case KEY.RETURN:
if( selectCurrent() ) {
// stop default to prevent a form submit, Opera needs special handling
event.preventDefault();
blockSubmit = true;
return false;
}
break;

case KEY.ESC:
select.hide();
break;

default:
clearTimeout(timeout);
timeout = setTimeout(onChange, options.delay);
break;
}
}).focus(function(){
// track whether the field has focus, we shouldn't process any
// results if the field no longer has focus
hasFocus++;
}).blur(function() {
hasFocus = 0;
if (!config.mouseDownOnSelect) {
hideResults();
}
}).click(function() {
// show select when clicking in a focused field
if ( hasFocus++ > 1 && !select.visible() ) {
onChange(0, true);
}
}).bind("search", function() {
// TODO why not just specifying both arguments?
var fn = (arguments.length > 1) ? arguments[1] : null;
function findValueCallback(q, data) {
var result;
if( data && data.length ) {
for (var i=0; i < data.length; i++) {
if( data[i].result.toLowerCase() == q.toLowerCase() ) {
result = data[i];
break;
}
}
}
if( typeof fn == "function" ) fn(result);
else $input.trigger("result", result && [result.data, result.value]);
}
$.each(trimWords($input.val()), function(i, value) {
request(value, findValueCallback, findValueCallback);
});
}).bind("flushCache", function() {
cache.flush();
}).bind("setOptions", function() {
$.extend(options, arguments[1]);
// if we've updated the data, repopulate
if ( "data" in arguments[1] )
cache.populate();
}).bind("unautocomplete", function() {
select.unbind();
$input.unbind();
$(input.form).unbind(".autocomplete");
});


function selectCurrent() {
var selected = select.selected();
if( !selected )
return false;

var v = selected.result;
previousValue = v;

if ( options.multiple ) {
var words = trimWords($input.val());
if ( words.length > 1 ) {
v = words.slice(0, words.length - 1).join( options.multipleSeparator ) + options.multipleSeparator + v;
}
v += options.multipleSeparator;
}

$input.val(v);
hideResultsNow();
$input.trigger("result", [selected.data, selected.value]);
return true;
}

function onChange(crap, skipPrevCheck) {
if( lastKeyPressCode == KEY.DEL ) {
select.hide();
return;
}

var currentValue = $input.val();

if ( !skipPrevCheck && currentValue == previousValue )
return;

previousValue = currentValue;

currentValue = lastWord(currentValue);
if ( currentValue.length >= options.minChars) {
$input.addClass(options.loadingClass);
if (!options.matchCase)
currentValue = currentValue.toLowerCase();
request(currentValue, receiveData, hideResultsNow);
} else {
stopLoading();
select.hide();
}
};

function trimWords(value) {
if ( !value ) {
return [""];
}
var words = value.split( options.multipleSeparator );
var result = [];
$.each(words, function(i, value) {
if ( $.trim(value) )
result[i] = $.trim(value);
});
return result;
}

function lastWord(value) {
if ( !options.multiple )
return value;
var words = trimWords(value);
return words[words.length - 1];
}

// fills in the input box w/the first match (assumed to be the best match)
// q: the term entered
// sValue: the first matching result
function autoFill(q, sValue){
// autofill in the complete box w/the first match as long as the user hasn't entered in more data
// if the last user key pressed was backspace, don't autofill
if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) {
// fill in the value (keep the case the user has typed)
$input.val($input.val() + sValue.substring(lastWord(previousValue).length));
// select the portion of the value not typed by the user (so the next character will erase)
$.Autocompleter.Selection(input, previousValue.length, previousValue.length + sValue.length);
}
};

function hideResults() {
clearTimeout(timeout);
timeout = setTimeout(hideResultsNow, 200);
};

function hideResultsNow() {
var wasVisible = select.visible();
select.hide();
clearTimeout(timeout);
stopLoading();
if (options.mustMatch) {
// call search and run callback
$input.search(
function (result){
// if no value found, clear the input box
if( !result ) {
if (options.multiple) {
var words = trimWords($input.val()).slice(0, -1);
$input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") );
}
else
$input.val( "" );
}
}
);
}
if (wasVisible)
// position cursor at end of input field
$.Autocompleter.Selection(input, input.value.length, input.value.length);
};

function receiveData(q, data) {
if ( data && data.length && hasFocus ) {
stopLoading();
select.display(data, q);
autoFill(q, data[0].value);
select.show();
} else {
hideResultsNow();
}
};

function request(term, success, failure) {
if (!options.matchCase)
term = term.toLowerCase();
var data = cache.load(term);
// recieve the cached data
if (data && data.length) {
success(term, data);
// if an AJAX url has been supplied, try loading the data now
} else if( (typeof options.url == "string") && (options.url.length > 0) ){

var extraParams = {
timestamp: +new Date()
};
$.each(options.extraParams, function(key, param) {
extraParams[key] = typeof param == "function" ? param() : param;
});

$.ajax({
// try to leverage ajaxQueue plugin to abort previous requests
mode: "abort",
// limit abortion to this input
port: "autocomplete" + input.name,
dataType: options.dataType,
url: options.url,
data: $.extend({
q: lastWord(term),
limit: options.max
}, extraParams),
success: function(data) {
var parsed = options.parse && options.parse(data) || parse(data);
cache.add(term, parsed);
success(term, parsed);
}
});
} else {
// if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
select.emptyList();
failure(term);
}
};

function parse(data) {
var parsed = [];
var rows = data.split("\n");
for (var i=0; i < rows.length; i++) {
var row = $.trim(rows[i]);
if (row) {
row = row.split("|");
parsed[parsed.length] = {
data: row,
value: row[0],
result: options.formatResult && options.formatResult(row, row[0]) || row[0]
};
}
}
return parsed;
};

function stopLoading() {
$input.removeClass(options.loadingClass);
};

};

$.Autocompleter.defaults = {
inputClass: "ac_input",
resultsClass: "ac_results",
loadingClass: "ac_loading",
minChars: 1,
delay: 400,
matchCase: false,
matchSubset: true,
matchContains: false,
cacheLength: 10,
max: 100,
mustMatch: false,
extraParams: {},
selectFirst: true,
formatItem: function(row) { return row[0]; },
formatMatch: null,
autoFill: false,
width: 0,
multiple: false,
multipleSeparator: ", ",
highlight: function(value, term) {
return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
},
scroll: true,
scrollHeight: 180
};

$.Autocompleter.Cache = function(options) {

var data = {};
var length = 0;

function matchSubset(s, sub) {
if (!options.matchCase) 
s = s.toLowerCase();
var i = s.indexOf(sub);
if (i == -1) return false;
return i == 0 || options.matchContains;
};

function add(q, value) {
if (length > options.cacheLength){
flush();
}
if (!data[q]){ 
length++;
}
data[q] = value;
}

function populate(){
if( !options.data ) return false;
// track the matches
var stMatchSets = {},
nullData = 0;

// no url was specified, we need to adjust the cache length to make sure it fits the local data store
if( !options.url ) options.cacheLength = 1;

// track all options for minChars = 0
stMatchSets[""] = [];

// loop through the array and create a lookup structure
for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
var rawValue = options.data[i];
// if rawValue is a string, make an array otherwise just reference the array
rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;

var value = options.formatMatch(rawValue, i+1, options.data.length);
if ( value === false )
continue;

var firstChar = value.charAt(0).toLowerCase();
// if no lookup array for this character exists, look it up now
if( !stMatchSets[firstChar] ) 
stMatchSets[firstChar] = [];

// if the match is a string
var row = {
value: value,
data: rawValue,
result: options.formatResult && options.formatResult(rawValue) || value
};

// push the current match into the set list
stMatchSets[firstChar].push(row);

// keep track of minChars zero items
if ( nullData++ < options.max ) {
stMatchSets[""].push(row);
}
};

// add the data items to the cache
$.each(stMatchSets, function(i, value) {
// increase the cache size
options.cacheLength++;
// add to the cache
add(i, value);
});
}

// populate any existing data
setTimeout(populate, 25);

function flush(){
data = {};
length = 0;
}

return {
flush: flush,
add: add,
populate: populate,
load: function(q) {
if (!options.cacheLength || !length)
return null;
/* 
* if dealing w/local data and matchContains than we must make sure
* to loop through all the data collections looking for matches
*/
if( !options.url && options.matchContains ){
// track all matches
var csub = [];
// loop through all the data grids for matches
for( var k in data ){
// don't search through the stMatchSets[""] (minChars: 0) cache
// this prevents duplicates
if( k.length > 0 ){
var c = data[k];
$.each(c, function(i, x) {
// if we've got a match, add it to the array
if (matchSubset(x.value, q)) {
csub.push(x);
}
});
}
}				
return csub;
} else 
// if the exact item exists, use it
if (data[q]){
return data[q];
} else
if (options.matchSubset) {
for (var i = q.length - 1; i >= options.minChars; i--) {
var c = data[q.substr(0, i)];
if (c) {
var csub = [];
$.each(c, function(i, x) {
if (matchSubset(x.value, q)) {
csub[csub.length] = x;
}
});
return csub;
}
}
}
return null;
}
};
};

$.Autocompleter.Select = function (options, input, select, config) {
var CLASSES = {
ACTIVE: "ac_over"
};

var listItems,
active = -1,
data,
term = "",
needsInit = true,
element,
list;

// Create results
function init() {
if (!needsInit)
return;
element = $("<div/>")
.hide()
.addClass(options.resultsClass)
.css("position", "absolute")
.appendTo(document.body);

list = $("<ul/>").appendTo(element).mouseover( function(event) {
if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
$(target(event)).addClass(CLASSES.ACTIVE);            
}
}).click(function(event) {
$(target(event)).addClass(CLASSES.ACTIVE);
select();
// TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
input.focus();
return false;
}).mousedown(function() {
config.mouseDownOnSelect = true;
}).mouseup(function() {
config.mouseDownOnSelect = false;
});

if( options.width > 0 )
element.css("width", options.width);

needsInit = false;
} 

function target(event) {
var element = event.target;
while(element && element.tagName != "LI")
element = element.parentNode;
// more fun with IE, sometimes event.target is empty, just ignore it then
if(!element)
return [];
return element;
}

function moveSelect(step) {
listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
movePosition(step);
var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
if(options.scroll) {
var offset = 0;
listItems.slice(0, active).each(function() {
offset += this.offsetHeight;
});
if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
} else if(offset < list.scrollTop()) {
list.scrollTop(offset);
}
}
};

function movePosition(step) {
active += step;
if (active < 0) {
active = listItems.size() - 1;
} else if (active >= listItems.size()) {
active = 0;
}
}

function limitNumberOfItems(available) {
return options.max && options.max < available
? options.max
: available;
}

function fillList() {
list.empty();
var max = limitNumberOfItems(data.length);
for (var i=0; i < max; i++) {
if (!data[i])
continue;
var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term);
if ( formatted === false )
continue;
var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
$.data(li, "ac_data", data[i]);
}
listItems = list.find("li");
if ( options.selectFirst ) {
listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
active = 0;
}
// apply bgiframe if available
if ( $.fn.bgiframe )
list.bgiframe();
}

return {
display: function(d, q) {
init();
data = d;
term = q;
fillList();
},
next: function() {
moveSelect(1);
},
prev: function() {
moveSelect(-1);
},
pageUp: function() {
if (active != 0 && active - 8 < 0) {
moveSelect( -active );
} else {
moveSelect(-8);
}
},
pageDown: function() {
if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
moveSelect( listItems.size() - 1 - active );
} else {
moveSelect(8);
}
},
hide: function() {
element && element.hide();
listItems && listItems.removeClass(CLASSES.ACTIVE);
active = -1;
},
visible : function() {
return element && element.is(":visible");
},
current: function() {
return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
},
show: function() {
var offset = $(input).offset();
element.css({
width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
top: offset.top + input.offsetHeight,
left: offset.left
}).show();
if(options.scroll) {
list.scrollTop(0);
list.css({
maxHeight: options.scrollHeight,
overflow: 'auto'
});

if($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
var listHeight = 0;
listItems.each(function() {
listHeight += this.offsetHeight;
});
var scrollbarsVisible = listHeight > options.scrollHeight;
list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight );
if (!scrollbarsVisible) {
// IE doesn't recalculate width when scrollbar disappears
listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );
}
}

}
},
selected: function() {
var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
return selected && selected.length && $.data(selected[0], "ac_data");
},
emptyList: function (){
list && list.empty();
},
unbind: function() {
element && element.remove();
}
};
};

$.Autocompleter.Selection = function(field, start, end) {
if( field.createTextRange ){
var selRange = field.createTextRange();
selRange.collapse(true);
selRange.moveStart("character", start);
selRange.moveEnd("character", end);
selRange.select();
} else if( field.setSelectionRange ){
field.setSelectionRange(start, end);
} else {
if( field.selectionStart ){
field.selectionStart = start;
field.selectionEnd = end;
}
}
field.focus();
};

})(jQuery);

/*
 * jQuery Cycle Plugin (core engine)
 * Examples and documentation at: http://jquery.malsup.com/cycle/
 * Copyright (c) 2007-2010 M. Alsup
 * Version: 2.88 (08-JUN-2010)
 * Dual licensed under the MIT and GPL licenses.
 * http://jquery.malsup.com/license.html
 * Requires: jQuery v1.2.6 or later
 */
(function($){var ver="2.88";if($.support==undefined){$.support={opacity:!($.browser.msie)};}function debug(s){if($.fn.cycle.debug){log(s);}}function log(){if(window.console&&window.console.log){window.console.log("[cycle] "+Array.prototype.join.call(arguments," "));}}$.fn.cycle=function(options,arg2){var o={s:this.selector,c:this.context};if(this.length===0&&options!="stop"){if(!$.isReady&&o.s){log("DOM not ready, queuing slideshow");$(function(){$(o.s,o.c).cycle(options,arg2);});return this;}log("terminating; zero elements found by selector"+($.isReady?"":" (DOM not ready)"));return this;}return this.each(function(){var opts=handleArguments(this,options,arg2);if(opts===false){return;}opts.updateActivePagerLink=opts.updateActivePagerLink||$.fn.cycle.updateActivePagerLink;if(this.cycleTimeout){clearTimeout(this.cycleTimeout);}this.cycleTimeout=this.cyclePause=0;var $cont=$(this);var $slides=opts.slideExpr?$(opts.slideExpr,this):$cont.children();var els=$slides.get();if(els.length<2){log("terminating; too few slides: "+els.length);return;}var opts2=buildOptions($cont,$slides,els,opts,o);if(opts2===false){return;}var startTime=opts2.continuous?10:getTimeout(els[opts2.currSlide],els[opts2.nextSlide],opts2,!opts2.rev);if(startTime){startTime+=(opts2.delay||0);if(startTime<10){startTime=10;}debug("first timeout: "+startTime);this.cycleTimeout=setTimeout(function(){go(els,opts2,0,(!opts2.rev&&!opts.backwards));},startTime);}});};function handleArguments(cont,options,arg2){if(cont.cycleStop==undefined){cont.cycleStop=0;}if(options===undefined||options===null){options={};}if(options.constructor==String){switch(options){case"destroy":case"stop":var opts=$(cont).data("cycle.opts");if(!opts){return false;}cont.cycleStop++;if(cont.cycleTimeout){clearTimeout(cont.cycleTimeout);}cont.cycleTimeout=0;$(cont).removeData("cycle.opts");if(options=="destroy"){destroy(opts);}return false;case"toggle":cont.cyclePause=(cont.cyclePause===1)?0:1;checkInstantResume(cont.cyclePause,arg2,cont);return false;case"pause":cont.cyclePause=1;return false;case"resume":cont.cyclePause=0;checkInstantResume(false,arg2,cont);return false;case"prev":case"next":var opts=$(cont).data("cycle.opts");if(!opts){log('options not found, "prev/next" ignored');return false;}$.fn.cycle[options](opts);return false;default:options={fx:options};}return options;}else{if(options.constructor==Number){var num=options;options=$(cont).data("cycle.opts");if(!options){log("options not found, can not advance slide");return false;}if(num<0||num>=options.elements.length){log("invalid slide index: "+num);return false;}options.nextSlide=num;if(cont.cycleTimeout){clearTimeout(cont.cycleTimeout);cont.cycleTimeout=0;}if(typeof arg2=="string"){options.oneTimeFx=arg2;}go(options.elements,options,1,num>=options.currSlide);return false;}}return options;function checkInstantResume(isPaused,arg2,cont){if(!isPaused&&arg2===true){var options=$(cont).data("cycle.opts");if(!options){log("options not found, can not resume");return false;}if(cont.cycleTimeout){clearTimeout(cont.cycleTimeout);cont.cycleTimeout=0;}go(options.elements,options,1,(!opts.rev&&!opts.backwards));}}}function removeFilter(el,opts){if(!$.support.opacity&&opts.cleartype&&el.style.filter){try{el.style.removeAttribute("filter");}catch(smother){}}}function destroy(opts){if(opts.next){$(opts.next).unbind(opts.prevNextEvent);}if(opts.prev){$(opts.prev).unbind(opts.prevNextEvent);}if(opts.pager||opts.pagerAnchorBuilder){$.each(opts.pagerAnchors||[],function(){this.unbind().remove();});}opts.pagerAnchors=null;if(opts.destroy){opts.destroy(opts);}}function buildOptions($cont,$slides,els,options,o){var opts=$.extend({},$.fn.cycle.defaults,options||{},$.metadata?$cont.metadata():$.meta?$cont.data():{});if(opts.autostop){opts.countdown=opts.autostopCount||els.length;}var cont=$cont[0];$cont.data("cycle.opts",opts);opts.$cont=$cont;opts.stopCount=cont.cycleStop;opts.elements=els;opts.before=opts.before?[opts.before]:[];opts.after=opts.after?[opts.after]:[];opts.after.unshift(function(){opts.busy=0;});if(!$.support.opacity&&opts.cleartype){opts.after.push(function(){removeFilter(this,opts);});}if(opts.continuous){opts.after.push(function(){go(els,opts,0,(!opts.rev&&!opts.backwards));});}saveOriginalOpts(opts);if(!$.support.opacity&&opts.cleartype&&!opts.cleartypeNoBg){clearTypeFix($slides);}if($cont.css("position")=="static"){$cont.css("position","relative");}if(opts.width){$cont.width(opts.width);}if(opts.height&&opts.height!="auto"){$cont.height(opts.height);}if(opts.startingSlide){opts.startingSlide=parseInt(opts.startingSlide);}else{if(opts.backwards){opts.startingSlide=els.length-1;}}if(opts.random){opts.randomMap=[];for(var i=0;i<els.length;i++){opts.randomMap.push(i);}opts.randomMap.sort(function(a,b){return Math.random()-0.5;});opts.randomIndex=1;opts.startingSlide=opts.randomMap[1];}else{if(opts.startingSlide>=els.length){opts.startingSlide=0;}}opts.currSlide=opts.startingSlide||0;var first=opts.startingSlide;$slides.css({position:"absolute",top:0,left:0}).hide().each(function(i){var z;if(opts.backwards){z=first?i<=first?els.length+(i-first):first-i:els.length-i;}else{z=first?i>=first?els.length-(i-first):first-i:els.length-i;}$(this).css("z-index",z);});$(els[first]).css("opacity",1).show();removeFilter(els[first],opts);if(opts.fit&&opts.width){$slides.width(opts.width);}if(opts.fit&&opts.height&&opts.height!="auto"){$slides.height(opts.height);}var reshape=opts.containerResize&&!$cont.innerHeight();if(reshape){var maxw=0,maxh=0;for(var j=0;j<els.length;j++){var $e=$(els[j]),e=$e[0],w=$e.outerWidth(),h=$e.outerHeight();if(!w){w=e.offsetWidth||e.width||$e.attr("width");}if(!h){h=e.offsetHeight||e.height||$e.attr("height");}maxw=w>maxw?w:maxw;maxh=h>maxh?h:maxh;}if(maxw>0&&maxh>0){$cont.css({width:maxw+"px",height:maxh+"px"});}}if(opts.pause){$cont.hover(function(){this.cyclePause++;},function(){this.cyclePause--;});}if(supportMultiTransitions(opts)===false){return false;}var requeue=false;options.requeueAttempts=options.requeueAttempts||0;$slides.each(function(){var $el=$(this);this.cycleH=(opts.fit&&opts.height)?opts.height:($el.height()||this.offsetHeight||this.height||$el.attr("height")||0);this.cycleW=(opts.fit&&opts.width)?opts.width:($el.width()||this.offsetWidth||this.width||$el.attr("width")||0);if($el.is("img")){var loadingIE=($.browser.msie&&this.cycleW==28&&this.cycleH==30&&!this.complete);var loadingFF=($.browser.mozilla&&this.cycleW==34&&this.cycleH==19&&!this.complete);var loadingOp=($.browser.opera&&((this.cycleW==42&&this.cycleH==19)||(this.cycleW==37&&this.cycleH==17))&&!this.complete);var loadingOther=(this.cycleH==0&&this.cycleW==0&&!this.complete);if(loadingIE||loadingFF||loadingOp||loadingOther){if(o.s&&opts.requeueOnImageNotLoaded&&++options.requeueAttempts<100){log(options.requeueAttempts," - img slide not loaded, requeuing slideshow: ",this.src,this.cycleW,this.cycleH);setTimeout(function(){$(o.s,o.c).cycle(options);},opts.requeueTimeout);requeue=true;return false;}else{log("could not determine size of image: "+this.src,this.cycleW,this.cycleH);}}}return true;});if(requeue){return false;}opts.cssBefore=opts.cssBefore||{};opts.animIn=opts.animIn||{};opts.animOut=opts.animOut||{};$slides.not(":eq("+first+")").css(opts.cssBefore);if(opts.cssFirst){$($slides[first]).css(opts.cssFirst);}if(opts.timeout){opts.timeout=parseInt(opts.timeout);if(opts.speed.constructor==String){opts.speed=$.fx.speeds[opts.speed]||parseInt(opts.speed);}if(!opts.sync){opts.speed=opts.speed/2;}var buffer=opts.fx=="shuffle"?500:250;while((opts.timeout-opts.speed)<buffer){opts.timeout+=opts.speed;}}if(opts.easing){opts.easeIn=opts.easeOut=opts.easing;}if(!opts.speedIn){opts.speedIn=opts.speed;}if(!opts.speedOut){opts.speedOut=opts.speed;}opts.slideCount=els.length;opts.currSlide=opts.lastSlide=first;if(opts.random){if(++opts.randomIndex==els.length){opts.randomIndex=0;}opts.nextSlide=opts.randomMap[opts.randomIndex];}else{if(opts.backwards){opts.nextSlide=opts.startingSlide==0?(els.length-1):opts.startingSlide-1;}else{opts.nextSlide=opts.startingSlide>=(els.length-1)?0:opts.startingSlide+1;}}if(!opts.multiFx){var init=$.fn.cycle.transitions[opts.fx];if($.isFunction(init)){init($cont,$slides,opts);}else{if(opts.fx!="custom"&&!opts.multiFx){log("unknown transition: "+opts.fx,"; slideshow terminating");return false;}}}var e0=$slides[first];if(opts.before.length){opts.before[0].apply(e0,[e0,e0,opts,true]);}if(opts.after.length>1){opts.after[1].apply(e0,[e0,e0,opts,true]);}if(opts.next){$(opts.next).bind(opts.prevNextEvent,function(){return advance(opts,opts.rev?-1:1);});}if(opts.prev){$(opts.prev).bind(opts.prevNextEvent,function(){return advance(opts,opts.rev?1:-1);});}if(opts.pager||opts.pagerAnchorBuilder){buildPager(els,opts);}exposeAddSlide(opts,els);return opts;}function saveOriginalOpts(opts){opts.original={before:[],after:[]};opts.original.cssBefore=$.extend({},opts.cssBefore);opts.original.cssAfter=$.extend({},opts.cssAfter);opts.original.animIn=$.extend({},opts.animIn);opts.original.animOut=$.extend({},opts.animOut);$.each(opts.before,function(){opts.original.before.push(this);});$.each(opts.after,function(){opts.original.after.push(this);});}function supportMultiTransitions(opts){var i,tx,txs=$.fn.cycle.transitions;if(opts.fx.indexOf(",")>0){opts.multiFx=true;opts.fxs=opts.fx.replace(/\s*/g,"").split(",");for(i=0;i<opts.fxs.length;i++){var fx=opts.fxs[i];tx=txs[fx];if(!tx||!txs.hasOwnProperty(fx)||!$.isFunction(tx)){log("discarding unknown transition: ",fx);opts.fxs.splice(i,1);i--;}}if(!opts.fxs.length){log("No valid transitions named; slideshow terminating.");return false;}}else{if(opts.fx=="all"){opts.multiFx=true;opts.fxs=[];for(p in txs){tx=txs[p];if(txs.hasOwnProperty(p)&&$.isFunction(tx)){opts.fxs.push(p);}}}}if(opts.multiFx&&opts.randomizeEffects){var r1=Math.floor(Math.random()*20)+30;for(i=0;i<r1;i++){var r2=Math.floor(Math.random()*opts.fxs.length);opts.fxs.push(opts.fxs.splice(r2,1)[0]);}debug("randomized fx sequence: ",opts.fxs);}return true;}function exposeAddSlide(opts,els){opts.addSlide=function(newSlide,prepend){var $s=$(newSlide),s=$s[0];if(!opts.autostopCount){opts.countdown++;}els[prepend?"unshift":"push"](s);if(opts.els){opts.els[prepend?"unshift":"push"](s);}opts.slideCount=els.length;$s.css("position","absolute");$s[prepend?"prependTo":"appendTo"](opts.$cont);if(prepend){opts.currSlide++;opts.nextSlide++;}if(!$.support.opacity&&opts.cleartype&&!opts.cleartypeNoBg){clearTypeFix($s);}if(opts.fit&&opts.width){$s.width(opts.width);}if(opts.fit&&opts.height&&opts.height!="auto"){$slides.height(opts.height);}s.cycleH=(opts.fit&&opts.height)?opts.height:$s.height();s.cycleW=(opts.fit&&opts.width)?opts.width:$s.width();$s.css(opts.cssBefore);if(opts.pager||opts.pagerAnchorBuilder){$.fn.cycle.createPagerAnchor(els.length-1,s,$(opts.pager),els,opts);}if($.isFunction(opts.onAddSlide)){opts.onAddSlide($s);}else{$s.hide();}};}$.fn.cycle.resetState=function(opts,fx){fx=fx||opts.fx;opts.before=[];opts.after=[];opts.cssBefore=$.extend({},opts.original.cssBefore);opts.cssAfter=$.extend({},opts.original.cssAfter);opts.animIn=$.extend({},opts.original.animIn);opts.animOut=$.extend({},opts.original.animOut);opts.fxFn=null;$.each(opts.original.before,function(){opts.before.push(this);});$.each(opts.original.after,function(){opts.after.push(this);});var init=$.fn.cycle.transitions[fx];if($.isFunction(init)){init(opts.$cont,$(opts.elements),opts);}};function go(els,opts,manual,fwd){if(manual&&opts.busy&&opts.manualTrump){debug("manualTrump in go(), stopping active transition");$(els).stop(true,true);opts.busy=false;}if(opts.busy){debug("transition active, ignoring new tx request");return;}var p=opts.$cont[0],curr=els[opts.currSlide],next=els[opts.nextSlide];if(p.cycleStop!=opts.stopCount||p.cycleTimeout===0&&!manual){return;}if(!manual&&!p.cyclePause&&!opts.bounce&&((opts.autostop&&(--opts.countdown<=0))||(opts.nowrap&&!opts.random&&opts.nextSlide<opts.currSlide))){if(opts.end){opts.end(opts);}return;}var changed=false;if((manual||!p.cyclePause)&&(opts.nextSlide!=opts.currSlide)){changed=true;var fx=opts.fx;curr.cycleH=curr.cycleH||$(curr).height();curr.cycleW=curr.cycleW||$(curr).width();next.cycleH=next.cycleH||$(next).height();next.cycleW=next.cycleW||$(next).width();if(opts.multiFx){if(opts.lastFx==undefined||++opts.lastFx>=opts.fxs.length){opts.lastFx=0;}fx=opts.fxs[opts.lastFx];opts.currFx=fx;}if(opts.oneTimeFx){fx=opts.oneTimeFx;opts.oneTimeFx=null;}$.fn.cycle.resetState(opts,fx);if(opts.before.length){$.each(opts.before,function(i,o){if(p.cycleStop!=opts.stopCount){return;}o.apply(next,[curr,next,opts,fwd]);});}var after=function(){$.each(opts.after,function(i,o){if(p.cycleStop!=opts.stopCount){return;}o.apply(next,[curr,next,opts,fwd]);});};debug("tx firing; currSlide: "+opts.currSlide+"; nextSlide: "+opts.nextSlide);opts.busy=1;if(opts.fxFn){opts.fxFn(curr,next,opts,after,fwd,manual&&opts.fastOnEvent);}else{if($.isFunction($.fn.cycle[opts.fx])){$.fn.cycle[opts.fx](curr,next,opts,after,fwd,manual&&opts.fastOnEvent);}else{$.fn.cycle.custom(curr,next,opts,after,fwd,manual&&opts.fastOnEvent);}}}if(changed||opts.nextSlide==opts.currSlide){opts.lastSlide=opts.currSlide;if(opts.random){opts.currSlide=opts.nextSlide;if(++opts.randomIndex==els.length){opts.randomIndex=0;}opts.nextSlide=opts.randomMap[opts.randomIndex];if(opts.nextSlide==opts.currSlide){opts.nextSlide=(opts.currSlide==opts.slideCount-1)?0:opts.currSlide+1;}}else{if(opts.backwards){var roll=(opts.nextSlide-1)<0;if(roll&&opts.bounce){opts.backwards=!opts.backwards;opts.nextSlide=1;opts.currSlide=0;}else{opts.nextSlide=roll?(els.length-1):opts.nextSlide-1;opts.currSlide=roll?0:opts.nextSlide+1;}}else{var roll=(opts.nextSlide+1)==els.length;if(roll&&opts.bounce){opts.backwards=!opts.backwards;opts.nextSlide=els.length-2;opts.currSlide=els.length-1;}else{opts.nextSlide=roll?0:opts.nextSlide+1;opts.currSlide=roll?els.length-1:opts.nextSlide-1;}}}}if(changed&&opts.pager){opts.updateActivePagerLink(opts.pager,opts.currSlide,opts.activePagerClass);}var ms=0;if(opts.timeout&&!opts.continuous){ms=getTimeout(els[opts.currSlide],els[opts.nextSlide],opts,fwd);}else{if(opts.continuous&&p.cyclePause){ms=10;}}if(ms>0){p.cycleTimeout=setTimeout(function(){go(els,opts,0,(!opts.rev&&!opts.backwards));},ms);}}$.fn.cycle.updateActivePagerLink=function(pager,currSlide,clsName){$(pager).each(function(){$(this).children().removeClass(clsName).eq(currSlide).addClass(clsName);});};function getTimeout(curr,next,opts,fwd){if(opts.timeoutFn){var t=opts.timeoutFn.call(curr,curr,next,opts,fwd);while((t-opts.speed)<250){t+=opts.speed;}debug("calculated timeout: "+t+"; speed: "+opts.speed);if(t!==false){return t;}}return opts.timeout;}$.fn.cycle.next=function(opts){advance(opts,opts.rev?-1:1);};$.fn.cycle.prev=function(opts){advance(opts,opts.rev?1:-1);};function advance(opts,val){var els=opts.elements;var p=opts.$cont[0],timeout=p.cycleTimeout;if(timeout){clearTimeout(timeout);p.cycleTimeout=0;}if(opts.random&&val<0){opts.randomIndex--;if(--opts.randomIndex==-2){opts.randomIndex=els.length-2;}else{if(opts.randomIndex==-1){opts.randomIndex=els.length-1;}}opts.nextSlide=opts.randomMap[opts.randomIndex];}else{if(opts.random){opts.nextSlide=opts.randomMap[opts.randomIndex];}else{opts.nextSlide=opts.currSlide+val;if(opts.nextSlide<0){if(opts.nowrap){return false;}opts.nextSlide=els.length-1;}else{if(opts.nextSlide>=els.length){if(opts.nowrap){return false;}opts.nextSlide=0;}}}}var cb=opts.onPrevNextEvent||opts.prevNextClick;if($.isFunction(cb)){cb(val>0,opts.nextSlide,els[opts.nextSlide]);}go(els,opts,1,val>=0);return false;}function buildPager(els,opts){var $p=$(opts.pager);$.each(els,function(i,o){$.fn.cycle.createPagerAnchor(i,o,$p,els,opts);});opts.updateActivePagerLink(opts.pager,opts.startingSlide,opts.activePagerClass);}$.fn.cycle.createPagerAnchor=function(i,el,$p,els,opts){var a;if($.isFunction(opts.pagerAnchorBuilder)){a=opts.pagerAnchorBuilder(i,el);debug("pagerAnchorBuilder("+i+", el) returned: "+a);}else{a='<a href="#">'+(i+1)+"</a>";}if(!a){return;}var $a=$(a);if($a.parents("body").length===0){var arr=[];if($p.length>1){$p.each(function(){var $clone=$a.clone(true);$(this).append($clone);arr.push($clone[0]);});$a=$(arr);}else{$a.appendTo($p);}}opts.pagerAnchors=opts.pagerAnchors||[];opts.pagerAnchors.push($a);$a.bind(opts.pagerEvent,function(e){e.preventDefault();opts.nextSlide=i;var p=opts.$cont[0],timeout=p.cycleTimeout;if(timeout){clearTimeout(timeout);p.cycleTimeout=0;}var cb=opts.onPagerEvent||opts.pagerClick;if($.isFunction(cb)){cb(opts.nextSlide,els[opts.nextSlide]);}go(els,opts,1,opts.currSlide<i);});if(!/^click/.test(opts.pagerEvent)&&!opts.allowPagerClickBubble){$a.bind("click.cycle",function(){return false;});}if(opts.pauseOnPagerHover){$a.hover(function(){opts.$cont[0].cyclePause++;},function(){opts.$cont[0].cyclePause--;});}};$.fn.cycle.hopsFromLast=function(opts,fwd){var hops,l=opts.lastSlide,c=opts.currSlide;if(fwd){hops=c>l?c-l:opts.slideCount-l;}else{hops=c<l?l-c:l+opts.slideCount-c;}return hops;};function clearTypeFix($slides){debug("applying clearType background-color hack");function hex(s){s=parseInt(s).toString(16);return s.length<2?"0"+s:s;}function getBg(e){for(;e&&e.nodeName.toLowerCase()!="html";e=e.parentNode){var v=$.css(e,"background-color");if(v.indexOf("rgb")>=0){var rgb=v.match(/\d+/g);return"#"+hex(rgb[0])+hex(rgb[1])+hex(rgb[2]);}if(v&&v!="transparent"){return v;}}return"#ffffff";}$slides.each(function(){$(this).css("background-color",getBg(this));});}$.fn.cycle.commonReset=function(curr,next,opts,w,h,rev){$(opts.elements).not(curr).hide();opts.cssBefore.opacity=1;opts.cssBefore.display="block";if(w!==false&&next.cycleW>0){opts.cssBefore.width=next.cycleW;}if(h!==false&&next.cycleH>0){opts.cssBefore.height=next.cycleH;}opts.cssAfter=opts.cssAfter||{};opts.cssAfter.display="none";$(curr).css("zIndex",opts.slideCount+(rev===true?1:0));$(next).css("zIndex",opts.slideCount+(rev===true?0:1));};$.fn.cycle.custom=function(curr,next,opts,cb,fwd,speedOverride){var $l=$(curr),$n=$(next);var speedIn=opts.speedIn,speedOut=opts.speedOut,easeIn=opts.easeIn,easeOut=opts.easeOut;$n.css(opts.cssBefore);if(speedOverride){if(typeof speedOverride=="number"){speedIn=speedOut=speedOverride;}else{speedIn=speedOut=1;}easeIn=easeOut=null;}var fn=function(){$n.animate(opts.animIn,speedIn,easeIn,cb);};$l.animate(opts.animOut,speedOut,easeOut,function(){if(opts.cssAfter){$l.css(opts.cssAfter);}if(!opts.sync){fn();}});if(opts.sync){fn();}};$.fn.cycle.transitions={fade:function($cont,$slides,opts){$slides.not(":eq("+opts.currSlide+")").css("opacity",0);opts.before.push(function(curr,next,opts){$.fn.cycle.commonReset(curr,next,opts);opts.cssBefore.opacity=0;});opts.animIn={opacity:1};opts.animOut={opacity:0};opts.cssBefore={top:0,left:0};}};$.fn.cycle.ver=function(){return ver;};$.fn.cycle.defaults={fx:"fade",timeout:4000,timeoutFn:null,continuous:0,speed:1000,speedIn:null,speedOut:null,next:null,prev:null,onPrevNextEvent:null,prevNextEvent:"click.cycle",pager:null,onPagerEvent:null,pagerEvent:"click.cycle",allowPagerClickBubble:false,pagerAnchorBuilder:null,before:null,after:null,end:null,easing:null,easeIn:null,easeOut:null,shuffle:null,animIn:null,animOut:null,cssBefore:null,cssAfter:null,fxFn:null,height:"auto",startingSlide:0,sync:1,random:0,fit:0,containerResize:1,pause:0,pauseOnPagerHover:0,autostop:0,autostopCount:0,delay:0,slideExpr:null,cleartype:!$.support.opacity,cleartypeNoBg:false,nowrap:0,fastOnEvent:0,randomizeEffects:1,rev:0,manualTrump:true,requeueOnImageNotLoaded:true,requeueTimeout:250,activePagerClass:"activeSlide",updateActivePagerLink:null,backwards:false};})(jQuery);

/*
* jQuery Form Plugin
* version: 2.17 (06-NOV-2008)
* @requires jQuery v1.2.2 or later
*
* Examples and documentation at: http://malsup.com/jquery/form/
* Dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
*
* Revision: $Id$
*/
;(function($) {

/*
Usage Note:  
-----------
Do not use both ajaxSubmit and ajaxForm on the same form.  These
functions are intended to be exclusive.  Use ajaxSubmit if you want
to bind your own submit handler to the form.  For example,

$(document).ready(function() {
$('#myForm').bind('submit', function() {
$(this).ajaxSubmit({
target: '#output'
});
return false; // <-- important!
});
});

Use ajaxForm when you want the plugin to manage all the event binding
for you.  For example,

$(document).ready(function() {
$('#myForm').ajaxForm({
target: '#output'
});
});

When using ajaxForm, the ajaxSubmit function will be invoked for you
at the appropriate time.  
*/

/**
* ajaxSubmit() provides a mechanism for immediately submitting 
* an HTML form using AJAX.
*/
$.fn.ajaxSubmit = function(options) {
// fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
if (!this.length) {
log('ajaxSubmit: skipping submit process - no element selected');
return this;
}

if (typeof options == 'function')
options = { success: options };

options = $.extend({
url:  this.attr('action') || window.location.toString(),
type: this.attr('method') || 'GET'
}, options || {});

// hook for manipulating the form data before it is extracted;
// convenient for use with rich editors like tinyMCE or FCKEditor
var veto = {};
this.trigger('form-pre-serialize', [this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
return this;
}

// provide opportunity to alter form data before it is serialized
if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSerialize callback');
return this;
}    

var a = this.formToArray(options.semantic);
if (options.data) {
options.extraData = options.data;
for (var n in options.data) {
if(options.data[n] instanceof Array) {
for (var k in options.data[n])
a.push( { name: n, value: options.data[n][k] } )
}  
else
a.push( { name: n, value: options.data[n] } );
}
}

// give pre-submit callback an opportunity to abort the submit
if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
log('ajaxSubmit: submit aborted via beforeSubmit callback');
return this;
}    

// fire vetoable 'validate' event
this.trigger('form-submit-validate', [a, this, options, veto]);
if (veto.veto) {
log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
return this;
}    

var q = $.param(a);

if (options.type.toUpperCase() == 'GET') {
options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
options.data = null;  // data is null for 'get'
}
else
options.data = q; // data is the query string for 'post'

var $form = this, callbacks = [];
if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
if (options.clearForm) callbacks.push(function() { $form.clearForm(); });

// perform a load on the target only if dataType is not provided
if (!options.dataType && options.target) {
var oldSuccess = options.success || function(){};
callbacks.push(function(data) {
$(options.target).html(data).each(oldSuccess, arguments);
});
}
else if (options.success)
callbacks.push(options.success);

options.success = function(data, status) {
for (var i=0, max=callbacks.length; i < max; i++)
callbacks[i].apply(options, [data, status, $form]);
};

// are there files to upload?
var files = $('input:file', this).fieldValue();
var found = false;
for (var j=0; j < files.length; j++)
if (files[j])
found = true;

// options.iframe allows user to force iframe mode
if (options.iframe || found) { 
// hack to fix Safari hang (thanks to Tim Molendijk for this)
// see:  http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
if ($.browser.safari && options.closeKeepAlive)
$.get(options.closeKeepAlive, fileUpload);
else
fileUpload();
}
else
$.ajax(options);

// fire 'notify' event
this.trigger('form-submit-notify', [this, options]);
return this;


// private function for handling file uploads (hat tip to YAHOO!)
function fileUpload() {
var form = $form[0];

if ($(':input[@name=submit]', form).length) {
alert('Error: Form elements must not be named "submit".');
return;
}

var opts = $.extend({}, $.ajaxSettings, options);
var s = jQuery.extend(true, {}, $.extend(true, {}, $.ajaxSettings), opts);

var id = 'jqFormIO' + (new Date().getTime());
var $io = $('<iframe id="' + id + '" name="' + id + '" />');
var io = $io[0];

if ($.browser.msie || $.browser.opera) 
io.src = 'javascript:false;document.write("");';
$io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });

var xhr = { // mock object
aborted: 0,
responseText: null,
responseXML: null,
status: 0,
statusText: 'n/a',
getAllResponseHeaders: function() {},
getResponseHeader: function() {},
setRequestHeader: function() {},
abort: function() { 
this.aborted = 1; 
$io.attr('src','about:blank'); // abort op in progress
}
};

var g = opts.global;
// trigger ajax global events so that activity/block indicators work like normal
if (g && ! $.active++) $.event.trigger("ajaxStart");
if (g) $.event.trigger("ajaxSend", [xhr, opts]);

if (s.beforeSend && s.beforeSend(xhr, s) === false) {
s.global && jQuery.active--;
return;
}
if (xhr.aborted)
return;

var cbInvoked = 0;
var timedOut = 0;

// add submitting element to data if we know it
var sub = form.clk;
if (sub) {
var n = sub.name;
if (n && !sub.disabled) {
options.extraData = options.extraData || {};
options.extraData[n] = sub.value;
if (sub.type == "image") {
options.extraData[name+'.x'] = form.clk_x;
options.extraData[name+'.y'] = form.clk_y;
}
}
}

// take a breath so that pending repaints get some cpu time before the upload starts
setTimeout(function() {
// make sure form attrs are set
var t = $form.attr('target'), a = $form.attr('action');
$form.attr({
target:   id,
method:   'POST',
action:   opts.url
});

// ie borks in some cases when setting encoding
if (! options.skipEncodingOverride) {
$form.attr({
encoding: 'multipart/form-data',
enctype:  'multipart/form-data'
});
}

// support timout
if (opts.timeout)
setTimeout(function() { timedOut = true; cb(); }, opts.timeout);

// add "extra" data to form if provided in options
var extraInputs = [];
try {
if (options.extraData)
for (var n in options.extraData)
extraInputs.push(
$('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />')
.appendTo(form)[0]);

// add iframe to doc and submit the form
$io.appendTo('body');
io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
form.submit();
}
finally {
// reset attrs and remove "extra" input elements
$form.attr('action', a);
t ? $form.attr('target', t) : $form.removeAttr('target');
$(extraInputs).remove();
}
}, 10);

function cb() {
if (cbInvoked++) return;

io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);

var operaHack = 0;
var ok = true;
try {
if (timedOut) throw 'timeout';
// extract the server response from the iframe
var data, doc;

doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;

if (doc.body == null && !operaHack && $.browser.opera) {
// In Opera 9.2.x the iframe DOM is not always traversable when
// the onload callback fires so we give Opera 100ms to right itself
operaHack = 1;
cbInvoked--;
setTimeout(cb, 100);
return;
}

xhr.responseText = doc.body ? doc.body.innerHTML : null;
xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
xhr.getResponseHeader = function(header){
var headers = {'content-type': opts.dataType};
return headers[header];
};

if (opts.dataType == 'json' || opts.dataType == 'script') {
var ta = doc.getElementsByTagName('textarea')[0];
xhr.responseText = ta ? ta.value : xhr.responseText;
}
else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
xhr.responseXML = toXml(xhr.responseText);
}
data = $.httpData(xhr, opts.dataType);
}
catch(e){
ok = false;
$.handleError(opts, xhr, 'error', e);
}

// ordering of these callbacks/triggers is odd, but that's how $.ajax does it
if (ok) {
opts.success(data, 'success');
if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
}
if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
if (g && ! --$.active) $.event.trigger("ajaxStop");
if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');

// clean up
setTimeout(function() {
$io.remove();
xhr.responseXML = null;
}, 100);
};

function toXml(s, doc) {
if (window.ActiveXObject) {
doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
doc.loadXML(s);
}
else
doc = (new DOMParser()).parseFromString(s, 'text/xml');
return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
};
};
};

/**
* ajaxForm() provides a mechanism for fully automating form submission.
*
* The advantages of using this method instead of ajaxSubmit() are:
*
* 1: This method will include coordinates for <input type="image" /> elements (if the element
*    is used to submit the form).
* 2. This method will include the submit element's name/value data (for the element that was
*    used to submit the form).
* 3. This method binds the submit() method to the form for you.
*
* The options argument for ajaxForm works exactly as it does for ajaxSubmit.  ajaxForm merely
* passes the options argument along after properly binding events for submit elements and
* the form itself.
*/ 
$.fn.ajaxForm = function(options) {
return this.ajaxFormUnbind().bind('submit.form-plugin',function() {
$(this).ajaxSubmit(options);
return false;
}).each(function() {
// store options in hash
$(":submit,input:image", this).bind('click.form-plugin',function(e) {
var form = this.form;
form.clk = this;
if (this.type == 'image') {
if (e.offsetX != undefined) {
form.clk_x = e.offsetX;
form.clk_y = e.offsetY;
} else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
var offset = $(this).offset();
form.clk_x = e.pageX - offset.left;
form.clk_y = e.pageY - offset.top;
} else {
form.clk_x = e.pageX - this.offsetLeft;
form.clk_y = e.pageY - this.offsetTop;
}
}
// clear form vars
setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 10);
});
});
};

// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
this.unbind('submit.form-plugin');
return this.each(function() {
$(":submit,input:image", this).unbind('click.form-plugin');
});

};

/**
* formToArray() gathers form element data into an array of objects that can
* be passed to any of the following ajax functions: $.get, $.post, or load.
* Each object in the array has both a 'name' and 'value' property.  An example of
* an array for a simple login form might be:
*
* [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
*
* It is this array that is passed to pre-submit callback functions provided to the
* ajaxSubmit() and ajaxForm() methods.
*/
$.fn.formToArray = function(semantic) {
var a = [];
if (this.length == 0) return a;

var form = this[0];
var els = semantic ? form.getElementsByTagName('*') : form.elements;
if (!els) return a;
for(var i=0, max=els.length; i < max; i++) {
var el = els[i];
var n = el.name;
if (!n) continue;

if (semantic && form.clk && el.type == "image") {
// handle image inputs on the fly when semantic == true
if(!el.disabled && form.clk == el)
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
continue;
}

var v = $.fieldValue(el, true);
if (v && v.constructor == Array) {
for(var j=0, jmax=v.length; j < jmax; j++)
a.push({name: n, value: v[j]});
}
else if (v !== null && typeof v != 'undefined')
a.push({name: n, value: v});
}

if (!semantic && form.clk) {
// input type=='image' are not found in elements array! handle them here
var inputs = form.getElementsByTagName("input");
for(var i=0, max=inputs.length; i < max; i++) {
var input = inputs[i];
var n = input.name;
if(n && !input.disabled && input.type == "image" && form.clk == input)
a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
}
}
return a;
};

/**
* Serializes form data into a 'submittable' string. This method will return a string
* in the format: name1=value1&amp;name2=value2
*/
$.fn.formSerialize = function(semantic) {
//hand off to jQuery.param for proper encoding
return $.param(this.formToArray(semantic));
};

/**
* Serializes all field elements in the jQuery object into a query string.
* This method will return a string in the format: name1=value1&amp;name2=value2
*/
$.fn.fieldSerialize = function(successful) {
var a = [];
this.each(function() {
var n = this.name;
if (!n) return;
var v = $.fieldValue(this, successful);
if (v && v.constructor == Array) {
for (var i=0,max=v.length; i < max; i++)
a.push({name: n, value: v[i]});
}
else if (v !== null && typeof v != 'undefined')
a.push({name: this.name, value: v});
});
//hand off to jQuery.param for proper encoding
return $.param(a);
};

/**
* Returns the value(s) of the element in the matched set.  For example, consider the following form:
*
*  <form><fieldset>
*      <input name="A" type="text" />
*      <input name="A" type="text" />
*      <input name="B" type="checkbox" value="B1" />
*      <input name="B" type="checkbox" value="B2"/>
*      <input name="C" type="radio" value="C1" />
*      <input name="C" type="radio" value="C2" />
*  </fieldset></form>
*
*  var v = $(':text').fieldValue();
*  // if no values are entered into the text inputs
*  v == ['','']
*  // if values entered into the text inputs are 'foo' and 'bar'
*  v == ['foo','bar']
*
*  var v = $(':checkbox').fieldValue();
*  // if neither checkbox is checked
*  v === undefined
*  // if both checkboxes are checked
*  v == ['B1', 'B2']
*
*  var v = $(':radio').fieldValue();
*  // if neither radio is checked
*  v === undefined
*  // if first radio is checked
*  v == ['C1']
*
* The successful argument controls whether or not the field element must be 'successful'
* (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
* The default value of the successful argument is true.  If this value is false the value(s)
* for each element is returned.
*
* Note: This method *always* returns an array.  If no valid value can be determined the
*       array will be empty, otherwise it will contain one or more values.
*/
$.fn.fieldValue = function(successful) {
for (var val=[], i=0, max=this.length; i < max; i++) {
var el = this[i];
var v = $.fieldValue(el, successful);
if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
continue;
v.constructor == Array ? $.merge(val, v) : val.push(v);
}
return val;
};

/**
* Returns the value of the field element.
*/
$.fieldValue = function(el, successful) {
var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
if (typeof successful == 'undefined') successful = true;

if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
(t == 'checkbox' || t == 'radio') && !el.checked ||
(t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
tag == 'select' && el.selectedIndex == -1))
return null;

if (tag == 'select') {
var index = el.selectedIndex;
if (index < 0) return null;
var a = [], ops = el.options;
var one = (t == 'select-one');
var max = (one ? index+1 : ops.length);
for(var i=(one ? index : 0); i < max; i++) {
var op = ops[i];
if (op.selected) {
// extra pain for IE...
var v = $.browser.msie && !(op.attributes['value'].specified) ? op.text : op.value;
if (one) return v;
a.push(v);
}
}
return a;
}
return el.value;
};

/**
* Clears the form data.  Takes the following actions on the form's input fields:
*  - input text fields will have their 'value' property set to the empty string
*  - select elements will have their 'selectedIndex' property set to -1
*  - checkbox and radio inputs will have their 'checked' property set to false
*  - inputs of type submit, button, reset, and hidden will *not* be effected
*  - button elements will *not* be effected
*/
$.fn.clearForm = function() {
return this.each(function() {
$('input,select,textarea', this).clearFields();
});
};

/**
* Clears the selected form elements.
*/
$.fn.clearFields = $.fn.clearInputs = function() {
return this.each(function() {
var t = this.type, tag = this.tagName.toLowerCase();
if (t == 'text' || t == 'password' || tag == 'textarea')
this.value = '';
else if (t == 'checkbox' || t == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = -1;
});
};

/**
* Resets the form data.  Causes all form elements to be reset to their original value.
*/
$.fn.resetForm = function() {
return this.each(function() {
// guard against an input with the name of 'reset'
// note that IE reports the reset function as an 'object'
if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
this.reset();
});
};

/**
* Enables or disables any matching elements.
*/
$.fn.enable = function(b) { 
if (b == undefined) b = true;
return this.each(function() { 
this.disabled = !b 
});
};

/**
* Checks/unchecks any matching checkboxes or radio buttons and
* selects/deselects and matching option elements.
*/
$.fn.selected = function(select) {
if (select == undefined) select = true;
return this.each(function() { 
var t = this.type;
if (t == 'checkbox' || t == 'radio')
this.checked = select;
else if (this.tagName.toLowerCase() == 'option') {
var $sel = $(this).parent('select');
if (select && $sel[0] && $sel[0].type == 'select-one') {
// deselect all other options
$sel.find('option').selected(false);
}
this.selected = select;
}
});
};

// helper fn for console logging
// set $.fn.ajaxSubmit.debug to true to enable debug logging
function log() {
if ($.fn.ajaxSubmit.debug && window.console && window.console.log)
window.console.log('[jquery.form] ' + Array.prototype.join.call(arguments,''));
};

})(jQuery);


/* idTabs ~ Sean Catchpole - Version 2.2 - MIT/GPL */
(function(){
var dep = {"jQuery":"http://code.jquery.com/jquery-latest.min.js"};
var init = function(){ 

/* Options (in any order):

start (number|string)
Index number of default tab. ex: $(...).idTabs(0)
String of id of default tab. ex: $(...).idTabs("tab1")
default: class "selected" or index 0
Passing null will force it to not select a default tab

change (boolean)
True - Url will change. ex: $(...).idTabs(true)
False - Url will not change. ex: $(...).idTabs(false)
default: false

click (function)
Function will be called when a tab is clicked. ex: $(...).idTabs(foo)
If the function returns true, idTabs will show/hide content (as usual).
If the function returns false, idTabs will not take any action.
The function is passed four variables:
The id of the element to be shown
an array of all id's that can be shown
the element containing the tabs
and the current settings

selected (string)
Class to use for selected. ex: $(...).idTabs(".current")
default: ".selected"

event (string)
Event to trigger idTabs on. ex: $(...).idTabs("!mouseover")
default: "!click"
To bind multiple event, call idTabs multiple times
ex: $(...).idTabs("!click").idTabs("!focus")

*/
(function($){

$.fn.idTabs = function(){
//Loop Arguments matching options
var s = {};
for(var i=0; i<arguments.length; ++i) {
var a=arguments[i];
switch(a.constructor){
case Object: $.extend(s,a); break;
case Boolean: s.change = a; break;
case Number: s.start = a; break;
case Function: s.click = a; break;
case String:
if(a.charAt(0)=='.') s.selected = a;
else if(a.charAt(0)=='!') s.event = a;
else s.start = a;
break;
}
}

if(typeof s['return'] == "function") //backwards compatible
s.change = s['return'];

return this.each(function(){ $.idTabs(this,s); }); //Chainable
}

$.idTabs = function(tabs,options) {
//Settings
var meta = ($.metadata)?$(tabs).metadata():{};
var s = $.extend({},$.idTabs.settings,meta,options);

//Play nice
if(s.selected.charAt(0)=='.') s.selected=s.selected.substr(1);
if(s.event.charAt(0)=='!') s.event=s.event.substr(1);
if(s.start==null) s.start=-1; //no tab selected

//Setup Tabs
var showId = function(){
if($(this).is('.'+s.selected))
return s.change; //return if already selected
var id = "#"+this.href.split('#')[1];
var aList = []; //save tabs
var idList = []; //save possible elements
$("a",tabs).each(function(){
if(this.href.match(/#/)) {
aList.push(this);
idList.push("#"+this.href.split('#')[1]);
}
});
if(s.click && !s.click.apply(this,[id,idList,tabs,s])) return s.change;
//Clear tabs, and hide all
for(i in aList) $(aList[i]).removeClass(s.selected);
for(i in idList) $(idList[i]).hide();
//Select clicked tab and show content
$(this).addClass(s.selected);
$(id).show();
return s.change; //Option for changing url
}

//Bind idTabs
var list = $("a[href*='#']",tabs).unbind(s.event,showId).bind(s.event,showId);
list.each(function(){ $("#"+this.href.split('#')[1]).hide(); });

//Select default tab
var test=false;
if((test=list.filter('.'+s.selected)).length); //Select tab with selected class
else if(typeof s.start == "number" &&(test=list.eq(s.start)).length); //Select num tab
else if(typeof s.start == "string" //Select tab linking to id
&&(test=list.filter("[href*='#"+s.start+"']")).length);
if(test) { test.removeClass(s.selected); test.trigger(s.event); } //Select tab

return s; //return current settings (be creative)
}

//Defaults
$.idTabs.settings = {
start:0,
change:false,
click:null,
selected:".selected",
event:"!click"
};

//Version
$.idTabs.version = "2.2";

//Auto-run
$(function(){ $(".idTabs").idTabs(); });

})(jQuery);



} //init

// Check Dependencies
var check = function(o,s){
s = s.split('.');
while(o && s.length) o = o[s.shift()];
return o;
}

// Add Script
var head = document.getElementsByTagName("head")[0];
var add = function(url){
var s = document.createElement("script");
s.type = "text/javascript"; s.src = url;
head.appendChild(s);
}

// Save Self
var s = document.getElementsByTagName('script');
var src = s[s.length-1].src;

// Load Dependencies
var ok=true;
for(d in dep) {
if(check(this,d)) continue;
ok=false;
add(dep[d]);
} if(ok) return init();

// Reload Self
add(src);

})();



/**
* jCarousel - Riding carousels with jQuery
*   http://sorgalla.com/jcarousel/
*
* Copyright (c) 2006 Jan Sorgalla (http://sorgalla.com)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* Built on top of the jQuery library
*   http://jquery.com
*
* Inspired by the "Carousel Component" by Bill Scott
*   http://billwscott.com/carousel/
*/

(function($) {
/**
* Creates a carousel for all matched elements.
*
* @example $("#mycarousel").jcarousel();
* @before <ul id="mycarousel" class="jcarousel-skin-name"><li>First item</li><li>Second item</li></ul>
* @result
*
* <div class="jcarousel-skin-name">
*   <div class="jcarousel-container">
*     <div disabled="disabled" class="jcarousel-prev jcarousel-prev-disabled"></div>
*     <div class="jcarousel-next"></div>
*     <div class="jcarousel-clip">
*       <ul class="jcarousel-list">
*         <li class="jcarousel-item-1">First item</li>
*         <li class="jcarousel-item-2">Second item</li>
*       </ul>
*     </div>
*   </div>
* </div>
*
* @name jcarousel
* @type jQuery
* @param Hash o A set of key/value pairs to set as configuration properties.
* @cat Plugins/jCarousel
*/
$.fn.jcarousel = function(o) {
return this.each(function() {
new $jc(this, o);
});
};

// Default configuration properties.
var defaults = {
vertical: false,
start: 1,
offset: 1,
size: null,
scroll: 3,
visible: null,
animation: 'normal',
easing: 'swing',
auto: 0,
wrap: null,
initCallback: null,
reloadCallback: null,
itemLoadCallback: null,
itemFirstInCallback: null,
itemFirstOutCallback: null,
itemLastInCallback: null,
itemLastOutCallback: null,
itemVisibleInCallback: null,
itemVisibleOutCallback: null,
buttonNextHTML: '<div></div>',
buttonPrevHTML: '<div></div>',
buttonNextEvent: 'click',
buttonPrevEvent: 'click',
buttonNextCallback: null,
buttonPrevCallback: null,
// marci hack *********************************************************************
fallbackWidth: 0  
// marci hack *********************************************************************
};

/**
* The jCarousel object.
*
* @constructor
* @name $.jcarousel
* @param Object e The element to create the carousel for.
* @param Hash o A set of key/value pairs to set as configuration properties.
* @cat Plugins/jCarousel
*/
$.jcarousel = function(e, o) {
this.options    = $.extend({}, defaults, o || {});

this.locked     = false;

this.container  = null;
this.clip       = null;
this.list       = null;
this.buttonNext = null;
this.buttonPrev = null;

this.wh = !this.options.vertical ? 'width' : 'height';
this.lt = !this.options.vertical ? 'left' : 'top';

// Extract skin class
var skin = '', split = e.className.split(' ');

for (var i = 0; i < split.length; i++) {
if (split[i].indexOf('jcarousel-skin') != -1) {
$(e).removeClass(split[i]);
var skin = split[i];
break;
}
}

if (e.nodeName == 'UL' || e.nodeName == 'OL') {
this.list = $(e);
this.container = this.list.parent();

if (this.container.hasClass('jcarousel-clip')) {
if (!this.container.parent().hasClass('jcarousel-container'))
this.container = this.container.wrap('<div></div>');

this.container = this.container.parent();
} else if (!this.container.hasClass('jcarousel-container'))
this.container = this.list.wrap('<div></div>').parent();
} else {
this.container = $(e);
this.list = $(e).find('>ul,>ol,div>ul,div>ol');
}

if (skin != '' && this.container.parent()[0].className.indexOf('jcarousel-skin') == -1)
this.container.wrap('<div class=" '+ skin + '"></div>');

this.clip = this.list.parent();

if (!this.clip.length || !this.clip.hasClass('jcarousel-clip'))
this.clip = this.list.wrap('<div></div>').parent();

this.buttonPrev = $('.jcarousel-prev', this.container);

if (this.buttonPrev.size() == 0 && this.options.buttonPrevHTML != null)
this.buttonPrev = this.clip.before(this.options.buttonPrevHTML).prev();

this.buttonPrev.addClass(this.className('jcarousel-prev'));

this.buttonNext = $('.jcarousel-next', this.container);

if (this.buttonNext.size() == 0 && this.options.buttonNextHTML != null)
this.buttonNext = this.clip.before(this.options.buttonNextHTML).prev();

this.buttonNext.addClass(this.className('jcarousel-next'));

this.clip.addClass(this.className('jcarousel-clip'));
this.list.addClass(this.className('jcarousel-list'));
this.container.addClass(this.className('jcarousel-container'));

var di = this.options.visible != null ? Math.ceil(this.clipping() / this.options.visible) : null;
var li = this.list.children('li');

var self = this;

if (li.size() > 0) {
var wh = 0, i = this.options.offset;
li.each(function() {
self.format(this, i++);
wh += self.dimension(this, di);
});

this.list.css(this.wh, wh + 'px');

// Only set if not explicitly passed as option
if (!o || o.size === undefined)
this.options.size = li.size();
}

// For whatever reason, .show() does not work in Safari...
this.container.css('display', 'block');
this.buttonNext.css('display', 'block');
this.buttonPrev.css('display', 'block');

this.funcNext   = function() { self.next(); };
this.funcPrev   = function() { self.prev(); };
this.funcResize = function() { self.reload(); };

if (this.options.initCallback != null)
this.options.initCallback(this, 'init');

if ($.browser.safari) {
this.buttons(false, false);
$(window).bind('load', function() { self.setup(); });
} else
this.setup();
};

// Create shortcut for internal use
var $jc = $.jcarousel;

$jc.fn = $jc.prototype = {
jcarousel: '0.2.3'
};

$jc.fn.extend = $jc.extend = $.extend;

$jc.fn.extend({
/**
* Setups the carousel.
*
* @name setup
* @type undefined
* @cat Plugins/jCarousel
*/
setup: function() {
this.first     = null;
this.last      = null;
this.prevFirst = null;
this.prevLast  = null;
this.animating = false;
this.timer     = null;
this.tail      = null;
this.inTail    = false;

if (this.locked)
return;

this.list.css(this.lt, this.pos(this.options.offset) + 'px');
var p = this.pos(this.options.start);
this.prevFirst = this.prevLast = null;
this.animate(p, false);

$(window).unbind('resize', this.funcResize).bind('resize', this.funcResize);
},

/**
* Clears the list and resets the carousel.
*
* @name reset
* @type undefined
* @cat Plugins/jCarousel
*/
reset: function() {
this.list.empty();

this.list.css(this.lt, '0px');
this.list.css(this.wh, '10px');

if (this.options.initCallback != null)
this.options.initCallback(this, 'reset');

this.setup();
},

/**
* Reloads the carousel and adjusts positions.
*
* @name reload
* @type undefined
* @cat Plugins/jCarousel
*/
reload: function() {
if (this.tail != null && this.inTail)
this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) + this.tail);

this.tail   = null;
this.inTail = false;

if (this.options.reloadCallback != null)
this.options.reloadCallback(this);

if (this.options.visible != null) {
var self = this;
var di = Math.ceil(this.clipping() / this.options.visible), wh = 0, lt = 0;
$('li', this.list).each(function(i) {
wh += self.dimension(this, di);
if (i + 1 < self.first)
lt = wh;
});

this.list.css(this.wh, wh + 'px');
this.list.css(this.lt, -lt + 'px');
}

this.scroll(this.first, false);
},

/**
* Locks the carousel.
*
* @name lock
* @type undefined
* @cat Plugins/jCarousel
*/
lock: function() {
this.locked = true;
this.buttons();
},

/**
* Unlocks the carousel.
*
* @name unlock
* @type undefined
* @cat Plugins/jCarousel
*/
unlock: function() {
this.locked = false;
this.buttons();
},

/**
* Sets the size of the carousel.
*
* @name size
* @type undefined
* @param Number s The size of the carousel.
* @cat Plugins/jCarousel
*/
size: function(s) {
if (s != undefined) {
this.options.size = s;
if (!this.locked)
this.buttons();
}

return this.options.size;
},

/**
* Checks whether a list element exists for the given index (or index range).
*
* @name get
* @type bool
* @param Number i The index of the (first) element.
* @param Number i2 The index of the last element.
* @cat Plugins/jCarousel
*/
has: function(i, i2) {
if (i2 == undefined || !i2)
i2 = i;

if (this.options.size !== null && i2 > this.options.size)
i2 = this.options.size;

for (var j = i; j <= i2; j++) {
var e = this.get(j);
if (!e.length || e.hasClass('jcarousel-item-placeholder'))
return false;
}

return true;
},

/**
* Returns a jQuery object with list element for the given index.
*
* @name get
* @type jQuery
* @param Number i The index of the element.
* @cat Plugins/jCarousel
*/
get: function(i) {
return $('.jcarousel-item-' + i, this.list);
},

/**
* Adds an element for the given index to the list.
* If the element already exists, it updates the inner html.
* Returns the created element as jQuery object.
*
* @name add
* @type jQuery
* @param Number i The index of the element.
* @param String s The innerHTML of the element.
* @cat Plugins/jCarousel
*/
add: function(i, s) {
var e = this.get(i), old = 0, add = 0;

if (e.length == 0) {
var c, e = this.create(i), j = $jc.intval(i);
while (c = this.get(--j)) {
if (j <= 0 || c.length) {
j <= 0 ? this.list.prepend(e) : c.after(e);
break;
}
}
} else
old = this.dimension(e);

e.removeClass(this.className('jcarousel-item-placeholder'));
typeof s == 'string' ? e.html(s) : e.empty().append(s);

var di = this.options.visible != null ? Math.ceil(this.clipping() / this.options.visible) : null;
var wh = this.dimension(e, di) - old;

if (i > 0 && i < this.first)
this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) - wh + 'px');

this.list.css(this.wh, $jc.intval(this.list.css(this.wh)) + wh + 'px');

return e;
},

/**
* Removes an element for the given index from the list.
*
* @name remove
* @type undefined
* @param Number i The index of the element.
* @cat Plugins/jCarousel
*/
remove: function(i) {
var e = this.get(i);

// Check if item exists and is not currently visible
if (!e.length || (i >= this.first && i <= this.last))
return;

var d = this.dimension(e);

if (i < this.first)
this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) + d + 'px');

e.remove();

this.list.css(this.wh, $jc.intval(this.list.css(this.wh)) - d + 'px');
},

/**
* Moves the carousel forwards.
*
* @name next
* @type undefined
* @cat Plugins/jCarousel
*/
next: function() {
this.stopAuto();

if (this.tail != null && !this.inTail)
this.scrollTail(false);
else
this.scroll(((this.options.wrap == 'both' || this.options.wrap == 'last') && this.options.size != null && this.last == this.options.size) ? 1 : this.first + this.options.scroll);
},

/**
* Moves the carousel backwards.
*
* @name prev
* @type undefined
* @cat Plugins/jCarousel
*/
prev: function() {
this.stopAuto();

if (this.tail != null && this.inTail)
this.scrollTail(true);
else
this.scroll(((this.options.wrap == 'both' || this.options.wrap == 'first') && this.options.size != null && this.first == 1) ? this.options.size : this.first - this.options.scroll);
},

/**
* Scrolls the tail of the carousel.
*
* @name scrollTail
* @type undefined
* @param Bool b Whether scroll the tail back or forward.
* @cat Plugins/jCarousel
*/
scrollTail: function(b) {
if (this.locked || this.animating || !this.tail)
return;

var pos  = $jc.intval(this.list.css(this.lt));

!b ? pos -= this.tail : pos += this.tail;
this.inTail = !b;

// Save for callbacks
this.prevFirst = this.first;
this.prevLast  = this.last;

this.animate(pos);
},

/**
* Scrolls the carousel to a certain position.
*
* @name scroll
* @type undefined
* @param Number i The index of the element to scoll to.
* @param Bool a Flag indicating whether to perform animation.
* @cat Plugins/jCarousel
*/
scroll: function(i, a) {
if (this.locked || this.animating)
return;

this.animate(this.pos(i), a);
},

/**
* Prepares the carousel and return the position for a certian index.
*
* @name pos
* @type Number
* @param Number i The index of the element to scoll to.
* @cat Plugins/jCarousel
*/
pos: function(i) {
if (this.locked || this.animating)
return;

if (this.options.wrap != 'circular')
i = i < 1 ? 1 : (this.options.size && i > this.options.size ? this.options.size : i);

var back = this.first > i;
var pos  = $jc.intval(this.list.css(this.lt));

// Create placeholders, new list width/height
// and new list position
var f = this.options.wrap != 'circular' && this.first <= 1 ? 1 : this.first;
var c = back ? this.get(f) : this.get(this.last);
var j = back ? f : f - 1;
var e = null, l = 0, p = false, d = 0;

while (back ? --j >= i : ++j < i) {
e = this.get(j);
p = !e.length;
if (e.length == 0) {
e = this.create(j).addClass(this.className('jcarousel-item-placeholder'));
c[back ? 'before' : 'after' ](e);
}

c = e;
d = this.dimension(e);

if (p)
l += d;

if (this.first != null && (this.options.wrap == 'circular' || (j >= 1 && (this.options.size == null || j <= this.options.size))))
pos = back ? pos + d : pos - d;
}

// Calculate visible items
var clipping = this.clipping();
var cache = [];
var visible = 0, j = i, v = 0;
var c = this.get(i - 1);

while (++visible) {
e = this.get(j);
p = !e.length;
if (e.length == 0) {
e = this.create(j).addClass(this.className('jcarousel-item-placeholder'));
// This should only happen on a next scroll
c.length == 0 ? this.list.prepend(e) : c[back ? 'before' : 'after' ](e);
}

c = e;
var d = this.dimension(e);

// marci hack *********************************************************************
if (d == 0 && this.options.fallbackWidth > 0)
d = this.options.fallbackWidth;
// marci hack *********************************************************************

if (d == 0) {
alert('jCarousel: No width/height set for items. This will cause an infinite loop. Aborting');
return 0;
}

if (this.options.wrap != 'circular' && this.options.size !== null && j > this.options.size)
cache.push(e);
else if (p)
l += d;

v += d;

if (v >= clipping)
break;

j++;
}

// Remove out-of-range placeholders
for (var x = 0; x < cache.length; x++)
cache[x].remove();

// Resize list
if (l > 0) {
this.list.css(this.wh, this.dimension(this.list) + l + 'px');

if (back) {
pos -= l;
this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) - l + 'px');
}
}

// Calculate first and last item
var last = i + visible - 1;
if (this.options.wrap != 'circular' && this.options.size && last > this.options.size)
last = this.options.size;

if (j > last) {
visible = 0, j = last, v = 0;
while (++visible) {
var e = this.get(j--);
if (!e.length)
break;
v += this.dimension(e);
if (v >= clipping)
break;
}
}

var first = last - visible + 1;
if (this.options.wrap != 'circular' && first < 1)
first = 1;

if (this.inTail && back) {
pos += this.tail;
this.inTail = false;
}

this.tail = null;
if (this.options.wrap != 'circular' && last == this.options.size && (last - visible + 1) >= 1) {
var m = $jc.margin(this.get(last), !this.options.vertical ? 'marginRight' : 'marginBottom');
if ((v - m) > clipping)
this.tail = v - clipping - m;
}

// Adjust position
while (i-- > first)
pos += this.dimension(this.get(i));

// Save visible item range
this.prevFirst = this.first;
this.prevLast  = this.last;
this.first     = first;
this.last      = last;

return pos;
},

/**
* Animates the carousel to a certain position.
*
* @name animate
* @type undefined
* @param mixed p Position to scroll to.
* @param Bool a Flag indicating whether to perform animation.
* @cat Plugins/jCarousel
*/
animate: function(p, a) {
if (this.locked || this.animating)
return;

this.animating = true;

var self = this;
var scrolled = function() {
self.animating = false;

if (p == 0)
self.list.css(self.lt,  0);

if (self.options.wrap == 'both' || self.options.wrap == 'last' || self.options.size == null || self.last < self.options.size)
self.startAuto();

self.buttons();
self.notify('onAfterAnimation');
};

this.notify('onBeforeAnimation');

// Animate
if (!this.options.animation || a == false) {
this.list.css(this.lt, p + 'px');
scrolled();
} else {
var o = !this.options.vertical ? {'left': p} : {'top': p};
this.list.animate(o, this.options.animation, this.options.easing, scrolled);
}
},

/**
* Starts autoscrolling.
*
* @name auto
* @type undefined
* @param Number s Seconds to periodically autoscroll the content.
* @cat Plugins/jCarousel
*/
startAuto: function(s) {
if (s != undefined)
this.options.auto = s;

if (this.options.auto == 0)
return this.stopAuto();

if (this.timer != null)
return;

var self = this;
this.timer = setTimeout(function() { self.next(); }, this.options.auto * 1000);
},

/**
* Stops autoscrolling.
*
* @name stopAuto
* @type undefined
* @cat Plugins/jCarousel
*/
stopAuto: function() {
if (this.timer == null)
return;

clearTimeout(this.timer);
this.timer = null;
},

/**
* Sets the states of the prev/next buttons.
*
* @name buttons
* @type undefined
* @cat Plugins/jCarousel
*/
buttons: function(n, p) {
if (n == undefined || n == null) {
var n = !this.locked && this.options.size !== 0 && ((this.options.wrap && this.options.wrap != 'first') || this.options.size == null || this.last < this.options.size);
if (!this.locked && (!this.options.wrap || this.options.wrap == 'first') && this.options.size != null && this.last >= this.options.size)
n = this.tail != null && !this.inTail;
}

if (p == undefined || p == null) {
var p = !this.locked && this.options.size !== 0 && ((this.options.wrap && this.options.wrap != 'last') || this.first > 1);
if (!this.locked && (!this.options.wrap || this.options.wrap == 'last') && this.options.size != null && this.first == 1)
p = this.tail != null && this.inTail;
}

var self = this;

this.buttonNext[n ? 'bind' : 'unbind'](this.options.buttonNextEvent, this.funcNext)[n ? 'removeClass' : 'addClass'](this.className('jcarousel-next-disabled')).attr('disabled', n ? false : true);
this.buttonPrev[p ? 'bind' : 'unbind'](this.options.buttonPrevEvent, this.funcPrev)[p ? 'removeClass' : 'addClass'](this.className('jcarousel-prev-disabled')).attr('disabled', p ? false : true);

if (this.buttonNext.length > 0 && (this.buttonNext[0].jcarouselstate == undefined || this.buttonNext[0].jcarouselstate != n) && this.options.buttonNextCallback != null) {
this.buttonNext.each(function() { self.options.buttonNextCallback(self, this, n); });
this.buttonNext[0].jcarouselstate = n;
}

if (this.buttonPrev.length > 0 && (this.buttonPrev[0].jcarouselstate == undefined || this.buttonPrev[0].jcarouselstate != p) && this.options.buttonPrevCallback != null) {
this.buttonPrev.each(function() { self.options.buttonPrevCallback(self, this, p); });
this.buttonPrev[0].jcarouselstate = p;
}
},

notify: function(evt) {
var state = this.prevFirst == null ? 'init' : (this.prevFirst < this.first ? 'next' : 'prev');

// Load items
this.callback('itemLoadCallback', evt, state);

if (this.prevFirst !== this.first) {
this.callback('itemFirstInCallback', evt, state, this.first);
this.callback('itemFirstOutCallback', evt, state, this.prevFirst);
}

if (this.prevLast !== this.last) {
this.callback('itemLastInCallback', evt, state, this.last);
this.callback('itemLastOutCallback', evt, state, this.prevLast);
}

this.callback('itemVisibleInCallback', evt, state, this.first, this.last, this.prevFirst, this.prevLast);
this.callback('itemVisibleOutCallback', evt, state, this.prevFirst, this.prevLast, this.first, this.last);
},

callback: function(cb, evt, state, i1, i2, i3, i4) {
if (this.options[cb] == undefined || (typeof this.options[cb] != 'object' && evt != 'onAfterAnimation'))
return;

var callback = typeof this.options[cb] == 'object' ? this.options[cb][evt] : this.options[cb];

if (!$.isFunction(callback))
return;

var self = this;

if (i1 === undefined)
callback(self, state, evt);
else if (i2 === undefined)
this.get(i1).each(function() { callback(self, this, i1, state, evt); });
else {
for (var i = i1; i <= i2; i++)
if (i !== null && !(i >= i3 && i <= i4))
this.get(i).each(function() { callback(self, this, i, state, evt); });
}
},

create: function(i) {
return this.format('<li></li>', i);
},

format: function(e, i) {
var $e = $(e).addClass(this.className('jcarousel-item')).addClass(this.className('jcarousel-item-' + i));
$e.attr('jcarouselindex', i);
return $e;
},

className: function(c) {
return c + ' ' + c + (!this.options.vertical ? '-horizontal' : '-vertical');
},

dimension: function(e, d) {
var el = e.jquery != undefined ? e[0] : e;

var old = !this.options.vertical ?
el.offsetWidth + $jc.margin(el, 'marginLeft') + $jc.margin(el, 'marginRight') :
el.offsetHeight + $jc.margin(el, 'marginTop') + $jc.margin(el, 'marginBottom');

if (d == undefined || old == d)
return old;

var w = !this.options.vertical ?
d - $jc.margin(el, 'marginLeft') - $jc.margin(el, 'marginRight') :
d - $jc.margin(el, 'marginTop') - $jc.margin(el, 'marginBottom');

$(el).css(this.wh, w + 'px');

return this.dimension(el);
},

clipping: function() {
return !this.options.vertical ?
this.clip[0].offsetWidth - $jc.intval(this.clip.css('borderLeftWidth')) - $jc.intval(this.clip.css('borderRightWidth')) :
this.clip[0].offsetHeight - $jc.intval(this.clip.css('borderTopWidth')) - $jc.intval(this.clip.css('borderBottomWidth'));
},

index: function(i, s) {
if (s == undefined)
s = this.options.size;

return Math.round((((i-1) / s) - Math.floor((i-1) / s)) * s) + 1;
}
});

$jc.extend({
/**
* Gets/Sets the global default configuration properties.
*
* @name defaults
* @descr Gets/Sets the global default configuration properties.
* @type Hash
* @param Hash d A set of key/value pairs to set as configuration properties.
* @cat Plugins/jCarousel
*/
defaults: function(d) {
return $.extend(defaults, d || {});
},

margin: function(e, p) {
if (!e)
return 0;

var el = e.jquery != undefined ? e[0] : e;

if (p == 'marginRight' && $.browser.safari) {
var old = {'display': 'block', 'float': 'none', 'width': 'auto'}, oWidth, oWidth2;

$.swap(el, old, function() { oWidth = el.offsetWidth; });

old['marginRight'] = 0;
$.swap(el, old, function() { oWidth2 = el.offsetWidth; });

return oWidth2 - oWidth;
}

return $jc.intval($.css(el, p));
},

intval: function(v) {
v = parseInt(v);
return isNaN(v) ? 0 : v;
}
});

})(jQuery);

/*
### jQuery Star Rating Plugin v2.5 - 2008-09-10 ###
* http://www.fyneworks.com/ - diego@fyneworks.com
* Dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
###
Project: http://plugins.jquery.com/project/MultipleFriendlyStarRating
Website: http://www.fyneworks.com/jquery/star-rating/
*//*
Based on http://www.phpletter.com/Demo/Jquery-Star-Rating-Plugin/
Original comments:
This is hacked version of star rating created by <a href="http://php.scripts.psu.edu/rja171/widgets/rating.php">Ritesh Agrawal</a>
It thansform a set of radio type input elements to star rating type and remain the radio element name and value,
so could be integrated with your form. It acts as a normal radio button.
modified by : Logan Cai (cailongqun[at]yahoo.com.cn)
*/

/*# AVOID COLLISIONS #*/
;if(window.jQuery) (function($){
/*# AVOID COLLISIONS #*/

// default settings
$.rating = {
cancel: 'Cancel Rating',   // advisory title for the 'cancel' link
cancelValue: '',           // value to submit when user click the 'cancel' link
split: 0,                  // split the star into how many parts?

// Width of star image in case the plugin can't work it out. This can happen if
// the jQuery.dimensions plugin is not available OR the image is hidden at installation
starWidth: 16,

//NB.: These don't need to be defined (can be undefined/null) so let's save some code!
//half:     false,         // just a shortcut to settings.split = 2
//required: false,         // disables the 'cancel' button so user can only select one of the specified values
//readOnly: false,         // disable rating plugin interaction/ values cannot be changed
//focus:    function(){},  // executed when stars are focused
//blur:     function(){},  // executed when stars are focused
//callback: function(){},  // executed when a star is clicked

// required properties:
groups: {},// allows multiple star ratings on one page
event: {// plugin event handlers
fill: function(n, el, settings, state){ // fill to the current mouse position.
//if(window.console) console.log(['fill', $(el), $(el).prevAll('.star_group_'+n), arguments]);
this.drain(n);
$(el).prevAll('.star_group_'+n).andSelf().addClass('star_'+(state || 'hover'));
// focus handler, as requested by focusdigital.co.uk
var lnk = $(el).children('a'); val = lnk.text();
if(settings.focus) settings.focus.apply($.rating.groups[n].valueElem[0], [val, lnk[0]]);
},
drain: function(n, el, settings) { // drain all the stars.
//if(window.console) console.log(['drain', $(el), $(el).prevAll('.star_group_'+n), arguments]);
$.rating.groups[n].valueElem.siblings('.star_group_'+n).removeClass('star_on').removeClass('star_hover');
},
reset: function(n, el, settings){ // Reset the stars to the default index.
if(!$($.rating.groups[n].current).is('.cancel'))
$($.rating.groups[n].current).prevAll('.star_group_'+n).andSelf().addClass('star_on');
// blur handler, as requested by focusdigital.co.uk
var lnk = $(el).children('a'); val = lnk.text();
if(settings.blur) settings.blur.apply($.rating.groups[n].valueElem[0], [val, lnk[0]]);
},
click: function(n, el, settings){ // Selected a star or cancelled
$.rating.groups[n].current = el;
var lnk = $(el).children('a'); val = lnk.text();
// Set value
$.rating.groups[n].valueElem.val(val);
// Update display
$.rating.event.drain(n, el, settings);
$.rating.event.reset(n, el, settings);
// click callback, as requested here: http://plugins.jquery.com/node/1655
if(settings.callback) settings.callback.apply($.rating.groups[n].valueElem[0], [val, lnk[0]]);
}      
}// plugin events
};

$.fn.rating = function(instanceSettings){
if(this.length==0) return this; // quick fail

instanceSettings = $.extend(
{}/* new object */,
$.rating/* global settings */,
instanceSettings || {} /* just-in-time settings */
);

// loop through each matched element
this.each(function(i){

var settings = $.extend(
{}/* new object */,
instanceSettings || {} /* current call settings */,
($.metadata? $(this).metadata(): ($.meta?$(this).data():null)) || {} /* metadata settings */
);

////if(window.console) console.log([this.name, settings.half, settings.split], '#');

// Generate internal control ID
// - ignore square brackets in element names
var n = (this.name || 'unnamed-rating').replace(/\[|\]/, "_");

// Grouping
if(!$.rating.groups[n]) $.rating.groups[n] = {count: 0};
i = $.rating.groups[n].count; $.rating.groups[n].count++;

// Accept readOnly setting from 'disabled' property
$.rating.groups[n].readOnly = $.rating.groups[n].readOnly || settings.readOnly || $(this).attr('disabled');

// Things to do with the first element...
if(i == 0){
// Create value element (disabled if readOnly)
$.rating.groups[n].valueElem = $('<input type="hidden" name="' + n + '" value=""' + (settings.readOnly ? ' disabled="disabled"' : '') + '/>');
// Insert value element into form
$(this).before($.rating.groups[n].valueElem);

if($.rating.groups[n].readOnly || settings.required){
// DO NOT display 'cancel' button
}
else{
// Display 'cancel' button
$(this).before(
$('<div class="cancel"><a title="' + settings.cancel + '">' + settings.cancelValue + '</a></div>')
.mouseover(function(){ $.rating.event.drain(n, this, settings); $(this).addClass('star_on'); })
.mouseout(function(){ $.rating.event.reset(n, this, settings); $(this).removeClass('star_on'); })
.click(function(){ $.rating.event.click(n, this, settings); })
);
}
}; // if (i == 0) (first element)

// insert rating option right after preview element
eStar = $('<div class="star"><a title="' + (this.title || this.value) + '">' + this.value + '</a></div>');
$(this).after(eStar);

// Half-stars?
if(settings.half) settings.split = 2;

// Prepare division settings
if(typeof settings.split=='number' && settings.split>0){
var stw = ($.fn.width ? $(eStar).width() : 0) || settings.starWidth;
var spi = (i % settings.split), spw = Math.floor(stw/settings.split);
$(eStar)
// restrict star's width and hide overflow (already in CSS)
.width(spw)
// move the star left by using a negative margin
// this is work-around to IE's stupid box model (position:relative doesn't work)
.find('a').css({ 'margin-left':'-'+ (spi*spw) +'px' })
};

// Remember group name so controls within the same container don't get mixed up
$(eStar).addClass('star_group_'+n);

// readOnly?
if($.rating.groups[n].readOnly)//{ //save a byte!
// Mark star as readOnly so user can customize display
$(eStar).addClass('star_readonly');
//}  //save a byte!
else//{ //save a byte!
$(eStar)
// Enable hover css effects
.addClass('star_live')
// Attach mouse events
.mouseover(function(){ $.rating.event.drain(n, this, settings); $.rating.event.fill(n, this, settings, 'hover'); })
.mouseout(function(){ $.rating.event.drain(n, this, settings); $.rating.event.reset(n, this, settings); })
.click(function(){ $.rating.event.click(n, this, settings); });
//}; //save a byte!

////if(window.console) console.log(['###', n, this.checked, $.rating.groups[n].initial]);
if(this.checked) $.rating.groups[n].current = eStar;

//remove this checkbox
$(this).remove();

// reset display if last element
if(i + 1 == this.length) $.rating.event.reset(n, this, settings);

}); // each element

// initialize groups...
for(n in $.rating.groups)//{ not needed, save a byte!
(function(c, v, n){ if(!c) return;
$.rating.event.fill(n, c, instanceSettings || {}, 'on');
$(v).val($(c).children('a').text());
})
($.rating.groups[n].current, $.rating.groups[n].valueElem, n);
//}; not needed, save a byte!

return this; // don't break the chain...
};



/*
### Default implementation ###
The plugin will attach itself to file inputs
with the class 'multi' when the page loads
*/
$(function(){ $('input[@type=radio].star').rating(); });



/*# AVOID COLLISIONS #*/
})(jQuery);
/*# AVOID COLLISIONS #*/


/*
* Thickbox 3.1 - One Box To Rule Them All.
* By Cody Lindley (http://www.codylindley.com)
* Copyright (c) 2007 cody lindley
* Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/

var tb_pathToImage = "/art/css/thickbox-loading.gif";

/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/

//on page load call tb_init
$(document).ready(function(){   
tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
imgLoader = new Image();// preload image
imgLoader.src = tb_pathToImage;
});

//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
$(domChunk).click(function(){
var t = this.title || this.name || null;
var a = this.href || this.alt;
var g = this.rel || false;
tb_show(t,a,g);
this.blur();
return false;
});
}

function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link

try {
if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
$("body","html").css({height: "100%", width: "100%"});
$("html").css("overflow","hidden");
if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
$("#TB_overlay").click(tb_remove);
}
}else{//all others
if(document.getElementById("TB_overlay") === null){
$("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
$("#TB_overlay").click(tb_remove);
}
}

if(tb_detectMacXFF()){
$("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
}else{
$("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
}

if(caption===null){caption="";}
$("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
$('#TB_load').show();//show loader

var baseURL;
if(url.indexOf("?")!==-1){ //ff there is a query string involved
baseURL = url.substr(0, url.indexOf("?"));
}else{ 
baseURL = url;
}

var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
var urlType = baseURL.toLowerCase().match(urlString);

if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images

TB_PrevCaption = "";
TB_PrevURL = "";
TB_PrevHTML = "";
TB_NextCaption = "";
TB_NextURL = "";
TB_NextHTML = "";
TB_imageCount = "";
TB_FoundURL = false;
if(imageGroup){
TB_TempArray = $("a[@rel="+imageGroup+"]").get();
for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
if (!(TB_TempArray[TB_Counter].href == url)) {						
if (TB_FoundURL) {
TB_NextCaption = TB_TempArray[TB_Counter].title;
TB_NextURL = TB_TempArray[TB_Counter].href;
TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
} else {
TB_PrevCaption = TB_TempArray[TB_Counter].title;
TB_PrevURL = TB_TempArray[TB_Counter].href;
TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
}
} else {
TB_FoundURL = true;
TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);											
}
}
}

imgPreloader = new Image();
imgPreloader.onload = function(){		
imgPreloader.onload = null;

// Resizing large images - orginal by Christian Montoya edited by me.
var pagesize = tb_getPageSize();
var x = pagesize[0] - 150;
var y = pagesize[1] - 150;
var imageWidth = imgPreloader.width;
var imageHeight = imgPreloader.height;
if (imageWidth > x) {
imageHeight = imageHeight * (x / imageWidth); 
imageWidth = x; 
if (imageHeight > y) { 
imageWidth = imageWidth * (y / imageHeight); 
imageHeight = y; 
}
} else if (imageHeight > y) { 
imageWidth = imageWidth * (y / imageHeight); 
imageHeight = y; 
if (imageWidth > x) { 
imageHeight = imageHeight * (x / imageWidth); 
imageWidth = x;
}
}
// End Resizing

TB_WIDTH = imageWidth + 30;
TB_HEIGHT = imageHeight + 60;
$("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div>"); 		

$("#TB_closeWindowButton").click(tb_remove);

if (!(TB_PrevHTML === "")) {
function goPrev(){
if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);}
$("#TB_window").remove();
$("body").append("<div id='TB_window'></div>");
tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
return false;	
}
$("#TB_prev").click(goPrev);
}

if (!(TB_NextHTML === "")) {		
function goNext(){
$("#TB_window").remove();
$("body").append("<div id='TB_window'></div>");
tb_show(TB_NextCaption, TB_NextURL, imageGroup);				
return false;	
}
$("#TB_next").click(goNext);

}

document.onkeydown = function(e){ 	
if (e == null) { // ie
keycode = event.keyCode;
} else { // mozilla
keycode = e.which;
}
if(keycode == 27){ // close
tb_remove();
} else if(keycode == 190){ // display previous image
if(!(TB_NextHTML == "")){
document.onkeydown = "";
goNext();
}
} else if(keycode == 188){ // display next image
if(!(TB_PrevHTML == "")){
document.onkeydown = "";
goPrev();
}
}	
};

tb_position();
$("#TB_load").remove();
$("#TB_ImageOff").click(tb_remove);
$("#TB_window").css({display:"block"}); //for safari using css instead of show
};

imgPreloader.src = url;
}else{//code to show html

var queryString = url.replace(/^[^\?]+\??/,'');
var params = tb_parseQuery( queryString );

TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
ajaxContentW = TB_WIDTH - 30;
ajaxContentH = TB_HEIGHT - 45;

if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window		
urlNoQuery = url.split('TB_');
$("#TB_iframeContent").remove();
if(params['modal'] != "true"){//iframe no modal
$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
}else{//iframe modal
$("#TB_overlay").unbind();
$("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
}
}else{// not an iframe, ajax
if($("#TB_window").css("display") != "block"){
if(params['modal'] != "true"){//ajax no modal
$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>close</a> or Esc Key</div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
}else{//ajax modal
$("#TB_overlay").unbind();
$("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");	
}
}else{//this means the window is already up, we are just loading new content via ajax
$("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
$("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
$("#TB_ajaxContent")[0].scrollTop = 0;
$("#TB_ajaxWindowTitle").html(caption);
}
}

$("#TB_closeWindowButton").click(tb_remove);

if(url.indexOf('TB_inline') != -1){	
$("#TB_ajaxContent").append($('#' + params['inlineId']).children());
$("#TB_window").unload(function () {
$('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished
});
tb_position();
$("#TB_load").remove();
$("#TB_window").css({display:"block"}); 
}else if(url.indexOf('TB_iframe') != -1){
tb_position();
if($.browser.safari){//safari needs help because it will not fire iframe onload
$("#TB_load").remove();
$("#TB_window").css({display:"block"});
}
}else{
$("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
tb_position();
$("#TB_load").remove();
tb_init("#TB_ajaxContent a.thickbox");
$("#TB_window").css({display:"block"});
});
}

}

if(!params['modal']){
document.onkeyup = function(e){ 	
if (e == null) { // ie
keycode = event.keyCode;
} else { // mozilla
keycode = e.which;
}
if(keycode == 27){ // close
tb_remove();
}	
};
}

} catch(e) {
//nothing here
}
}

//helper functions below
function tb_showIframe(){
$("#TB_load").remove();
$("#TB_window").css({display:"block"});
}

function tb_remove() {
$("#TB_imageOff").unbind("click");
$("#TB_closeWindowButton").unbind("click");
$("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
$("#TB_load").remove();
if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
$("body","html").css({height: "auto", width: "auto"});
$("html").css("overflow","");
}
document.onkeydown = "";
document.onkeyup = "";
return false;
}

function tb_position() {
    $("#TB_window").css({ marginLeft: '-' + parseInt((TB_WIDTH / 2), 10) + 'px', width: TB_WIDTH + 'px' });
    $.browser.msie6 = $.browser.msie && /MSIE 6\.0/i.test(window.navigator.userAgent) && !/MSIE 7\.0/i.test(window.navigator.userAgent);
    if ( !(jQuery.browser.msie6)) { // take away IE6
        $("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
    }
}

function tb_parseQuery ( query ) {
var Params = {};
if ( ! query ) {return Params;}// return empty object
var Pairs = query.split(/[;&]/);
for ( var i = 0; i < Pairs.length; i++ ) {
var KeyVal = Pairs[i].split('=');
if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
var key = unescape( KeyVal[0] );
var val = unescape( KeyVal[1] );
val = val.replace(/\+/g, ' ');
Params[key] = val;
}
return Params;
}

function tb_getPageSize(){
var de = document.documentElement;
var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
arrayPageSize = [w,h];
return arrayPageSize;
}

function tb_detectMacXFF() {
var userAgent = navigator.userAgent.toLowerCase();
if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
return true;
}
}


/*
* jQuery UI 1.5.3
*
* Copyright (c) 2008 Paul Bakaus (ui.jquery.com)
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*
* http://docs.jquery.com/UI
*/
;(function($) {

$.ui = {
plugin: {
add: function(module, option, set) {
var proto = $.ui[module].prototype;
for(var i in set) {
proto.plugins[i] = proto.plugins[i] || [];
proto.plugins[i].push([option, set[i]]);
}
},
call: function(instance, name, args) {
var set = instance.plugins[name];
if(!set) { return; }

for (var i = 0; i < set.length; i++) {
if (instance.options[set[i][0]]) {
set[i][1].apply(instance.element, args);
}
}
}	
},
cssCache: {},
css: function(name) {
if ($.ui.cssCache[name]) { return $.ui.cssCache[name]; }
var tmp = $('<div class="ui-gen">').addClass(name).css({position:'absolute', top:'-5000px', left:'-5000px', display:'block'}).appendTo('body');

//if (!$.browser.safari)
//tmp.appendTo('body'); 

//Opera and Safari set width and height to 0px instead of auto
//Safari returns rgba(0,0,0,0) when bgcolor is not set
$.ui.cssCache[name] = !!(
(!(/auto|default/).test(tmp.css('cursor')) || (/^[1-9]/).test(tmp.css('height')) || (/^[1-9]/).test(tmp.css('width')) || 
!(/none/).test(tmp.css('backgroundImage')) || !(/transparent|rgba\(0, 0, 0, 0\)/).test(tmp.css('backgroundColor')))
);
try { $('body').get(0).removeChild(tmp.get(0));	} catch(e){}
return $.ui.cssCache[name];
},
disableSelection: function(el) {
$(el).attr('unselectable', 'on').css('MozUserSelect', 'none');
},
enableSelection: function(el) {
$(el).attr('unselectable', 'off').css('MozUserSelect', '');
},
hasScroll: function(e, a) {
var scroll = /top/.test(a||"top") ? 'scrollTop' : 'scrollLeft', has = false;
if (e[scroll] > 0) return true; e[scroll] = 1;
has = e[scroll] > 0 ? true : false; e[scroll] = 0;
return has;
}
};


/** jQuery core modifications and additions **/

var _remove = $.fn.remove;
$.fn.remove = function() {
$("*", this).add(this).triggerHandler("remove");
return _remove.apply(this, arguments );
};

// $.widget is a factory to create jQuery plugins
// taking some boilerplate code out of the plugin code
// created by Scott González and Jörn Zaefferer
function getter(namespace, plugin, method) {
var methods = $[namespace][plugin].getter || [];
methods = (typeof methods == "string" ? methods.split(/,?\s+/) : methods);
return ($.inArray(method, methods) != -1);
}

$.widget = function(name, prototype) {
var namespace = name.split(".")[0];
name = name.split(".")[1];

// create plugin method
$.fn[name] = function(options) {
var isMethodCall = (typeof options == 'string'),
args = Array.prototype.slice.call(arguments, 1);

if (isMethodCall && getter(namespace, name, options)) {
var instance = $.data(this[0], name);
return (instance ? instance[options].apply(instance, args)
: undefined);
}

return this.each(function() {
var instance = $.data(this, name);
if (isMethodCall && instance && $.isFunction(instance[options])) {
instance[options].apply(instance, args);
} else if (!isMethodCall) {
$.data(this, name, new $[namespace][name](this, options));
}
});
};

// create widget constructor
$[namespace][name] = function(element, options) {
var self = this;

this.widgetName = name;
this.widgetBaseClass = namespace + '-' + name;

this.options = $.extend({}, $.widget.defaults, $[namespace][name].defaults, options);
this.element = $(element)
.bind('setData.' + name, function(e, key, value) {
return self.setData(key, value);
})
.bind('getData.' + name, function(e, key) {
return self.getData(key);
})
.bind('remove', function() {
return self.destroy();
});
this.init();
};

// add widget prototype
$[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype);
};

$.widget.prototype = {
init: function() {},
destroy: function() {
this.element.removeData(this.widgetName);
},

getData: function(key) {
return this.options[key];
},
setData: function(key, value) {
this.options[key] = value;

if (key == 'disabled') {
this.element[value ? 'addClass' : 'removeClass'](
this.widgetBaseClass + '-disabled');
}
},

enable: function() {
this.setData('disabled', false);
},
disable: function() {
this.setData('disabled', true);
}
};

$.widget.defaults = {
disabled: false
};


/** Mouse Interaction Plugin **/

$.ui.mouse = {
mouseInit: function() {
var self = this;

this.element.bind('mousedown.'+this.widgetName, function(e) {
return self.mouseDown(e);
});

// Prevent text selection in IE
if ($.browser.msie) {
this._mouseUnselectable = this.element.attr('unselectable');
this.element.attr('unselectable', 'on');
}

this.started = false;
},

// TODO: make sure destroying one instance of mouse doesn't mess with
// other instances of mouse
mouseDestroy: function() {
this.element.unbind('.'+this.widgetName);

// Restore text selection in IE
($.browser.msie
&& this.element.attr('unselectable', this._mouseUnselectable));
},

mouseDown: function(e) {
// we may have missed mouseup (out of window)
(this._mouseStarted && this.mouseUp(e));

this._mouseDownEvent = e;

var self = this,
btnIsLeft = (e.which == 1),
elIsCancel = (typeof this.options.cancel == "string" ? $(e.target).parents().add(e.target).filter(this.options.cancel).length : false);
if (!btnIsLeft || elIsCancel || !this.mouseCapture(e)) {
return true;
}

this._mouseDelayMet = !this.options.delay;
if (!this._mouseDelayMet) {
this._mouseDelayTimer = setTimeout(function() {
self._mouseDelayMet = true;
}, this.options.delay);
}

if (this.mouseDistanceMet(e) && this.mouseDelayMet(e)) {
this._mouseStarted = (this.mouseStart(e) !== false);
if (!this._mouseStarted) {
e.preventDefault();
return true;
}
}

// these delegates are required to keep context
this._mouseMoveDelegate = function(e) {
return self.mouseMove(e);
};
this._mouseUpDelegate = function(e) {
return self.mouseUp(e);
};
$(document)
.bind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
.bind('mouseup.'+this.widgetName, this._mouseUpDelegate);

return false;
},

mouseMove: function(e) {
// IE mouseup check - mouseup happened when mouse was out of window
if ($.browser.msie && !e.button) {
return this.mouseUp(e);
}

if (this._mouseStarted) {
this.mouseDrag(e);
return false;
}

if (this.mouseDistanceMet(e) && this.mouseDelayMet(e)) {
this._mouseStarted =
(this.mouseStart(this._mouseDownEvent, e) !== false);
(this._mouseStarted ? this.mouseDrag(e) : this.mouseUp(e));
}

return !this._mouseStarted;
},

mouseUp: function(e) {
$(document)
.unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate)
.unbind('mouseup.'+this.widgetName, this._mouseUpDelegate);

if (this._mouseStarted) {
this._mouseStarted = false;
this.mouseStop(e);
}

return false;
},

mouseDistanceMet: function(e) {
return (Math.max(
Math.abs(this._mouseDownEvent.pageX - e.pageX),
Math.abs(this._mouseDownEvent.pageY - e.pageY)
) >= this.options.distance
);
},

mouseDelayMet: function(e) {
return this._mouseDelayMet;
},

// These are placeholder methods, to be overriden by extending plugin
mouseStart: function(e) {},
mouseDrag: function(e) {},
mouseStop: function(e) {},
mouseCapture: function(e) { return true; }
};

$.ui.mouse.defaults = {
cancel: null,
distance: 1,
delay: 0
};

})(jQuery);



/**
* SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
*
* SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*
*/
if(typeof deconcept == "undefined") var deconcept = new Object();
if(typeof deconcept.util == "undefined") deconcept.util = new Object();
if(typeof deconcept.SWFObjectUtil == "undefined") deconcept.SWFObjectUtil = new Object();
deconcept.SWFObject = function(swf, id, w, h, ver, c, quality, xiRedirectUrl, redirectUrl, detectKey) {
if (!document.getElementById) { return; }
this.DETECT_KEY = detectKey ? detectKey : 'detectflash';
this.skipDetect = deconcept.util.getRequestParameter(this.DETECT_KEY);
this.params = new Object();
this.variables = new Object();
this.attributes = new Array();
if(swf) { this.setAttribute('swf', swf); }
if(id) { this.setAttribute('id', id); }
if(w) { this.setAttribute('width', w); }
if(h) { this.setAttribute('height', h); }
if(ver) { this.setAttribute('version', new deconcept.PlayerVersion(ver.toString().split("."))); }
this.installedVer = deconcept.SWFObjectUtil.getPlayerVersion();
if (!window.opera && document.all && this.installedVer.major > 7) {
// only add the onunload cleanup if the Flash Player version supports External Interface and we are in IE
deconcept.SWFObject.doPrepUnload = true;
}
if(c) { this.addParam('bgcolor', c); }
var q = quality ? quality : 'high';
this.addParam('quality', q);
this.setAttribute('useExpressInstall', false);
this.setAttribute('doExpressInstall', false);
var xir = (xiRedirectUrl) ? xiRedirectUrl : window.location;
this.setAttribute('xiRedirectUrl', xir);
this.setAttribute('redirectUrl', '');
if(redirectUrl) { this.setAttribute('redirectUrl', redirectUrl); }
}
deconcept.SWFObject.prototype = {
useExpressInstall: function(path) {
this.xiSWFPath = !path ? "expressinstall.swf" : path;
this.setAttribute('useExpressInstall', true);
},
setAttribute: function(name, value){
this.attributes[name] = value;
},
getAttribute: function(name){
return this.attributes[name];
},
addParam: function(name, value){
this.params[name] = value;
},
getParams: function(){
return this.params;
},
addVariable: function(name, value){
this.variables[name] = value;
},
getVariable: function(name){
return this.variables[name];
},
getVariables: function(){
return this.variables;
},
getVariablePairs: function(){
var variablePairs = new Array();
var key;
var variables = this.getVariables();
for(key in variables){
variablePairs[variablePairs.length] = key +"="+ variables[key];
}
return variablePairs;
},
getSWFHTML: function() {
var swfNode = "";
if (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) { // netscape plugin architecture
if (this.getAttribute("doExpressInstall")) {
this.addVariable("MMplayerType", "PlugIn");
this.setAttribute('swf', this.xiSWFPath);
}
swfNode = '<embed type="application/x-shockwave-flash" src="'+ this.getAttribute('swf') +'" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'" style="'+ this.getAttribute('style') +'"';
swfNode += ' id="'+ this.getAttribute('id') +'" name="'+ this.getAttribute('id') +'" ';
var params = this.getParams();
for(var key in params){ swfNode += [key] +'="'+ params[key] +'" '; }
var pairs = this.getVariablePairs().join("&");
if (pairs.length > 0){ swfNode += 'flashvars="'+ pairs +'"'; }
swfNode += '/>';
} else { // PC IE
if (this.getAttribute("doExpressInstall")) {
this.addVariable("MMplayerType", "ActiveX");
this.setAttribute('swf', this.xiSWFPath);
}
swfNode = '<object id="'+ this.getAttribute('id') +'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'" style="'+ this.getAttribute('style') +'">';
swfNode += '<param name="movie" value="'+ this.getAttribute('swf') +'" />';
var params = this.getParams();
for(var key in params) {
swfNode += '<param name="'+ key +'" value="'+ params[key] +'" />';
}
var pairs = this.getVariablePairs().join("&");
if(pairs.length > 0) {swfNode += '<param name="flashvars" value="'+ pairs +'" />';}
swfNode += "</object>";
}
return swfNode;
},
write: function(elementId){
if(this.getAttribute('useExpressInstall')) {
// check to see if we need to do an express install
var expressInstallReqVer = new deconcept.PlayerVersion([6,0,65]);
if (this.installedVer.versionIsValid(expressInstallReqVer) && !this.installedVer.versionIsValid(this.getAttribute('version'))) {
this.setAttribute('doExpressInstall', true);
this.addVariable("MMredirectURL", escape(this.getAttribute('xiRedirectUrl')));
document.title = document.title.slice(0, 47) + " - Flash Player Installation";
this.addVariable("MMdoctitle", document.title);
}
}
if(this.skipDetect || this.getAttribute('doExpressInstall') || this.installedVer.versionIsValid(this.getAttribute('version'))){
var n = (typeof elementId == 'string') ? document.getElementById(elementId) : elementId;
n.innerHTML = this.getSWFHTML();
return true;
}else{
if(this.getAttribute('redirectUrl') != "") {
document.location.replace(this.getAttribute('redirectUrl'));
}
}
return false;
}
}

/* ---- detection functions ---- */
deconcept.SWFObjectUtil.getPlayerVersion = function(){
var PlayerVersion = new deconcept.PlayerVersion([0,0,0]);
if(navigator.plugins && navigator.mimeTypes.length){
var x = navigator.plugins["Shockwave Flash"];
if(x && x.description) {
PlayerVersion = new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/, "").replace(/(\s+r|\s+b[0-9]+)/, ".").split("."));
}
}else if (navigator.userAgent && navigator.userAgent.indexOf("Windows CE") >= 0){ // if Windows CE
var axo = 1;
var counter = 3;
while(axo) {
try {
counter++;
axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+ counter);
//				document.write("player v: "+ counter);
PlayerVersion = new deconcept.PlayerVersion([counter,0,0]);
} catch (e) {
axo = null;
}
}
} else { // Win IE (non mobile)
// do minor version lookup in IE, but avoid fp6 crashing issues
// see http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
try{
var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
}catch(e){
try {
var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
PlayerVersion = new deconcept.PlayerVersion([6,0,21]);
axo.AllowScriptAccess = "always"; // error if player version < 6.0.47 (thanks to Michael Williams @ Adobe for this code)
} catch(e) {
if (PlayerVersion.major == 6) {
return PlayerVersion;
}
}
try {
axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
} catch(e) {}
}
if (axo != null) {
PlayerVersion = new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));
}
}
return PlayerVersion;
}
deconcept.PlayerVersion = function(arrVersion){
this.major = arrVersion[0] != null ? parseInt(arrVersion[0]) : 0;
this.minor = arrVersion[1] != null ? parseInt(arrVersion[1]) : 0;
this.rev = arrVersion[2] != null ? parseInt(arrVersion[2]) : 0;
}
deconcept.PlayerVersion.prototype.versionIsValid = function(fv){
if(this.major < fv.major) return false;
if(this.major > fv.major) return true;
if(this.minor < fv.minor) return false;
if(this.minor > fv.minor) return true;
if(this.rev < fv.rev) return false;
return true;
}
/* ---- get value of query string param ---- */
deconcept.util = {
getRequestParameter: function(param) {
var q = document.location.search || document.location.hash;
if (param == null) { return q; }
if(q) {
var pairs = q.substring(1).split("&");
for (var i=0; i < pairs.length; i++) {
if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) {
return pairs[i].substring((pairs[i].indexOf("=")+1));
}
}
}
return "";
}
}
/* fix for video streaming bug */
deconcept.SWFObjectUtil.cleanupSWFs = function() {
var objects = document.getElementsByTagName("OBJECT");
for (var i = objects.length - 1; i >= 0; i--) {
objects[i].style.display = 'none';
for (var x in objects[i]) {
if (typeof objects[i][x] == 'function') {
objects[i][x] = function(){};
}
}
}
}
// fixes bug in some fp9 versions see http://blog.deconcept.com/2006/07/28/swfobject-143-released/
if (deconcept.SWFObject.doPrepUnload) {
if (!deconcept.unloadSet) {
deconcept.SWFObjectUtil.prepUnload = function() {
__flash_unloadHandler = function(){};
__flash_savedUnloadHandler = function(){};
window.attachEvent("onunload", deconcept.SWFObjectUtil.cleanupSWFs);
}
window.attachEvent("onbeforeunload", deconcept.SWFObjectUtil.prepUnload);
deconcept.unloadSet = true;
}
}
/* add document.getElementById if needed (mobile IE < 5) */
if (!document.getElementById && document.all) { document.getElementById = function(id) { return document.all[id]; }}

/* add some aliases for ease of use/backwards compatibility */
var getQueryParamValue = deconcept.util.getRequestParameter;
var FlashObject = deconcept.SWFObject; // for legacy support
var SWFObject = deconcept.SWFObject;


/**
 * Boxy 0.1.4 - Facebook-style dialog, with frills
 *
 * (c) 2008 Jason Frame
 * Licensed under the MIT License (LICENSE)
 */
 
/*
 * jQuery plugin
 *
 * Options:
 *   message: confirmation message for form submit hook (default: "Please confirm:")
 * 
 * Any other options - e.g. 'clone' - will be passed onto the boxy constructor (or
 * Boxy.load for AJAX operations)
 */
jQuery.fn.boxy = function(options) {
    options = options || {};
    return this.each(function() {      
        var node = this.nodeName.toLowerCase(), self = this;
        if (node == 'a') {
            jQuery(this).click(function() {
                var active = Boxy.linkedTo(this),
                    href = this.getAttribute('href'),
                    localOptions = jQuery.extend({actuator: this, title: this.title}, options);
                    
                if (active) {
                    active.show();
                } else if (href.indexOf('#') >= 0) {
                    var content = jQuery(href.substr(href.indexOf('#'))),
                        newContent = content.clone(true);
                    content.remove();
                    localOptions.unloadOnHide = false;
                    new Boxy(newContent, localOptions);
                } else { // fall back to AJAX; could do with a same-origin check
                    if (!localOptions.cache) localOptions.unloadOnHide = true;
                    Boxy.load(this.href, localOptions);
                }
                
                return false;
            });
        } else if (node == 'form') {
            jQuery(this).bind('submit.boxy', function() {
                Boxy.confirm(options.message || 'Please confirm:', function() {
                    jQuery(self).unbind('submit.boxy').submit();
                });
                return false;
            });
        }
    });
};

//
// Boxy Class

function Boxy(element, options) {
    
    this.boxy = jQuery(Boxy.WRAPPER);
    jQuery.data(this.boxy[0], 'boxy', this);
    
    this.visible = false;
    this.options = jQuery.extend({}, Boxy.DEFAULTS, options || {});
    
    if (this.options.modal) {
        this.options = jQuery.extend(this.options, {center: true, draggable: false});
    }
    
    // options.actuator == DOM element that opened this boxy
    // association will be automatically deleted when this boxy is remove()d
    if (this.options.actuator) {
        jQuery.data(this.options.actuator, 'active.boxy', this);
    }
    
    this.setContent(element || "<div></div>");
    this._setupTitleBar();
    
    this.boxy.css('display', 'none').appendTo(document.body);
    this.toTop();

    if (this.options.fixed) {
        if (jQuery.browser.msie && jQuery.browser.version < 7) {
            this.options.fixed = false; // IE6 doesn't support fixed positioning
        } else {
            this.boxy.addClass('fixed');
        }
    }
    
    if (this.options.center && Boxy._u(this.options.x, this.options.y)) {
        this.center();
    } else {
        this.moveTo(
            Boxy._u(this.options.x) ? this.options.x : Boxy.DEFAULT_X,
            Boxy._u(this.options.y) ? this.options.y : Boxy.DEFAULT_Y
        );
    }
    
    if (this.options.show) this.show();

};

Boxy.EF = function() {};

jQuery.extend(Boxy, {
    
    WRAPPER:    "<table cellspacing='0' cellpadding='0' border='0' class='boxy-wrapper'>" +
                "<tr><td class='top-left'></td><td class='top'></td><td class='top-right'></td></tr>" +
                "<tr><td class='left'></td><td class='boxy-inner'></td><td class='right'></td></tr>" +
                "<tr><td class='bottom-left'></td><td class='bottom'></td><td class='bottom-right'></td></tr>" +
                "</table>",
    
    DEFAULTS: {
        title:                  null,           // titlebar text. titlebar will not be visible if not set.
        closeable:              true,           // display close link in titlebar?
        draggable:              true,           // can this dialog be dragged?
        clone:                  false,          // clone content prior to insertion into dialog?
        actuator:               null,           // element which opened this dialog
        center:                 true,           // center dialog in viewport?
        show:                   true,           // show dialog immediately?
        modal:                  false,          // make dialog modal?
        fixed:                  true,           // use fixed positioning, if supported? absolute positioning used otherwise
        closeText:              '[close]',      // text to use for default close link
        unloadOnHide:           false,          // should this dialog be removed from the DOM after being hidden?
        clickToFront:           false,          // bring dialog to foreground on any click (not just titlebar)?
        behaviours:             Boxy.EF,        // function used to apply behaviours to all content embedded in dialog.
        afterDrop:              Boxy.EF,        // callback fired after dialog is dropped. executes in context of Boxy instance.
        afterShow:              Boxy.EF,        // callback fired after dialog becomes visible. executes in context of Boxy instance.
        afterHide:              Boxy.EF,        // callback fired after dialog is hidden. executed in context of Boxy instance.
        beforeUnload:           Boxy.EF         // callback fired after dialog is unloaded. executed in context of Boxy instance.
    },
    
    DEFAULT_X:          50,
    DEFAULT_Y:          50,
    zIndex:             1337,
    dragConfigured:     false, // only set up one drag handler for all boxys
    resizeConfigured:   false,
    dragging:           null,
    
    // load a URL and display in boxy
    // url - url to load
    // options keys (any not listed below are passed to boxy constructor)
    //   type: HTTP method, default: GET
    //   cache: cache retrieved content? default: false
    //   filter: jQuery selector used to filter remote content
    load: function(url, options) {
        
        options = options || {};
        
        var ajax = {
            url: url, type: 'GET', dataType: 'html', cache: false, success: function(html) {
                html = jQuery(html);
                if (options.filter) html = jQuery(options.filter, html);
                new Boxy(html, options);
            }
        };
        
        jQuery.each(['type', 'cache'], function() {
            if (this in options) {
                ajax[this] = options[this];
                delete options[this];
            }
        });
        
        jQuery.ajax(ajax);
        
    },
    
    // allows you to get a handle to the containing boxy instance of any element
    // e.g. <a href='#' onclick='alert(Boxy.get(this));'>inspect!</a>.
    // this returns the actual instance of the boxy 'class', not just a DOM element.
    // Boxy.get(this).hide() would be valid, for instance.
    get: function(ele) {
        var p = jQuery(ele).parents('.boxy-wrapper');
        return p.length ? jQuery.data(p[0], 'boxy') : null;
    },
    
    // returns the boxy instance which has been linked to a given element via the
    // 'actuator' constructor option.
    linkedTo: function(ele) {
        return jQuery.data(ele, 'active.boxy');
    },
    
    // displays an alert box with a given message, calling optional callback
    // after dismissal.
    alert: function(message, callback, options) {
        return Boxy.ask(message, ['OK'], callback, options);
    },
    
    // displays an alert box with a given message, calling after callback iff
    // user selects OK.
    confirm: function(message, after, options) {
        return Boxy.ask(message, ['OK', 'Abbrechen'], function(response) {
            if (response == 'OK') after();
        }, options);
    },
    
    // asks a question with multiple responses presented as buttons
    // selected item is returned to a callback method.
    // answers may be either an array or a hash. if it's an array, the
    // the callback will received the selected value. if it's a hash,
    // you'll get the corresponding key.
    ask: function(question, answers, callback, options) {
        
        options = jQuery.extend({modal: true, closeable: false},
                                options || {},
                                {show: true, unloadOnHide: true});
        
        var body = jQuery('<div></div>').append(jQuery('<div class="question"></div>').html(question));
        
        // ick
        var map = {}, answerStrings = [];
        if (answers instanceof Array) {
            for (var i = 0; i < answers.length; i++) {
                map[answers[i]] = answers[i];
                answerStrings.push(answers[i]);
            }
        } else {
            for (var k in answers) {
                map[answers[k]] = k;
                answerStrings.push(answers[k]);
            }
        }
        
        var buttons = jQuery('<form class="answers"></form>');
        buttons.html(jQuery.map(answerStrings, function(v) {
            return "<input type='button' value='" + v + "' />";
        }).join(' '));
        
        jQuery('input[type=button]', buttons).click(function() {
            var clicked = this;
            Boxy.get(this).hide(function() {
                if (callback) callback(map[clicked.value]);
            });
        });
        
        body.append(buttons);
        
        new Boxy(body, options);
        
    },
    
    // returns true if a modal boxy is visible, false otherwise
    isModalVisible: function() {
        return jQuery('.boxy-modal-blackout').length > 0;
    },
    
    _u: function() {
        for (var i = 0; i < arguments.length; i++)
            if (typeof arguments[i] != 'undefined') return false;
        return true;
    },
    
    _handleResize: function(evt) {
        var d = jQuery(document);
        jQuery('.boxy-modal-blackout').css('display', 'none').css({
            width: d.width(), height: d.height()
        }).css('display', 'block');
    },
    
    _handleDrag: function(evt) {
        var d;
        if (d = Boxy.dragging) {
            d[0].boxy.css({left: evt.pageX - d[1], top: evt.pageY - d[2]});
        }
    },
    
    _nextZ: function() {
        return Boxy.zIndex++;
    },
    
    _viewport: function() {
        var d = document.documentElement, b = document.body, w = window;
        return jQuery.extend(
            jQuery.browser.msie ?
                { left: b.scrollLeft || d.scrollLeft, top: b.scrollTop || d.scrollTop } :
                { left: w.pageXOffset, top: w.pageYOffset },
            !Boxy._u(w.innerWidth) ?
                { width: w.innerWidth, height: w.innerHeight } :
                (!Boxy._u(d) && !Boxy._u(d.clientWidth) && d.clientWidth != 0 ?
                    { width: d.clientWidth, height: d.clientHeight } :
                    { width: b.clientWidth, height: b.clientHeight }) );
    }

});

Boxy.prototype = {

// Returns the size of this boxy instance without displaying it.
// Do not use this method if boxy is already visible, use getSize() instead.
estimateSize: function() {
this.boxy.css({visibility: 'hidden', display: 'block'});
var dims = this.getSize();
this.boxy.css('display', 'none').css('visibility', 'visible');
return dims;
},

// Returns the dimensions of the entire boxy dialog as [width,height]
getSize: function() {
return [this.boxy.width(), this.boxy.height()];
},

// Returns the dimensions of the content region as [width,height]
getContentSize: function() {
var c = this.getContent();
return [c.width(), c.height()];
},

// Returns the position of this dialog as [x,y]
getPosition: function() {
var b = this.boxy[0];
return [b.offsetLeft, b.offsetTop];
},

// Returns the center point of this dialog as [x,y]
getCenter: function() {
var p = this.getPosition();
var s = this.getSize();
return [Math.floor(p[0] + s[0] / 2), Math.floor(p[1] + s[1] / 2)];
},

// Returns a jQuery object wrapping the inner boxy region.
// Not much reason to use this, you're probably more interested in getContent()
getInner: function() {
return jQuery('.boxy-inner', this.boxy);
},

// Returns a jQuery object wrapping the boxy content region.
// This is the user-editable content area (i.e. excludes titlebar)
getContent: function() {
return jQuery('.boxy-content', this.boxy);
},

// Replace dialog content
setContent: function(newContent) {
newContent = jQuery(newContent).css({display: 'block'}).addClass('boxy-content');
if (this.options.clone) newContent = newContent.clone(true);
this.getContent().remove();
this.getInner().append(newContent);
this._setupDefaultBehaviours(newContent);
this.options.behaviours.call(this, newContent);
return this;
},

// Move this dialog to some position, funnily enough
moveTo: function(x, y) {
this.moveToX(x).moveToY(y);
return this;
},

// Move this dialog (x-coord only)
moveToX: function(x) {
if (typeof x == 'number') this.boxy.css({left: x});
else this.centerX();
return this;
},

// Move this dialog (y-coord only)
moveToY: function(y) {
if (typeof y == 'number') this.boxy.css({top: y});
else this.centerY();
return this;
},

// Move this dialog so that it is centered at (x,y)
centerAt: function(x, y) {
var s = this[this.visible ? 'getSize' : 'estimateSize']();
if (typeof x == 'number') this.moveToX(x - s[0] / 2);
if (typeof y == 'number') this.moveToY(y - s[1] / 2);
return this;
},

centerAtX: function(x) {
return this.centerAt(x, null);
},

centerAtY: function(y) {
return this.centerAt(null, y);
},

// Center this dialog in the viewport
// axis is optional, can be 'x', 'y'.
center: function(axis) {
var v = Boxy._viewport();
var o = this.options.fixed ? [0, 0] : [v.left, v.top];
if (!axis || axis == 'x') this.centerAt(o[0] + v.width / 2, null);
if (!axis || axis == 'y') this.centerAt(null, o[1] + v.height / 2);
return this;
},

// Center this dialog in the viewport (x-coord only)
centerX: function() {
return this.center('x');
},

// Center this dialog in the viewport (y-coord only)
centerY: function() {
return this.center('y');
},

// Resize the content region to a specific size
resize: function(width, height, after) {
if (!this.visible) return;
var bounds = this._getBoundsForResize(width, height);
this.boxy.css({left: bounds[0], top: bounds[1]});
this.getContent().css({width: bounds[2], height: bounds[3]});
if (after) after(this);
return this;
},

// Tween the content region to a specific size
tween: function(width, height, after) {
if (!this.visible) return;
var bounds = this._getBoundsForResize(width, height);
var self = this;
this.boxy.stop().animate({left: bounds[0], top: bounds[1]});
this.getContent().stop().animate({width: bounds[2], height: bounds[3]}, function() {
if (after) after(self);
});
return this;
},

// Returns true if this dialog is visible, false otherwise
isVisible: function() {
return this.visible;    
},

// Make this boxy instance visible
show: function() {
if (this.visible) return;
if (this.options.modal) {
var self = this;
if (!Boxy.resizeConfigured) {
Boxy.resizeConfigured = true;
jQuery(window).resize(function() { Boxy._handleResize(); });
}
this.modalBlackout = jQuery('<div class="boxy-modal-blackout"></div>')
.css({zIndex: Boxy._nextZ(),
opacity: 0.7,
width: jQuery(document).width(),
height: jQuery(document).height()})
.appendTo(document.body);
this.toTop();
if (this.options.closeable) {
jQuery(document.body).bind('keypress.boxy', function(evt) {
var key = evt.which || evt.keyCode;
if (key == 27) {
self.hide();
jQuery(document.body).unbind('keypress.boxy');
}
});
}
}
this.boxy.stop().css({opacity: 1}).show();
this.visible = true;
this._fire('afterShow');
return this;
},

// Hide this boxy instance
hide: function(after) {
if (!this.visible) return;
var self = this;
if (this.options.modal) {
jQuery(document.body).unbind('keypress.boxy');
this.modalBlackout.animate({opacity: 0}, function() {
jQuery(this).remove();
});
}
this.boxy.stop().animate({opacity: 0}, 300, function() {
self.boxy.css({display: 'none'});
self.visible = false;
self._fire('afterHide');
if (after) after(self);
if (self.options.unloadOnHide) self.unload();
});
return this;
},

toggle: function() {
this[this.visible ? 'hide' : 'show']();
return this;
},

hideAndUnload: function(after) {
this.options.unloadOnHide = true;
this.hide(after);
return this;
},

unload: function() {
this._fire('beforeUnload');
this.boxy.remove();
if (this.options.actuator) {
jQuery.data(this.options.actuator, 'active.boxy', false);
}
},

// Move this dialog box above all other boxy instances
toTop: function() {
this.boxy.css({zIndex: Boxy._nextZ()});
return this;
},

// Returns the title of this dialog
getTitle: function() {
return jQuery('> .title-bar h2', this.getInner()).html();
},

// Sets the title of this dialog
setTitle: function(t) {
jQuery('> .title-bar h2', this.getInner()).html(t);
return this;
},

//
// Don't touch these privates

_getBoundsForResize: function(width, height) {
var csize = this.getContentSize();
var delta = [width - csize[0], height - csize[1]];
var p = this.getPosition();
return [Math.max(p[0] - delta[0] / 2, 0),
Math.max(p[1] - delta[1] / 2, 0), width, height];
},

_setupTitleBar: function() {
if (this.options.title) {
var self = this;
var tb = jQuery("<div class='title-bar'></div>").html("<h2>" + this.options.title + "</h2>");
if (this.options.closeable) {
tb.append(jQuery("<a href='#' class='close'></a>").html(this.options.closeText));
}
if (this.options.draggable) {
tb[0].onselectstart = function() { return false; }
tb[0].unselectable = 'on';
tb[0].style.MozUserSelect = 'none';
if (!Boxy.dragConfigured) {
jQuery(document).mousemove(Boxy._handleDrag);
Boxy.dragConfigured = true;
}
tb.mousedown(function(evt) {
self.toTop();
Boxy.dragging = [self, evt.pageX - self.boxy[0].offsetLeft, evt.pageY - self.boxy[0].offsetTop];
jQuery(this).addClass('dragging');
}).mouseup(function() {
jQuery(this).removeClass('dragging');
Boxy.dragging = null;
self._fire('afterDrop');
});
}
this.getInner().prepend(tb);
this._setupDefaultBehaviours(tb);
}
},

_setupDefaultBehaviours: function(root) {
var self = this;
if (this.options.clickToFront) {
root.click(function() { self.toTop(); });
}
jQuery('.close', root).click(function() {
self.hide();
return false;
}).mousedown(function(evt) { evt.stopPropagation(); });
},

_fire: function(event) {
this.options[event].call(this);
}

};


$(document).ready( function()
{
   PEPS.rollover.init();
});

PEPS = {};

PEPS.rollover =
{
init: function()
{
this.preload();

$(".hover").hover(
function () { $(this).attr( 'src', PEPS.rollover.newimage($(this).attr('src')) ); },
function () { $(this).attr( 'src', PEPS.rollover.oldimage($(this).attr('src')) ); }
);
},

preload: function()
{
$(window).bind('load', function() {
$('.hover').each( function( key, elm ) { $('<img>').attr( 'src', PEPS.rollover.newimage( $(this).attr('src') ) ); });
});
},

newimage: function( src )
{
return src.substring( 0, src.search(/(\.[a-z]+)$/) ) + '_hi' + src.match(/(\.[a-z]+)$/)[0];
},

oldimage: function( src )
{
return src.replace(/_hi\./, '.');
}

};



// ajaxfileupload.js
// http: //www.phpletter.com/Our-Projects/AjaxFileUpload/
jQuery.extend({
	createUploadIframe: function(id, uri) {
		//create frame
		var frameId = 'jUploadFrame' + id;

		if (window.ActiveXObject) {
			var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
			if (typeof uri == 'boolean') {
				io.src = 'javascript:false';
			}
			else if (typeof uri == 'string') {
				io.src = uri;
			}
		}
		else {
			var io = document.createElement('iframe');
			io.id = frameId;
			io.name = frameId;
		}
		io.style.position = 'absolute';
		io.style.top = '-1000px';
		io.style.left = '-1000px';

		document.body.appendChild(io);

		return io
	},
	createUploadForm: function(id, fileElementId) {
		//create form	
		var formId = 'jUploadForm' + id;
		var fileId = 'jUploadFile' + id;
		var form = $('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
		var oldElement = $('#' + fileElementId);
		var newElement = $(oldElement).clone();
		$(oldElement).attr('id', fileId);
		$(oldElement).before(newElement);
		$(oldElement).appendTo(form);
		//set attributes
		$(form).css('position', 'absolute');
		$(form).css('top', '-1200px');
		$(form).css('left', '-1200px');
		$(form).appendTo('body');
		return form;
	},

	ajaxFileUpload: function(s) {
		// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout		
		s = jQuery.extend({}, jQuery.ajaxSettings, s);
		var id = new Date().getTime()
		var form = jQuery.createUploadForm(id, s.fileElementId);
		var io = jQuery.createUploadIframe(id, s.secureuri);
		var frameId = 'jUploadFrame' + id;
		var formId = 'jUploadForm' + id;
		// Watch for a new set of requests
		if (s.global && !jQuery.active++) {
			jQuery.event.trigger("ajaxStart");
		}
		var requestDone = false;
		// Create the request object
		var xml = {}
		if (s.global)
			jQuery.event.trigger("ajaxSend", [xml, s]);
		// Wait for a response to come back
		var uploadCallback = function(isTimeout) {
			var io = document.getElementById(frameId);
			try {
				if (io.contentWindow) {
					xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;
					xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;

				} else if (io.contentDocument) {
					xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;
					xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;
				}
			} catch (e) {
				jQuery.handleError(s, xml, null, e);
			}
			if (xml || isTimeout == "timeout") {
				requestDone = true;
				var status;
				try {
					status = isTimeout != "timeout" ? "success" : "error";
					// Make sure that the request was successful or notmodified
					if (status != "error") {
						// process the data (runs the xml through httpData regardless of callback)
						var data = jQuery.uploadHttpData(xml, s.dataType);
						// If a local callback was specified, fire it and pass it the data
						if (s.success)
							s.success(data, status);

						// Fire the global callback
						if (s.global)
							jQuery.event.trigger("ajaxSuccess", [xml, s]);
					} else
						jQuery.handleError(s, xml, status);
				} catch (e) {
					status = "error";
					jQuery.handleError(s, xml, status, e);
				}

				// The request was completed
				if (s.global)
					jQuery.event.trigger("ajaxComplete", [xml, s]);

				// Handle the global AJAX counter
				if (s.global && ! --jQuery.active)
					jQuery.event.trigger("ajaxStop");

				// Process result
				if (s.complete)
					s.complete(xml, status);

				jQuery(io).unbind()

				setTimeout(function() {
					try {
						$(io).remove();
						$(form).remove();

					} catch (e) {
						jQuery.handleError(s, xml, null, e);
					}

				}, 100)

				xml = null

			}
		}
		// Timeout checker
		if (s.timeout > 0) {
			setTimeout(function() {
				// Check to see if the request is still happening
				if (!requestDone) uploadCallback("timeout");
			}, s.timeout);
		}
		try {
			// var io = $('#' + frameId);
			var form = $('#' + formId);
			$(form).attr('action', s.url);
			$(form).attr('method', 'POST');
			$(form).attr('target', frameId);
			if (form.encoding) {
				form.encoding = 'multipart/form-data';
			}
			else {
				form.enctype = 'multipart/form-data';
			}
			$(form).submit();

		} catch (e) {
			jQuery.handleError(s, xml, null, e);
		}
		if (window.attachEvent) {
			document.getElementById(frameId).attachEvent('onload', uploadCallback);
		}
		else {
			document.getElementById(frameId).addEventListener('load', uploadCallback, false);
		}
		return { abort: function() { } };

	},

	uploadHttpData: function(r, type) {
		var data = !type;
		data = type == "xml" || data ? r.responseXML : r.responseText;
		// If the type is "script", eval it in global context
		if (type == "script")
			jQuery.globalEval(data);
		// Get the JavaScript object, if JSON is used.
		if (type == "json")
			eval("data = " + data);
		// evaluate scripts within html
		if (type == "html")
			jQuery("<div>").html(data).evalScripts();
		//alert($('param', data).each(function(){alert($(this).attr('value'));}));
		return data;
	}
})