function strip_tags (input, allowed) {

           allowed = (((allowed || "") + "")
              .toLowerCase()
              .match(/<[a-z][a-z0-9]*>/g) || [])
              .join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)           
              var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
               commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
           return input.replace(commentsAndPhpTags, '').replace(tags, function($0, $1){
              return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
           });        }

function explode( delimiter, string ) {  // Split a string by string
  // 
  // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // + improved by: kenneth
  // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)

  var emptyArray = { 0: '' };

  if ( arguments.length != 2
  || typeof arguments[0] == 'undefined'
  || typeof arguments[1] == 'undefined' )
  {
  return null;
  }

  if ( delimiter === ''
  || delimiter === false
  || delimiter === null )
  {
  return false;
  }

  if ( typeof delimiter == 'function'
  || typeof delimiter == 'object'
  || typeof string == 'function'
  || typeof string == 'object' )
  {
  return emptyArray;
  }

  if ( delimiter === true ) {
  delimiter = '1';
  }

  return string.toString().split ( delimiter.toString() );
}

function number_format(number, decimals, dec_point, thousands_sep) {
  var n = !isFinite(+number) ? 0 : +number, 
  prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
  sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,  dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
  s = '',
  toFixedFix = function (n, prec) {
  var k = Math.pow(10, prec);
  return '' + Math.round(n * k) / k;  };
  // Fix for IE parseFloat(0.55).toFixed(0) = 0;
  s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
  if (s[0].length > 3) {
  s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);  }
  if ((s[1] || '').length < prec) {
  s[1] = s[1] || '';
  s[1] += new Array(prec - s[1].length + 1).join('0');
  }  return s.join(dec);
}
function str_replace (search, replace, subject, count) {
  // Replaces all occurrences of search in haystack with replace  
  // 
  // version: 1004.1212
  // discuss at: http://phpjs.org/functions/str_replace  // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // + improved by: Gabriel Paderni
  // + improved by: Philip Peterson
  // + improved by: Simon Willison (http://simonwillison.net)
  // +  revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)  // + bugfixed by: Anton Ongson
  // +  input by: Onno Marsman
  // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +  tweaked by: Onno Marsman
  // +  input by: Brett Zamir (http://brett-zamir.me)  // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // + input by: Oleg Eremeev
  // + improved by: Brett Zamir (http://brett-zamir.me)
  // + bugfixed by: Oleg Eremeev
  // %  note 1: The count parameter must be passed as a string in order  // %  note 1:  to find a global variable in which the result will be given
  // * example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
  // * returns 1: 'Kevin.van.Zonneveld'
  // * example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
  // * returns 2: 'hemmo, mars'  var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
  f = [].concat(search),
  r = [].concat(replace),
  s = subject,
  ra = r instanceof Array, sa = s instanceof Array;  s = [].concat(s);
  if (count) {
  this.window[count] = 0;
  }
 for (i=0, sl=s.length; i < sl; i++) {
  if (s[i] === '') {
  continue;
  }
  for (j=0, fl=f.length; j < fl; j++) {  temp = s[i]+'';
  repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
  s[i] = (temp).split(f[j]).join(repl);
  if (count && s[i] !== temp) {
  this.window[count] += (temp.length-s[i].length)/f[j].length;}  }
  }
  return sa ? s : s[0];
}

function strpos( haystack, needle, offset){  // Find position of first occurrence of a string
  // 
  // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)

  var i = haystack.indexOf( needle, offset ); // returns -1
  return i >= 0 ? i : false;
}

var tooltip=function(){ 
 var id = 'tt';
 var top = 3;
 var left = 3;
 var maxw = 500;
 var speed = 10;
 var timer = 20;
 var endalpha = 95;
 var alpha = 0;
 var tt,t,c,b,h;
 var ie = document.all ? true : false;
 return{
  show:function(v,w){
 if(tt == null){
  tt = document.createElement('div');
  tt.setAttribute('id',id);
  t = document.createElement('div');
  t.setAttribute('id',id + 'top');
  c = document.createElement('div');
  c.setAttribute('id',id + 'cont');
  b = document.createElement('div');
  b.setAttribute('id',id + 'bot');
  tt.appendChild(t);
  tt.appendChild(c);
  tt.appendChild(b);
  document.body.appendChild(tt);
  tt.style.opacity = 0;
  tt.style.filter = 'alpha(opacity=0)';
  document.onmousemove = this.pos;
 }
 tt.style.display = 'block';
 c.innerHTML = v;
 tt.style.width = w ? w + 'px' : 'auto';
 if(!w && ie){
  t.style.display = 'none';
  b.style.display = 'none';
  tt.style.width = tt.offsetWidth;
  t.style.display = 'block';
  b.style.display = 'block';
 }
  if(tt.offsetWidth > maxw){tt.style.width = maxw + 'px'}
  h = parseInt(tt.offsetHeight) + top;
  clearInterval(tt.timer);
  tt.timer = setInterval(function(){tooltip.fade(1)},timer);
  },
  pos:function(e){
 var u = ie ? event.clientY + document.documentElement.scrollTop : e.pageY;
 var l = ie ? event.clientX + document.documentElement.scrollLeft : e.pageX;
 tt.style.top = (u - h) + 'px';
 tt.style.left = (l + left) + 'px';
  },
  fade:function(d){
 var a = alpha;
 if((a != endalpha && d == 1) || (a != 0 && d == -1)){
  var i = speed;
 if(endalpha - a < speed && d == 1){
  i = endalpha - a;
 }else if(alpha < speed && d == -1){
 i = a;
 }
 alpha = a + (i * d);
 tt.style.opacity = alpha * .01;
 tt.style.filter = 'alpha(opacity=' + alpha + ')';
  }else{
  clearInterval(tt.timer);
 if(d == -1){tt.style.display = 'none'}
  }
 },
 hide:function(){
  clearInterval(tt.timer);
 tt.timer = setInterval(function(){tooltip.fade(-1)},timer);
  }
 };
}();


function getTop(element) {
  result = element.offsetTop;
  if (element.offsetParent) result += getTop(element.offsetParent);
  return result;
}

function getLeft(element) {
  result = element.offsetLeft;
  if (element.offsetParent) result += getLeft(element.offsetParent);
  return result;
}

var main_banner_id = 1;
var main_banner_timer = false;
function change_main_banner()
{
  main_banner_id++;
  if(!document.getElementById('section'+main_banner_id)) main_banner_id = 1;
  my_glider.next();
  change_banner_control(main_banner_id);
  main_banner_timer = setTimeout("change_main_banner()",9000);
}

var popup_listing_timer = false;
var popup_listing_close_timer = false;
var popup_listing_id = 0;
var popup_listing_obj = 0;
function show_popup_listing(obj, id)
{
  if(typeof obj == 'undefined') var obj =  popup_listing_obj;
  if(popup_listing_id!=id)
    popup_listing_timer = setTimeout(function(){show_popup_listing_go(obj, id)}, 100);
  clearTimeout(popup_listing_close_timer);
}

function hide_popup_listing()
{
  clearTimeout(popup_listing_timer);
  popup_listing_close_timer = setTimeout('jQuery(\'#small_popup\').html(\'\');popup_listing_id=0;', 700);
}

function show_popup_listing_go(obj, id)
{
  popup_listing_obj = obj;  
  popup_listing_id = id;
  document.getElementById('small_popup').style.display='none';  
  var small_popup = document.getElementById('small_popup');
  var top = getTop(obj);
  var left = getLeft(obj);

  jQuery("#small_popup").css({
  "top": top-100,
  "left": left-37
  });
  jQuery.ajax({
  type:"GET",
  url:_BASE_URL+"popup_listing.php",
  data: 'id='+id,
  success:function(msg){
  if(msg!='')
  {
  small_popup.innerHTML=msg;
  jQuery('#small_popup').show('slow');
  }
  }
  });
}

var last_main_listing_timer = false;
var last_main_listing_close_timer = false;
var last_main_listing_id = 0;
function show_last_main_listing(id)
{
  if(last_main_listing_id!=id)
  last_main_listing_timer = setTimeout('show_last_main_listing_popup("'+id+'")', 700);
  clearTimeout(last_main_listing_close_timer);
}

function hide_last_main_listing(id)
{
  clearTimeout(last_main_listing_timer);
  last_main_listing_close_timer = setTimeout('jQuery(\'#small_popup\').html(\'\');last_main_listing_id=0;', 700);
}

function change_quantity()
{
  if(document.getElementById('quantity').value>1)
  {
  document.getElementById('reserve').checked = false;
  document.getElementById('buy_out').checked = true;
  document.getElementById('offer_range').checked = false;
  enable_textfield(document.getElementById('reserve'), 'reserve_price');
  enable_textfield(document.getElementById('buy_out'), 'buy_out_price');
  enable_textfield(document.getElementById('offer_range'), 'offer_range_price_min');
  document.getElementById('auction').disabled = true; 
  document.getElementById('auction').checked = false; 
  enable_textfield(document.getElementById('auction'), 'start_price');
  document.getElementById('start_price').disabled = true; 
  document.getElementById('start_price').style.color = '#dddddd';
  document.getElementById('start_price').value = '';
//  document.getElementById('qmess').innerHTML = 'For Quantity above 1 only buy now feature is available';
  
  jQuery(".only_buy_now_cont").each(function(ind,obj){obj.style.display='none';  });
  }
  else
  {
      document.getElementById('auction').disabled = false;
      enable_textfield(document.getElementById('auction'), 'start_price');
 
  document.getElementById('qmess').innerHTML = '';
  if(document.getElementById('product_id'))
  jQuery(".only_buy_now_cont").each(function(ind,obj){obj.style.display='table-row';  });
  else
  jQuery(".only_buy_now_cont").each(function(ind,obj){obj.style.display='block';  });
  }
}

function fill_quantity(pid, max)
{
    if(document.getElementById('buy_now_quantity'+pid) && max<=10 && document.getElementById('buy_now_quantity'+pid).innerHTML=='')
    {
        var text = '';
        for(var i=1;i<=max;i++)
            text += '<option value="'+i+'">'+i+'</option>';
        document.getElementById('buy_now_quantity'+pid).innerHTML = text;
    }
    show_popup_text(document.getElementById('buy_now_confirm'+pid).innerHTML, 450, 300);
}

function validate_bid()
{
  validate_reg(document.getElementById('bid'),'0-9.');
  if(strpos(document.getElementById('bid').value,'.'))
  {
  var temp = explode('.',document.getElementById('bid').value);
  document.getElementById('bid').value=temp[0]+'.'+temp[1].substr(0,2);
  }
  if(typeof this.window['convert_bid_to_USD'] == 'function') document.getElementById('USD_bid').innerHTML = number_format(convert_bid_to_USD(document.getElementById('bid').value),2,'.',',');
  if(typeof this.window['convert_bid_to_EUR'] == 'function') document.getElementById('EUR_bid').innerHTML = number_format(convert_bid_to_EUR(document.getElementById('bid').value),2,'.',',');
  if(typeof this.window['convert_bid_to_GBP'] == 'function') document.getElementById('GBP_bid').innerHTML = number_format(convert_bid_to_GBP(document.getElementById('bid').value),2,'.',',');
}

function validate_offer()
{
  validate_reg(document.getElementById('offer'),'0-9.');
  if(strpos(document.getElementById('offer').value,'.'))
  {
  var temp = explode('.',document.getElementById('bid').value);
  document.getElementById('offer').value=temp[0]+'.'+temp[1].substr(0,2);
  }
  if(typeof this.window['convert_bid_to_USD'] == 'function') document.getElementById('USD_offer').innerHTML = number_format(convert_bid_to_USD(document.getElementById('offer').value),2,'.',',');
  if(typeof this.window['convert_bid_to_EUR'] == 'function') document.getElementById('EUR_offer').innerHTML = number_format(convert_bid_to_EUR(document.getElementById('offer').value),2,'.',',');
  if(typeof this.window['convert_bid_to_GBP'] == 'function') document.getElementById('GBP_offer').innerHTML = number_format(convert_bid_to_GBP(document.getElementById('offer').value),2,'.',',');
}

function show_last_main_listing_popup(id)
{
  last_main_listing_id = id;
  document.getElementById('small_popup').style.display='none';  
  var small_popup = document.getElementById('small_popup');
  var obj = document.getElementById('sc_link'+id);
  var top = getTop(document.getElementById('subcat_count'+id));
  var left = getLeft(document.getElementById('subcat_count'+id));

  jQuery("#small_popup").css({
  "top": top-100,
  "left": left-37
  });
  jQuery.ajax({
  type:"GET",
  url:_BASE_URL+"popup_last_main_listing.php",
  data: 'categ='+id,
  success:function(msg){
  if(msg!='')
  {
  small_popup.innerHTML=msg;
  jQuery('#small_popup').show('slow');
  }
  }
  });
}

function remove_widget(id)
{
  jQuery.ajax({
  type:"GET",
  url:_BASE_URL+"ajax_remove_widget.php",
  data: 'id='+id,
  success:function(msg){
  jQuery("#widget_title"+id).remove();
  jQuery("#widget_"+id).remove();
  jQuery("#widget_play").html('');  
  }
  });
}

function home_page_listing_category(categ,prefix)
{ 
  if(document.getElementById(prefix+'subcats'+categ).style.display=='none')
  {
  jQuery('#'+prefix+'subcats'+categ).show(600); 
  jQuery('.'+prefix+'line'+categ).addClass('active'); 
  }
  else
  {
  jQuery('#'+prefix+'subcats'+categ).hide(600); 
  jQuery('.'+prefix+'line'+categ).removeClass('active'); 
  }
}

function cancel_post()
{
  if(document.getElementById('reply'+last_forum_reply_container)) document.getElementById('reply'+last_forum_reply_container).innerHTML = '';
  last_forum_reply_container = 0;
}

var last_forum_reply_container = 0;
var ckeditor_counter = 0;
function reply_forum(id, quote, who)
{
  if(who==undefined) var who = '';  
  if(document.getElementById('reply'+last_forum_reply_container)) document.getElementById('reply'+last_forum_reply_container).innerHTML = '';
  var form = '';
  if(quote!=undefined)
  form += '<input type="hidden" name="quote" value="'+id+'">';
  form += '<div class="comtcorns"><div class="comltcorn"></div><div class="comrtcorn"></div></div>';
  form += '<div class="leavecom">';
  form += '<div id="comment_add_fields">';
  if(quote!=undefined)
  form += '  Quote '+who+':<br>';
  else
 form += '  Reply:<br>'; 
  form += '  <center><span class="error" id="form_error"></span></center>';
  form += '</div>';
  form += '<textarea id="ckeditor'+ckeditor_counter+'" class="leavecomform" onkeyup="if(this.value.length>1000)this.value=this.value.substr(0,1000);"></textarea>'; 
  form += '<div id="2comment_add_fields" style="height:50px;">';
  form += '  <div style="float:left"><br><a href="#current" onclick="add_post()" class="button">Reply</a></div>';
  form += '  <div style="float:left;padding-left:5px;"><br><a href="#current" onclick="cancel_post()" class="button">Cancel</a></div>';
  form += '</div>';
  form += '</div>';
  form += '<div class="combcorns"><div class="comlbcorn"></div><div class="comrbcorn"></div></div><br>';

  document.getElementById('reply'+id).innerHTML = form;  
  last_forum_reply_container = id;
  init_ckeditor(ckeditor_counter, 1);
  ckeditor_counter++;
} 

function edit_forum(id, quote)
{
  if(document.getElementById('reply'+last_forum_reply_container)) document.getElementById('reply'+last_forum_reply_container).innerHTML = '';
  var form = '';
  form += '<input type="hidden" name="edit" value="'+id+'">';
  form += '<div class="comtcorns"><div class="comltcorn"></div><div class="comrtcorn"></div></div>';
  form += '<div class="leavecom">';
  form += '<div id="comment_add_fields">';
  form += '  Edit:<br>'; 
  form += '  <center><span class="error" id="form_error"></span></center>';
  form += '</div>';
  form += '<textarea id="ckeditor'+ckeditor_counter+'" class="leavecomform"></textarea>'; 
  form += '<div id="2comment_add_fields" style="height:50px;">';
  form += '  <div style="float:left"><br><a href="#current" onclick="add_post()" class="button">Save</a></div>';
  form += '  <div style="float:left;padding-left:5px;"><br><a href="#current" onclick="cancel_post()" class="button">Cancel</a></div>';
  form += '</div>';
  form += '</div>';
  form += '<div class="combcorns"><div class="comlbcorn"></div><div class="comrbcorn"></div></div><br>';

  document.getElementById('reply'+id).innerHTML = form;  
  document.getElementById('ckeditor'+ckeditor_counter).value = document.getElementById('message_text'+id).innerHTML;  
  last_forum_reply_container = id;
  init_ckeditor(ckeditor_counter, 1);
  ckeditor_counter++;
}  

function add_post()
{  
  var i = ckeditor_counter-1;
  jQuery("#text").val(eval("CKEDITOR.instances.ckeditor"+i+".getData()"));
  submit_ajax_form(document.forum_post_form, 'forum_posts'); 
}

function quote_forum(id, who)
{
  reply_forum(id, 1, who);
} 

function filter_ebay_listings(keyword)
{
    keyword = keyword.toLowerCase();
    jQuery('.ebay_import_row').each(function(id, obj){
        var temp = jQuery(obj).find('td:last').html().toLowerCase().replace(keyword, '^');
        if(keyword == '' || temp.indexOf('^')>=0) 
            jQuery(obj).show();
        else
            jQuery(obj).hide();
    });
}

function topic_preview()
{
  jQuery.ajaxUpload({
 url:_BASE_URL+'ajax_wrap_text.php',
 secureuri:false,
 uploadform: document.cur_ajax_form_feedback,
 dataType: 'html',  
 success: function (msg, status){ 
  var preview = document.getElementById('topic_preview').innerHTML;
  preview = str_replace("[TOPIC_TITLE]",document.getElementById('title').value,preview);
  preview = str_replace("[TOPIC_TEXT]",msg,preview);
  document.getElementById('topic_preview_container').innerHTML=preview; 
  },
  error: function (data, status, e)
  {
  if(e=='TypeError: i.contentWindow is null') 
  add_post();
  //else
  //alert('+'+e);  
  } 
 }); 
}

function expand_collapse(type)
{
  if(document.getElementById(type).style.display=='none')
  {
  jQuery('#'+type).show(600);
  jQuery('#'+type+'_link').addClass('active');
  }
  else
  {
  jQuery('#'+type).hide(600); 
  jQuery('#'+type+'_link').removeClass('active');  
  }  
}

function show_options(type,prefix)
{
  if(prefix==undefined) var prefix = 'listing_options';
  if(document.getElementById(prefix+type).style.display!='none')
  jQuery('#'+prefix+type).hide(600);  
  else
  {
  jQuery("."+prefix).each(function(ind,obj){obj.style.display='none';  });
  jQuery('#'+prefix+type).show(600); 
  }
}

var category = 0;
var subcategory = 0;
var subcategory3 = 0;
var price_from = 0;
var price_to = 1500;
var t_price_from = 0;
var t_price_to = 1500;
var feedback_search = 0;
function change_filter_subcategory3(subcateg3,noapply)
{
  curr_back_action = "change_filter_category(0);jQuery('#backbut').html('');";  
  jQuery('#backbut').html('Back');
  jQuery("#filter_categ ul li ul li ul li").each(function(ind,obj){
      if(obj.id!='') jQuery('#'+obj.id).removeClass('active');
  });
  jQuery('#'+'subcateg3_'+subcateg3).addClass('active');
  
  subcategory3 = subcateg3;
  if(noapply == undefined)
  apply_search_filter();
}

function change_filter_subcategory(subcateg,noapply)
{
  curr_back_action = "change_filter_category(0);jQuery('#backbut').html('');";  
  jQuery('#backbut').html('Back');
  jQuery("#filter_categ ul li ul li").each(function(ind,obj){
      if(obj.id!='') jQuery('#'+obj.id).removeClass('active');
  });
  jQuery('#'+'subcateg'+subcateg).addClass('active');
  jQuery("#filter_categ ul li ul li ul").each(function(ind,obj){obj.style.display='none';  });
  
  jQuery.ajax({
  type:"GET",
  url:_BASE_URL+"ajax_subcategories3_filter.php",
  data: 'id='+subcateg,
  success:function(msg){
  document.getElementById('subcateg3_cont'+subcateg).innerHTML=msg;
  if(msg!='')jQuery('#subcateg3_cont'+subcateg).show(600); 
  }
  });
  subcategory3 = 0;
  subcategory = subcateg;
  if(noapply == undefined)
  apply_search_filter();
}

var curr_back_action = '';
function change_filter_category(categ,noapply)
{
  curr_back_action = "change_filter_category(0);jQuery('#backbut').html('');";  
  jQuery('#backbut').html('Back');
  if(categ==31)
    jQuery('#keyword_title').html('University/College');  
  else
    jQuery('#keyword_title').html('Keywords');  
  jQuery("#filter_categ ul li").each(function(ind,obj){
      if(obj.id!='')
      {
          jQuery('#'+obj.id).removeClass('active');  
          if(categ > 0 && obj.id!='categ'+categ)
             jQuery('#'+obj.id).hide(600);  
          if(categ == 0)
            jQuery('#'+obj.id).show(600);  
      } 
  });
  jQuery("#filter_categ ul li ul").each(function(ind,obj){obj.style.display='none';  });
  jQuery('#'+'categ'+categ).addClass('active');  
  if(categ>0)
  {
  jQuery.ajax({
  type:"GET",
  url:_BASE_URL+"ajax_subcategories_filter.php",
  data: 'id='+categ,
  success:function(msg){
  document.getElementById('subcateg_cont'+categ).innerHTML=msg;
  jQuery('#subcateg_cont'+categ).show(600); 
  }
  });
  }
  category = categ;
  subcategory = 0;
  subcategory3 = 0;
  if(noapply == undefined)
  apply_search_filter();
}

function search_categ_back()
{
    eval(curr_back_action);
}

function save_query(params)
{
  var query_name = document.getElementById('query_name').value;
  jQuery.ajax({
  type:"GET",
  url:_BASE_URL+"ajax_save_query.php",
  data: 'query_name='+query_name+'&'+params,
  success:function(msg){
  document.getElementById('queries_container').innerHTML = msg + document.getElementById('queries_container').innerHTML;
  }
  });
}

function remove_query(id)
{
  var query_name = document.getElementById('query_name').value;
  jQuery.ajax({
  type:"GET",
  url:_BASE_URL+"ajax_save_query.php",
  data: 'id='+id+'&remove=1',
  success:function(msg){
  jQuery('#query_container'+id).remove();
  }
  });
}

function getuserlist()
{  
  var tags = document.getElementById('seller').value;
  if(tags.length>2)
  {
  var container = document.getElementById('autoenter_div');
  jQuery.ajax({
  type: "GET",
  url: _BASE_URL+"ajax_getUserList.php",
  data: "keyword="+tags,
  success: function(msg){
 container.innerHTML = msg;
 container.style.display = 'block';  
 }
 });
  }  
}

function insertSearch(val)
{
  if(val!='') {document.getElementById('seller').value = val;  apply_search_filter();}
  document.getElementById('autoenter_div').style.display = 'none'; 
  
} 

function change_activity_filter(script, action)
{
    jQuery('#my_activity_all a').removeClass('active_blue');
    jQuery('#my_activity_outbid a').removeClass('active_blue');
    jQuery('#my_activity_pp a').removeClass('active_blue');
    jQuery('#my_activity_paid a').removeClass('active_blue');
    jQuery('#my_activity_watch a').removeClass('active_blue');
    jQuery('#my_activity_shipped a').removeClass('active_blue');
    jQuery('#my_listings_all a').removeClass('active_blue');
    jQuery('#my_listings_sold a').removeClass('active_blue');
    jQuery('#my_listings_unsold a').removeClass('active_blue');
    jQuery('#my_listings_running a').removeClass('active_blue');
    jQuery('#my_listings_shipped a').removeClass('active_blue');
    jQuery('#my_listings_inactive a').removeClass('active_blue');
    jQuery('#my_listings_paid a').removeClass('active_blue');
    jQuery('#'+script+'_'+action+' a').addClass('active_blue');
  
    last_activity_action = action;
    last_activity_script = script;
    profile_show_content('action='+action,script, 'my_activity_cont');
} 
var last_activity_action = 'watch';
var last_activity_script = 'my_activity';
var no_search_action = 0;

function reset_search()
{
  document.getElementById('is_feature').value = '1';
  document.getElementById('buynow').checked = false;
  document.getElementById('media').checked = false;
  document.getElementById('auct').checked = false;
  document.getElementById('payment_moneybookers').checked = false;
  document.getElementById('payment_paypal').checked = false;
  document.getElementById('payment_google').checked = false;
  document.getElementById('direct_postal').checked = false;
  document.getElementById('direct_other').checked = false;
  document.getElementById('direct_cheque').checked = false;
  document.getElementById('return').checked = false;
  document.getElementById('f_price').value = '';
  document.getElementById('s_price').value = '';
  document.getElementById('keyword').value = '';
  document.getElementById('seller').value = '';
  
  jQuery(".facelist .token").each(function(ind,obj){ jQuery(obj).remove(); });
  jQuery(".facelist2 .token").each(function(ind,obj){ jQuery(obj).remove(); });
  
  no_search_action = 1;
  jQuery(".rating-cancel").click();
  change_filter_category(0);
  no_search_action = 0;
  apply_search_filter();
}

function apply_search_filter(onlysave)
{
  if(no_search_action > 0) return false;  
  var is_feature = document.getElementById('is_feature').value;
  document.getElementById('is_feature').value = '0';
  var default_view = document.getElementById('default_view').value;
  document.getElementById('default_view').value = '';
  if(document.getElementById('vtype_g')) var vtype_g = 'g'; else var vtype_g = '';
  if(document.getElementById('buynow').checked) var buynow = 1; else var buynow = 0;
  if(document.getElementById('media').checked) var media = 1; else var media = 0;
  if(document.getElementById('auct').checked) var auct = 1; else var auct = 0;
  if(document.getElementById('payment_moneybookers').checked) var payment_moneybookers = 1; else var payment_moneybookers = 0;
  if(document.getElementById('payment_paypal').checked) var payment_paypal = 1; else var payment_paypal = 0;
  if(document.getElementById('payment_google').checked) var payment_google = 1; else var payment_google = 0;
  if(document.getElementById('direct_postal').checked) var direct_postal = 1; else var direct_postal = 0;
  if(document.getElementById('direct_other').checked) var direct_other = 1; else var direct_other = 0;
  if(document.getElementById('direct_cheque').checked) var direct_cheque = 1; else var direct_cheque = 0;
  if(document.getElementById('return').checked) var rturn = 1; else var rturn = 0;
  var price_to = document.getElementById('f_price').value;
  var price_from = document.getElementById('s_price').value;
  if(document.getElementById('college_filter') && document.getElementById('college_filter').checked)
    var college_filter = 1;
  else
    var college_filter = 0;
  
  var country_id = '';
  var seller_country = '';
  jQuery(".facelist .token").each(function(ind,obj){ country_id += ','+obj.id; });
  jQuery(".facelist2 .token").each(function(ind,obj){ seller_country += ','+obj.id; });

  var params = 'default_view='+default_view+'&vtype='+vtype_g+'&is_feature='+is_feature+'&college_filter='+college_filter+'&return='+rturn+'&payment_moneybookers='+payment_moneybookers+'&payment_paypal='+payment_paypal+'&payment_google='+payment_google+
  '&direct_postal='+direct_postal+'&direct_other='+direct_other+'&direct_cheque='+direct_cheque+'&media='+media+'&auct='+auct+'&buynow='+buynow+
  '&keyword='+document.getElementById('keyword').value+'&seller='+document.getElementById('seller').value+'&price_to='+price_to+'&price_from='+price_from+
  '&category='+category+'&subcategory='+subcategory+'&subcategory3='+subcategory3+'&feedback_search='+feedback_search+'&country_id='+country_id+'&seller_country='+seller_country;
  
  if(onlysave != undefined && onlysave>0) 
  save_query(params);
  else
  profile_show_content(params,'main_listing', 'main_listing');
}

function sg_over(obj)
{
    jQuery(obj).parent().addClass('featactive').find('.gfav').show();
    jQuery(obj).parent().find('.qview').show();
}

function sg_out(obj)
{
    jQuery(obj).parent().removeClass('featactive').find('.gfav').hide();
    jQuery(obj).parent().find('.qview').hide();
}

function sfollow(obj, id, type)
{
    jQuery.ajax({
      type: "GET",
      url: _BASE_URL+"sub_unsub.php",
      data: 'id='+id+'&type='+type,
      success: function(msg){
        if(msg == 'Follow') 
            jQuery(obj).find('img').attr({'src':'/templates/default/n_img/gfav.png'});
        else
            jQuery(obj).find('img').attr({'src':'/templates/default/n_img/gfav_a.png'});
     }
     }); 
}

function quick_view_listing(id)
{
    jQuery.ajax({
      type: "GET",
      url: _BASE_URL+"product.php",
      data: 'short=1&ID='+id,
      success: function(msg){
        show_popup_text(msg, 900, 500);
     }
     }); 
    
}

function show_comment_form(id)
{
  document.getElementById('1comment_add_fields').innerHTML = document.getElementById('1comment_form'+id).innerHTML;
  document.getElementById('2comment_add_fields').innerHTML = document.getElementById('2comment_form'+id).innerHTML;
}

function post_comment(id, type,pid, cid)
{
  jQuery.ajax({
  type:"POST",
  url:_BASE_URL+"ajax_postComment.php",
  data: 'cid='+cid+'&type='+type+'&id='+id+'&text='+jQuery(".leavecomform").val(),
  success:function(msg){
  profile_show_content('type='+type+'&ID='+pid,'wall', 'wall_container');
  }
  });
}

function show_delete_post_button(id,act)
{
  var obj=document.getElementById('post'+id);
  if(obj)
  {
  if(act>0)
  obj.style.display='block';
  else 
  obj.style.display='none';
  }
}

function check_timezone()
{
  var d = new Date()
  var gmtHours = d.getTimezoneOffset();
  jQuery.ajax({
  type: "GET",
  url: _BASE_URL+"ajax_check_timezone.php",
  data: "time="+gmtHours,
  success: function(msg){
  if(msg!='ok') setTimeout("check_timezone()",10000);
 }
 }); 
 
}


function add_vote_option()
{
    var text = jQuery('#word_container').html();
    jQuery('#word_container').before(str_replace('type="text"','type="text" value="'+jQuery('#word_container input').val()+'"',text));
    jQuery(".add_opt_link").remove();
    jQuery('#word_container').html(text);
    jQuery('#word_container input').val();
}

function ban_ip(obj, ip)
{
    jQuery.ajax({
  type: "GET",
  url: _BASE_URL+"ajax_ban_ip.php",
  data: "ip="+ip,
  success: function(msg){
  obj.style.display = 'none';
 }
 }); 
}

function set_phone_code(country)
{
  var phone = document.getElementById('phone');
  jQuery.ajax({
  type: "GET",
  url: _BASE_URL+"set_phone_code.php",
  data: "phone="+phone.value+"&country="+country,
  success: function(msg){
 if(msg.substr(0,1)!='+')  msg = '+'+msg;
 phone.value = ''+msg;
 }
 }); 
 jQuery('#to_users').val('');
 jQuery('#city').val('');
 jQuery('#city').show();
 jQuery('#result_list').html('');
 jQuery('.token').remove();
}

function get_multi_deny()
{
    var listings = '';
    jQuery('.mdeny').each(function(ind,obj){if(obj.checked) listings += obj.value+',';});
    return listings;
}

function validate_reg(obj, reg)
{
  eval('obj.value = obj.value.replace(/[^'+reg+']/g,\'\'); '); 
}


function validate_profile_form(type,step)
{
  var errors = 0;
  if(type == 'Email1' || (type == 'all' && step>=1))
  {
      jQuery.ajax({
      type: "GET",
      async: false,
      url: _BASE_URL+"check_email.php",
      data: "value="+document.getElementById('Email1').value,
      success: function(msg){
      errors += set_error('Email1', msg)
     }
     }); 
  }
  if(type == 'fname' || (type == 'all' && step>=3))
  {
  if(document.getElementById('fname').value.length<2) errors += set_error('fname', ''); else errors += set_error('fname', 'ok');
  }
  if(type == 'lname' || (type == 'all' && step>=3))
  {
  if(document.getElementById('lname').value.length<2) errors += set_error('lname', ''); else errors += set_error('lname', 'ok');
  }
  if(type == 'country' || (type == 'all' && step>=2))
  {
  if(document.getElementById('country').value.length<1) errors += set_error('country', ''); else errors += set_error('country', 'ok');
  }
  if(type == 'city' || (type == 'all' && step>=2))
  {
  if(document.getElementById('city').value.length<1 && (!document.getElementById('to_users') || document.getElementById('to_users').value.length<1)) errors += set_error('city', ''); else errors += set_error('city', 'ok');
  }
  if(type == 'address' || (type == 'all' && step>=2))
  {
  if(document.getElementById('address').value.length<1) errors += set_error('address', ''); else errors += set_error('address', 'ok');
  }
  //if(type == 'phone' || (type == 'all' && step>=2))
  //{
  //if(document.getElementById('phone').value.length<8) errors += set_error('phone', ''); else errors += set_error('phone', 'ok');
  //}
  if(type == 'zip' || (type == 'all' && step>=2))
  {
  if(document.getElementById('zip').value.length<1) errors += set_error('zip', ''); else errors += set_error('zip', 'ok');
  }
  if(type == 'NickName' || (type == 'all' && step>=1))
  {
  jQuery.ajax({
  type: "GET",
  async: false,
  url: _BASE_URL+"check_nick.php",
  data: "value="+document.getElementById('NickName').value,
  success: function(msg){
 errors += set_error('NickName', msg)
 }
 }); 
  }
  if(type == 'Password1' || (type == 'all' && step>=1))
  {
  jQuery.ajax({
  type: "GET",
  async: false,
  url: _BASE_URL+"check_password.php",
  data: "value="+document.getElementById('Password1').value,
  success: function(msg){
      if(msg == 'Enter password')
      errors += set_error('Password1', msg)
      else
      set_error('Password1', msg)
 }
 }); 
  }
  if(type == 'Password2' || (type == 'all' && step>=1))
  {
  var temp = document.getElementById('Password2').value;
  if(temp == '' || temp != document.getElementById('Password1').value) errors += set_error('Password2', ''); else errors += set_error('Password2', 'ok');
  }  
  if(type == 'all' && step==1 && errors==0) 
  {
      if(document.getElementById('help1_link_cont'))
      {
          window.location = '/join?e='+jQuery('#Email1').val()+'&p='+btoa(jQuery('#Password1').val())+'&u='+jQuery('#NickName').val();
      }
      else
      {
          jQuery('#step1_but').hide();
          jQuery('#step2').show();
          jQuery('#join_block2').show();
          jQuery('#step2_but').show();
      }
  }
  if(type == 'all' && step==2 && errors==0) 
  {
      jQuery('#step2_but').hide();
      jQuery('#step3').show();
      jQuery('#step3_but').show();
      jQuery('#join_block3').show();
      jQuery('#step_terms').show();
  }
  if(type == 'all' && step==3 && errors==0) document.big_reg_form.submit(); 
}


function set_error(name, msg)
{
    
 jQuery('#error_'+name).parents('td').find('.greentick').remove();   
 if(msg=='ok')
 {
     var left = '-27';
     if(name=='Email1' || name=='NickName' || name=='Password2') left = '5';
     if(name=='fname' || name=='lname') left = '205';
     if(name=='address') left = '487';
     if(name=='country') left = '167';
     if(name=='city') left = '167';
     if(name=='zip') left = '167';
     jQuery('#error_'+name).removeClass('active').after('<img class="greentick" src="/templates/default/n_img/greentick.png" style="position:relative;top:7px;left:'+left+'px;">');
     return 0;
 }
 else
 {
    jQuery('#error_'+name).addClass('active');
    if(msg != '') jQuery('#error_'+name+' div').html(msg);
    return 1;
 }
}


function show_lang_field(key, lg)
{
  for(var sid in lang_keys) 
  {  
  if(document.getElementById('lang_link_'+key+'_'+lang_keys[sid]))  
  document.getElementById('lang_link_'+key+'_'+lang_keys[sid]).style.color = '#333';
  if(document.getElementById('lang_field_'+key+'_'+lang_keys[sid]))
  document.getElementById('lang_field_'+key+'_'+lang_keys[sid]).style.display = 'none'; 
  }
  
  document.getElementById('lang_link_'+key+'_'+lg).style.color = '#f00';
  document.getElementById('lang_field_'+key+'_'+lg).style.display = 'block'; 
  
}


function add_case_item(id,type)
{
  document.getElementById('error_add_ship'+id).style.display = 'none';
  if((document.getElementById('place_service'+id).value=='' || document.getElementById('place_country'+id).value==0))
  {
  return false;
  }
  
  var nid = id+1;
  var current_plus = document.getElementById(type+'_plus_'+id);
  var next_div = document.getElementById(type+'_'+nid);
  var next_plus = document.getElementById(type+'_plus_'+nid);
  if(next_div)
  {
  document.getElementById('place_country_cont'+nid).innerHTML = str_replace("-nid-",nid,document.getElementById('country_list').innerHTML);
  next_plus.innerHTML = '<a href="#current" onclick="add_case_item('+nid+',\''+type+'\')"><img src="/templates/default/n_img/add_field.png"></a>';
  current_plus.innerHTML = '<img src="/templates/default/n_img/add_field_clear.png">';
  next_div.style.display = 'block';
  }
  
  var place_country = jQuery('#place_country'+id).val();
  var text = jQuery('#place_country'+id+' option:selected').text();
  jQuery('#place_country_cont'+id).html('<input type="hidden" name="place_country['+id+']" class="m_r_input_big" value="'+place_country+'"><input type="text" class="m_r_input_big" id="place_countryt'+id+'" value="'+text+'" style="width:192px;">');
  jQuery('#place_service'+id).attr("readonly", true);
  jQuery('#place_cost'+id).attr("readonly", true);
  jQuery('#place_add'+id).attr("readonly", true);
  jQuery('#place_service'+id).parent().css("padding-left", '1px');
  jQuery('#place_countryt'+id).attr("readonly", true);
  jQuery('#place_plus_'+id).html('<a href="#current" onclick="remove_service('+id+')"><img src="/templates/default/n_img/remove.png" /></a>');
  jQuery(".ship_table").each(function(ind,obj){ jQuery("#"+obj.id).attr("width","405px");  });
  
  jQuery('#shipping_countries').hide();
}

function remove_service(id)
{
  jQuery('#1row_cont'+id).remove();
  jQuery('#2row_cont'+id).remove();
  jQuery('#shipping_countries').hide();
}

function view_bid_history(id, type) {
  
 if(type == undefined) type = '';
 jQuery.ajax({
  type: "GET",
  url: _BASE_URL+"bid_history.php",
  data: "id="+id+'&type='+type,
  success: function(msg){
 show_popup_text  (msg, 650, 400);
 }
 });  
}

function remove_admin_listings(params) {
  
 jQuery.ajax({
  type: "GET",
  url: _BASE_URL+"deny.php",
  data: params,
  success: function(msg){
 eval(msg);
 }
 });  
}

function good_product(id) {
  
 jQuery.ajax({
  type: "GET",
  url: _BASE_URL+"ajax_good_bad.php",
  data: "id="+id+'&status=1',
  success: function(msg){
  eval(msg);
 }
 });  
}

function bad_product(id) {
  
 jQuery.ajax({
  type: "GET",
  url: _BASE_URL+"ajax_good_bad.php",
  data: "id="+id+'&status=2',
  success: function(msg){
  eval(msg);
 }
 });  
}

function good_bad_buzz(id, status) {
  
    if(jQuery('.vote'+id+' .left').css('cursor')!='pointer') return false;
 jQuery.ajax({
  type: "GET",
  url: _BASE_URL+"ajax_good_bad_buzz.php",
  data: "id="+id+'&status='+status,
  dataType: "json",
  success: function(msg){
    jQuery('.vote'+id).find('.left').css({'cursor':'auto'});
    jQuery('.vote'+id).find('.right').css({'cursor':'auto'});
    jQuery('.vote'+id).find('.center div').html(msg.perc+'%');
    jQuery('.vote'+id).find('.center span').html(msg.votes);
 }
 });  
}


function view_bid_history_details(id, auction_id,type) {
jQuery('.modal_bullet').show(); 
 jQuery.ajax({
  type: "GET",
  url: _BASE_URL+"bid_history.php",
  data: "id="+id+"&auction_id="+auction_id+'&type='+type,
  success: function(msg){
 jQuery('#fancy_div').html(msg);  
 }
 });  
}

function show_popup_text(text, width, height, obj) {
 if(width==undefined)  var width = 450;
 if(height==undefined)  var height = 300;
 if(obj==undefined)  var obj = jQuery('.logo a'); else obj = jQuery(obj);
 obj.fancybox({'content':text, 'width':width, 'height':height});
}

function change_fan_page(id)
{
    jQuery('.fan_pages').each(function(id, obj){
        jQuery(obj).html('Select this page');
    });
    jQuery('.fan_page'+id).html('<img style="margin-top:3px;" src="/templates/default/n_img/fbp_small.png">');
    jQuery.ajax({
      type: "GET",
      url: "/linktofan.php",
      data: "fbp="+id,
      success: function(msg){disablePopup();}
    }); 
}

function set_buynow_limit()
{
    jQuery.ajax({
      type: "GET",
      url: "/users.php",
      data: "limit="+jQuery('#buy_limit').val()+"&ids="+get_multi_deny(),
      success: function(msg){
          show_promt('Saved');
      }
    }); 
}

var bz_cats_ebay_import = '';
function show_popup_script(script,params, width, height, obj) {
  
  if(script == 'linktofan') jQuery('.fblink').html('<div style="position:absolute;"><img src="/templates/default/n_img/radar.gif"></div>');  
  if(width==undefined)  var width = 450;
  if(height==undefined)  var height = 300;
  if(obj==undefined)  var obj = jQuery('.logo a'); else obj = jQuery(obj);
 
  jQuery.ajax({
  type: script=='edit_products'?"POST":"GET",
  url: _BASE_URL+script+".php",
  data: params,
  success: function(msg){
      
  if(script == 'vacation' && strpos(msg, 'name="disable"')>0) 
  {
       height=120;
  }    
  if(script == 'ebay_listings')
  {
      var temp = explode('[||]', msg);
      bz_cats_ebay_import = temp[0];
      msg = temp[1];
  }
  if(script == 'users_featured')  msg = str_replace('id="ckeditor"','id="ckeditor'+ckeditor_counter+'"',msg);
  obj.fancybox({'content':msg, 'width':width, 'height':height}); 
  if(script == 'notes')
  {
      jQuery('#fancy_inner').css({'border':'0px', 'background':'none'});
      jQuery('#fancy_close').remove();
      jQuery('#fancy_bg').remove();
  }
  if(script == 'users_featured')
  {
      msg = str_replace('id="ckeditor"','id="ckeditor'+ckeditor_counter+'"',msg);
      init_ckeditor(ckeditor_counter, 1);
      ckeditor_counter++;
  }
  if(script == 'feedback_add')  init_star_rating();  
  if(script == 'services') 
  {
      change_additional_ship();
  }
  if(script == 'vacation') 
  {
       jQuery(":date").dateinput({format: 'mm-dd-yyyy'});
       jQuery(":date").data("dateinput").setValue();
  }
  if(script == 'preferences') 
  {
    jQuery("#list_user").autocomplete( 'ajax_countries.php', properties = { 
        matchContains: true,
        minChars: 0,
        selectFirst:    true, 
        intro_text: "Type Country", 
        no_result: 'No Countries',
        result_cont: 'result_list',
        user_list: 'user_list',
        classname: 'facelist'
    });     
    jQuery('#list_user').removeAttr("disabled"); 
  }
  if(script == 'network_filter_location') 
  {
      jQuery("#list_user").autocomplete( 'ajax_countries.php', properties = { 
        matchContains: true,
        minChars: 0,
        selectFirst:    true, 
        intro_text: "Type Country", 
        no_result: 'No Countries',
        result_cont: 'result_list',
        user_list: 'user_list',
        classname: 'facelist'
      });     
      jQuery('#list_user').removeAttr("disabled"); 
  }
  if(script == 'linktofan') jQuery('.fblink').html('<img src="/templates/default/n_img/fblink.png"> <a href="" onclick="show_popup_script(\'linktofan\',\'\',500,300);return false;">Link Fan Pages</a>');  
 }
 }); 
}

function init_uploader(id, folder, script, container, max, data_url)
{
    if(document.getElementById('uploadify'+id+'Uploader'))
    {
        jQuery('#uploadify'+id+'Uploader').show(1);
        return true;
    }
    jQuery("#uploadify"+id).uploadify({
        'uploader'       : '/uploadify.swf',
        'script'         : '/uploadify.php',
        'cancelImg'      : '/templates/default/n_img/cancel2.png',
        'folder'         : '/media/'+folder,
        'queueID'        : 'fileQueue'+id,
        'scriptAccess'   : 'always',
        'fileExt'        : '*.jpg;*.jpeg;*.gif;*.bmp;*.png;',
        'fileDesc'       : 'Only *.jpg;*.jpeg;*.gif;*.bmp;*.png;',
        'buttonText'     : 'Upload Image',
        'sizeLimit'      : 1000000 * max_image_size,
        'onComplete'     : function(event, queueID, fileObj, response, data){
            jQuery.ajax({
              type: "GET",
              url: _BASE_URL+script+".php",
              data: "new_file="+response+data_url,
              success: function(msg){jQuery('#'+container).html(msg); if(folder=='tmp') init_image_zoom();}
            });             
            eval('exist_photos'+id+'++')
            if( eval('exist_photos'+id) >= max ) 
            {
                jQuery('#uploadify'+id+'Uploader').hide(1);
                eval('exist_photos'+id+'= '+max) ;
            }
        },
        'auto'           : true,
        'multi'          : false
      });
}

var gi_upload_flag = 0;
function add_gi(url)
{
    if(exist_photos > 0 && exist_photos2 > 3) return false;
    if(gi_upload_flag > 0) return false;
    gi_upload_flag = 1;
    jQuery.ajax({
      type: "GET",
      url: _BASE_URL+"ajax_upload_googe_image.php",
      data: "url="+url,
      success: function(msg){ 
            var id = (exist_photos == 0?'':'2');
            jQuery.ajax({
              type: "GET",
              url: _BASE_URL+"ajax_upload_photo.php",
              data: "new_file="+msg+(exist_photos == 0?'&thumb=1':''),
              success: function(msg){jQuery('#photo_cont'+id).html(msg); init_image_zoom();}
            });      
            var max = (exist_photos == 0?1:4);
            eval('exist_photos'+id+'++')
            if( eval('exist_photos'+id) >= max ) 
            {
                jQuery('#uploadify'+id+'Uploader').hide(1);
                eval('exist_photos'+id+'= '+max) ;
            }
            gi_upload_flag = 0;
      }
    });
}  

function remove_profile_photo()
{
    jQuery.ajax({
      type: "GET",
      url: _BASE_URL+"ajax_upload_photo_profile.php",
      data: "delete=1",
      success: function(msg){ jQuery('#photo').val('');jQuery('#photo_cont').html('');jQuery('#uploadifyUploader').show(); }
    });
}

function init_profile_photo_uploader()
{
    jQuery("#uploadify").uploadify({
        'uploader'       : '/uploadify.swf',
        'script'         : '/uploadify.php',
        'cancelImg'      : '/templates/default/n_img/cancel2.png',
        'folder'         : '/media/tmp',
        'queueID'        : 'fileQueue',
        'scriptAccess'   : 'always',
        'fileExt'        : '*.jpg;*.jpeg;*.gif;*.bmp;*.png;',
        'fileDesc'       : 'Only *.jpg;*.jpeg;*.gif;*.bmp;*.png;',
        'buttonText'     : 'Upload Image',
        'sizeLimit'      : max_image_size,
        'onComplete'     : function(event, queueID, fileObj, response, data){
            jQuery.ajax({
              type: "GET",
              url: _BASE_URL+"ajax_upload_photo_profile.php",
              data: "new_file="+response,
              success: function(msg){jQuery('#photo').val(response);jQuery('#photo_cont').html(msg); init_image_zoom();}
            });             
            jQuery('#uploadifyUploader').hide();
        },
        'auto'           : true,
        'multi'          : false
      });
}

function delete_me_photo(id)
{
    jQuery.ajax({
      type: "GET",
      url: _BASE_URL+"ajax_get_about_me_photos.php",
      data: "delete_id="+id,
      success: function(msg){exist_photos2--;init_uploader('2', 'about_me', 'ajax_get_about_me_photos', 'about_me_photos', 18, '');jQuery('#about_me_photos').html(msg); }
    });
}

function verify_bonanza()
{
    jQuery.ajax({
      type: "GET",
      url: _BASE_URL+"ajax_verify_bonanza.php",
      data: "",
      success: function(msg){
          if(msg!='')
          {
              show_popup_text  (msg, 450, 200);
          }
          else
          {
              show_promt("You have successfully detached your Bonanza account");
              disablePopup();
          }
     }
   });
}

function verify_ebay()
{
    jQuery.ajax({
      type: "GET",
      url: _BASE_URL+"ajax_verify_ebay.php",
      data: "",
      success: function(msg){
          if(msg!='')
          {
              show_popup_text  (msg, 450, 200);
          }
          else
          {
              show_promt("You have successfully detached your eBay account");
              jQuery('#ebay_feedbacks_cont').remove();
              jQuery('#ebay_link a').remove();
              disablePopup();
          }
     }
   });
}

function verify_email(ignore_prompt)
{
    if(ignore_prompt==undefined && document.getElementById('college_link') && jQuery('#college_link a').html().substr(0,7)=='Disable')
    {
        show_popup_text  (jQuery('#univer_confirm').html(), 450, 200);
        return false;
    }
    disablePopup();
    jQuery.ajax({
      type: "GET",
      url: _BASE_URL+"ajax_verify_email.php",
      data: "",
      success: function(msg){
          if(msg!='')
          {
            show_popup_text  (msg, 450, 400);
          }
          else
          {
              jQuery('#college_link a').html('Want to gain access to trade within Universities and Colleges?');
          }
     }
   });
}

function get_colleges(country)
{
    jQuery.ajax({
      type: "GET",
      url: _BASE_URL+"ajax_get_colleges.php",
      data: "country="+country,
      success: function(msg){
      jQuery('#colleges_cont').html(msg);
     }
   });
}

function get_email_postfix(college)
{
    jQuery.ajax({
      type: "GET",
      url: _BASE_URL+"ajax_get_college_email.php",
      data: "college="+college,
      success: function(msg){
      jQuery('#email_post_cont').html(msg);
     }
   });
}

function change_category(id, univer, val, ind)
{
    if(id==4)
    {
        jQuery('#isbn').parents('tr').show();
        jQuery('#mpn').parents('tr').parents('tr').hide();
    }
    else
    {
        jQuery('#isbn').parents('tr').hide();
        jQuery('#mpn').parents('tr').parents('tr').show();
    }
    if(id==31 && univer==0)
    {
        show_popup_text('In order to buy and sell in this category you need to <a href="javascript: void(0);" onclick="verify_email()">verify your university email</a>', 450, 70);
    }
    if(document.getElementById('subcategories_container') || document.getElementById('subcategories_container2'))
    {
  jQuery.ajax({
  type: "GET",
  url: _BASE_URL+"ajax_subcategories.php",
  data: "id="+id,
  success: function(msg){

  document.getElementById('subcategories_container'+(ind!=undefined?'2':'')).innerHTML=msg; 
  if(val != undefined) set_select_value('subcategory_id', val);
 }
 });
    }
}

function show_categ3(val, val3)
{
    if(val>0)
        jQuery('#categ3_cont').show();
    else 
        jQuery('#categ3_cont').hide();
        
    if(val > 0)
    {
         jQuery.ajax({
          type: "GET",
          url: _BASE_URL+"ajax_subcategories3.php",
          data: "val="+val,
          success: function(msg){
              jQuery('#categ3').html(msg);
              if(val3 != undefined)
                set_select_value('categ3',val3);
         }
         });
    }
}

function add_categ3()
{
    if(jQuery('#categ3_new').css('display') == 'none')
    {
        jQuery('#categ3').css({'width':250});
        jQuery('#categ3_new').show();
    }
    else
    {
        if(jQuery('#categ3_new').val()!='')
        {
            show_popup_text('<b>Add third category?</b><br><br><div style="float: left;padding-right:5px;"><div class="tabletitle_white"><a href="javascript: void(0);" onclick="add_categ3_go()" class="button">Yes</a></div></div><div style="float: left;"><div class="tabletitle_white"><a href="javascript: void(0);" onclick="disablePopup();" class="button">No</a></div></div>', 300, 150);
              
        }
    }
}

function add_categ3_go()
{
    jQuery.ajax({
      type: "GET",
      url: _BASE_URL+"ajax_subcategories3.php",
      data: "val="+jQuery('#subcategory_id').val()+'&title='+jQuery('#categ3_new').val(),
      success: function(msg){
          jQuery('#categ3').html(msg);
          jQuery('#categ3_cont img').remove();
          jQuery('#categ3_new').remove();
          jQuery('#categ3').css({'width':607});
          disablePopup();
     }
   });
}



function remove_photo(id)
{
  jQuery.ajax({
  type: "GET",
  url: _BASE_URL+"ajax_remove_photo.php",
  data: "id="+id,
  success: function(msg){
  document.getElementById('photo'+id+'_cont').innerHTML=msg; 
 }
 });
}

function show_message_full(id)
{
  if(-[1,]) jQuery('#message'+id).fadeTo("fast", 0.1);
  document.getElementById('show_tab'+id).className='active'; 
  document.getElementById('show_tab'+id).innerHTML='<a href="#current" onclick="show_message_small('+id+')">Collapse</a>';
  document.getElementById('message'+id).innerHTML='<br><br><center><img src="/templates/default/n_img/wait.gif"></center><br><br>'; 
  jQuery.ajax({
  type: "GET",
  url: _BASE_URL+"message_show_full.php",
  data: "groupID="+id,
  success: function(msg){
  document.getElementById('message'+id).innerHTML=msg;  
  if(-[1,]) jQuery('#message'+id).fadeTo("slow", 1);  
 }
 });
}

function show_message_small(id)
{
  if(-[1,]) jQuery('#message'+id).fadeTo("fast", 0.1);
  document.getElementById('show_tab'+id).className=''; 
  document.getElementById('show_tab'+id).innerHTML='<a href="#current" onclick="show_message_full('+id+')">Show all</a>'; 
  document.getElementById('message'+id).innerHTML='<br><br><center><img src="/templates/default/n_img/wait.gif"></center><br><br>'; 
  jQuery.ajax({
  type: "GET",
  url: _BASE_URL+"message_show_small.php",
  data: "groupID="+id,
  success: function(msg){
  document.getElementById('message'+id).innerHTML=msg;  
  if(-[1,]) jQuery('#message'+id).fadeTo("slow", 1);  
 }
 });
}

function remove_message(id)
{
  jQuery('#top_menu_message'+id).hide("slow");
  jQuery('#message'+id).hide("slow");
  jQuery.ajax({
  type: "GET",
  url: _BASE_URL+"inbox.php",
  data: "deleteGroup="+id,
  success: function(msg){  
 }
 });
}

function change_video(id)
{
  jQuery.ajax({
  type: "GET",
  url: _BASE_URL+"ajax_change_video.php",
  data: "id="+id,
  success: function(msg){
  document.getElementById('video_container').innerHTML=msg; 
 }
 });
}

function remove_video(id)
{
  jQuery.ajax({
  type: "GET",
  url: _BASE_URL+"ajax_remove_video.php",
  data: "id="+id,
  success: function(msg){
  document.getElementById('video'+id+'_cont').innerHTML=msg; 
  document.getElementById('swfupload-control').style.display='block';
 }
 });
}

function remove_uploaded_photo(id)
{
    if(id=='thumb')
        var ind = '';
    else
        var ind = '2';
  jQuery.ajax({
  type: "GET",
  url: _BASE_URL+"ajax_upload_photo.php",
  data: "delete_id="+id,
  success: function(msg){
  eval('exist_photos'+ind+'--;');init_uploader(ind, 'tmp', 'ajax_upload_photo', 'photo_cont'+ind, id=='thumb' ? 1 : 4, '&'+id+'=1');jQuery('#photo_cont'+ind).html(msg);  init_image_zoom();
 }
 });
}

function init_image_zoom()
{
    jQuery("ul.thumb li").hover(function() {
        jQuery(this).css({'z-index' : '10'});
        jQuery(this).find('img').addClass("hover").stop()
            .animate({
                marginTop: '-110px', 
                marginLeft: '-110px', 
                top: '50%', 
                left: '50%', 
                width: '174px', 
                height: '174px',
                padding: '20px' 
            }, 200);
        
        } , function() {
        jQuery(this).css({'z-index' : '0'});
        jQuery(this).find('img').removeClass("hover").stop()
            .animate({
                marginTop: '0', 
                marginLeft: '0',
                top: '0', 
                left: '0', 
                width: '100px', 
                height: '100px', 
                padding: '5px'
            }, 400);
    });
}

function change_banner_control(id)
{
  for(var i=1;i<=50;i++)
  {
  if(!document.getElementById('banner_control'+i)) break;
  document.getElementById('banner_control'+i).className='';
  }
  document.getElementById('banner_control'+id).className='active';
}

function change_step(id)
{  
  document.getElementById('d_step1').style.display='none';
  document.getElementById('d_step2').style.display='none';
  document.getElementById('d_step3').style.display='none';
  document.getElementById('d_step4').style.display='none';
  document.getElementById('d_step5').style.display='none';
  document.getElementById('d_step'+id).style.display='block';
}

function go_step(id)
{
  save_product('sell', id);
}

function upload_photo(id)
{
  
  if(id>0)
  {
  var id1 = "#photo"+id+'_cont input';
  var id4 = "photo"+id;
  var id2 = "#error_photo"+id;
  }
  else
  {
  var id1 = "#thumb_cont input";
  var id4 = "thumb";
  var id2 = "#error_thumb";
  }
  jQuery(id2).css({"display": "none"});
  var ext = (/[.]/.exec(jQuery(id1).val())) ? /[^.]+$/.exec(jQuery(id1).val()) : '';
  ext = (ext+'').toLowerCase();
  if(ext=='jpg' || ext=='jpeg' || ext=='gif' || ext=='png' || ext=='bmp')
  {  
  jQuery(id1).css({"display": "none"});
  //jQuery(id2).html('<img src="/templates/default/n_img/radar.gif">');
  
  jQuery.ajaxUpload({
 url:_BASE_URL+'ajax_upload_photo.php?phid='+id,
 secureuri:false,
 uploadform: document.big_form,
 dataType: 'html',  
 success: function (response, status){
  
 var pos = strpos(response,' = ');
 if(response.substr(0, 7)=='ierror_') 
 {
  jQuery(id1).css({"display": "block"});
  jQuery(id2).css({"display": "block"});
 }

 document.getElementById(response.substr(0, pos)).innerHTML = response.substr(pos+2);
 if(response.substr(0, 7)!='ierror_' && id>0 && document.getElementById('photo'+(id+1)+'_cont')) 
  document.getElementById('photo'+(id+1)+'_cont').style.display='block';
 
  },
  error: function (data, status, e)
  {
  //alert('+'+e);
  } 
 }); 
  }
  else
  {
  document.getElementById(id4).setAttribute('type', 'input');
  document.getElementById(id4).setAttribute('type', 'file');
  jQuery(id2+' div').html('Incorrect file type. Select jpg, png, bmp or gif');
  jQuery(id2).css({"display": "block"});
  }
}

var over_popup = false;
var close_popup_timer = false;
function show_trackbar()
{
  over_popup = true;
  jQuery('#trackbar_container').show('slow');
}

function hide_trackbar()
{
  over_popup = false;
  close_popup_timer = setTimeout('if(!over_popup) {jQuery(\'#trackbar_container\').hide(\'slow\');}', 500);
}

function preview_product()
{
    jQuery('.s_u_error_1').each(function(ind,obj){obj.style.display='none';  });
    jQuery('.s_u_error_3_desc').css('display','none');
  jQuery.ajaxUpload({
 url:_BASE_URL+'preview.php',
 secureuri:false,
 uploadform: document.big_form,
 dataType: 'html',  
 success: function (response, status){

 if(response.substr(0,6)!='error=')
 {
     jQuery('#preview_cont').html(response);
     change_step(5);
 }
 else
 {
 eval(response.substr(6));
 window.location="#sell";
 } 
  },
  error: function (data, status, e)
  {
  //alert('+'+e);
  } 
 }); 
}

function sell_error(field, error)
{
    jQuery('#error_'+field).css('display','block');
    jQuery('#error_'+field+' div').html(error);
}

function save_product(action, step)
{
    jQuery('.s_u_error_1').each(function(ind,obj){obj.style.display='none';  });
    jQuery('.s_u_error_3_desc').css('display','none');
  if(step==undefined) step = '';
  jQuery.ajaxUpload({
 url:_BASE_URL+action+'.php?step='+step,
 secureuri:false,
 uploadform: document.big_form,
 dataType: 'html',  
 success: function (response, status){
     eval(response);
     window.location="#sell";
  },
  error: function (data, status, e)
  {
  //alert('+'+e);
  } 
 }); 
}

function edit_products()
{
    jQuery('.s_u_error_1').each(function(ind,obj){obj.style.display='none';  });
  jQuery.ajaxUpload({
 url:_BASE_URL+'edit_products.php',
 secureuri:false,
 uploadform: document.big_form,
 dataType: 'html',  
 success: function (response, status){
     eval(response);
  },
  error: function (data, status, e)
  {
  //alert('+'+e);
  } 
 }); 
}

function init_video_upload(size)
{
    jQuery(function(){
        jQuery('#swfupload-control').swfupload({
            upload_url: "/upload-file.php",
            file_post_name: 'uploadfile',
            file_size_limit : size,
            file_types : "*.flv;*.avi;*.mpg;*.mpeg",
            file_types_description : "Video files",
            file_upload_limit : 1,
            flash_url : "/include_js/swfupload/swfupload.swf",
            button_image_url : '/include_js/swfupload/wdp_buttons_upload_114x29.png',
            button_width : 114,
            button_height : 29,
            button_placeholder : jQuery('#button')[0],
            debug: false
        })
            .bind('fileQueued', function(event, file){
                if(!document.getElementById(file.id))
                {
                    var listitem='<li id="'+file.id+'" >'+
                        'File: <em>'+file.name+'</em> ('+Math.round(file.size/1024)+' KB) <span class="progressvalue" ></span>'+
                        '<div class="progressbar" ><div class="progress" ></div></div>'+
                        '<p class="ustatus" >Pending</p>'+
                        '<span class="cancel" >&nbsp;</span>'+
                        '</li>';
                    jQuery('#log').append(listitem);
                    jQuery('li#'+file.id+' .cancel').bind('click', function(){
                        var swfu = jQuery.swfupload.getInstance('#swfupload-control');
                        swfu.cancelUpload(file.id);
                        jQuery('li#'+file.id).slideUp('fast');
                    });
                    // start the upload since it's queued
                    jQuery(this).swfupload('startUpload');
                }
            })
            .bind('fileQueueError', function(event, file, errorCode, message){
                alert('Size of the file '+file.name+' is greater than limit');
            })
            .bind('fileDialogComplete', function(event, numFilesSelected, numFilesQueued){
                jQuery('#queuestatus').text('Files Selected: '+numFilesSelected+' / Queued Files: '+numFilesQueued);
            })
            .bind('uploadStart', function(event, file){
                jQuery('#log li#'+file.id).find('p.ustatus').text('Uploading...');
                jQuery('#log li#'+file.id).find('span.progressvalue').text('0%');
                jQuery('#log li#'+file.id).find('span.cancel').hide();
            })
            .bind('uploadProgress', function(event, file, bytesLoaded){
                //Show Progress
                var percentage=Math.round((bytesLoaded/file.size)*100);
                jQuery('#log li#'+file.id).find('div.progress').css('width', percentage+'%');
                jQuery('#log li#'+file.id).find('span.progressvalue').text(percentage+'%');
            })
            .bind('uploadSuccess', function(event, file, serverData){

                var index = 0;
                if(document.getElementById('SWFUpload_1')) index = 1;
                if(serverData.substr(0,6)!='error=')
                {
                    var obj = document.getElementById('video_id');
                    obj.value += ';'+serverData+';';
                    var item=jQuery('#log li#'+file.id);
                    item.find('div.progress').css('width', '100%');
                    item.find('span.progressvalue').text('100%');
                    document.getElementById('SWFUpload_'+index).style.display='none';
                    item.addClass('success').find('p.ustatus').html('<div style="position:relative;top:-0px;left:0px;"><nobr>Done!!! &nbsp;&nbsp;&nbsp; <a href="javascript: void(0);" onclick="document.getElementById(\'video_id\').value=str_replace(\';'+serverData+';\',\'\',document.getElementById(\'video_id\').value);jQuery(\'#'+file.id+'\').remove();init_video_upload();document.getElementById(\'SWFUpload_'+index+'\').style.display=\'block\';">Remove</a></nobr></div>');
                }
                else
                {
                    jQuery('#'+file.id).remove();
                    init_video_upload();
                    document.getElementById('SWFUpload_'+index).style.display='block';
                    alert(serverData.substr(6));
                }
            })
            .bind('uploadComplete', function(event, file){
                // upload has completed, try the next one in the queue
                jQuery(this).swfupload('startUpload');
            })


    });    
}

function recycle_listing(id)
{
    jQuery.ajax({
          type: "GET",
          url: _BASE_URL+"ajax_recycle_step1.php",
          data: "id="+id,
          success: function(msg){
          eval(msg);
         }
    });
    jQuery.ajax({
          type: "GET",
          url: _BASE_URL+"ajax_recycle_step1_desc.php",
          data: "id="+id,
          success: function(msg){
          CKEDITOR.instances.ckeditor.setData(msg);
         }
    });
    jQuery.ajax({
          type: "GET",
          url: _BASE_URL+"ajax_recycle_steps234.php",
          data: "id="+id,
          success: function(msg){
          jQuery('#recycle_content').html(msg);
          change_quantity();
          change_additional_ship();
          jQuery('#shipping_countries').hide();
          init_image_zoom();
          google.load('search', '1');
          var imageSearch;
         }
    });
    disablePopup();
}

function autoimport_ebay_go()
{
    var ids = '';
    jQuery('.ebay_checkbox').each(function(id, obj){ if(obj.checked) ids += obj.value+',';});
    jQuery('#fancy_div').html('<center><br><b>Please wait...</b></center>');  
    jQuery.ajax({
          type: "POST",
          url: _BASE_URL+"import_from_ebay_go.php",
          data: "ids="+ids,
          success: function(msg){
            disablePopup();
            show_promt("Processing eBay listings. You will be notified when they are live.", 25, 6000);
         }
    });
}

function ebay_list_counter(time)
{
    jQuery('#ebay_list_counter').html(time-1);
    if(time > 1) 
        setTimeout('ebay_list_counter('+(time-1)+');', 1000);
    else
        disablePopup();
}

function set_select_value(name, val)
{
    var oListbox = document.getElementById(name);
    if(!oListbox) return false;
    oListbox.value = val;
    for (var i=0; i < oListbox.options.length; i++)
    {
        if (oListbox.options[i].value==val) 
            oListbox.options[i].selected = true;
        else
            oListbox.options[i].selected = false;
    }
}

function refresh_my_activity(url)
{
    if(document.getElementById('QUERY_STRING'))
    {
        profile_show_content(document.getElementById('QUERY_STRING').value, document.getElementById('QUERY_SCRIPT').value, 'my_activity_cont');
        jQuery.ajax({
          type: "GET",
          url: _BASE_URL+"activity.php",
          data: "onlystat=1",
          success: function(msg){
          eval(msg);
         }
         });
    }
    else if(typeof url != 'undefined')
    {
        window.location = url;
    }
}

var act_search_timer = null;
function search_by_activity(keyword)
{
    clearTimeout(act_search_timer);
    act_search_timer = setTimeout(function(){search_by_activity_go(keyword)}, 500);
}

function search_by_activity_go(keyword)
{
    var params = document.getElementById('QUERY_STRING').value;
    params = str_replace('keywords=','',params)+'&keywords='+keyword;
    profile_show_content(params, document.getElementById('QUERY_SCRIPT').value, 'my_activity_cont');
}

function change_who_ship(action)
{
    
    if(action==0)
        jQuery("#shipping_methods").hide(1);
    else
        jQuery("#shipping_methods").show(1);
        
    if(action==2)
        jQuery("#serv_descr_title").html('Description');
    else
        jQuery("#serv_descr_title").html('Service');
  //jQuery(".ship_price_fields1").each(function(ind,obj){ if(action==2) obj.style.display='none'; else obj.style.display='table-cell';  });
  jQuery(".ship_price_fields2").each(function(ind,obj){ if(action==2) obj.style.display='none'; else obj.style.display='table-cell';  });


  if(action == 2)
  jQuery(".ship_table").each(function(ind,obj){  jQuery("#"+obj.id).attr("width","240px");  });
  else
  jQuery(".ship_table").each(function(ind,obj){ jQuery("#"+obj.id).attr("width","405px");  });
  change_additional_ship();
  
  jQuery('#shipping_countries').hide();
}

function click_worldwide(obj)
{
  if(obj.checked)
  jQuery('#no_worldwide').css("display","none");
  else
  jQuery('#no_worldwide').css("display","block");
}

function place_offer()
{
    jQuery.ajax({
      type: "GET",
      url: _BASE_URL+"place_offer.php",
      data: "id="+document.getElementById('product_id[TEMP]').value+'&offer='+document.getElementById('offer').value+'&quantity='+document.getElementById('offer_quantity').value,
      success: function(msg){
          eval(msg);
          if(document.getElementById('offer')) document.getElementById('offer').value='';  
     }
     });
}

function accept_offer(id)
{
    jQuery.ajax({
      type: "GET",
      url: _BASE_URL+"offers.php",
      data: "accept&id="+id,
      success: function(msg){
          jQuery('#offer'+id+' td:last').html('<span style="color:#0a0;">Accepted</span>');
          if(document.getElementById('my_listings_all'))
          { 
            disablePopup();
            refresh_my_activity();
          }
          else
            window.location.reload();
     }
     });
}

function decline_offer(id)
{
    jQuery.ajax({
      type: "GET",
      url: _BASE_URL+"offers.php",
      data: "decline&id="+id,
      success: function(msg){
          jQuery('#offer'+id+' td:last').html('<span style="color:#f00;">Declined</span>');
     }
     });
}

function place_bid()
{
  jQuery.ajaxUpload({
 url:_BASE_URL+'place_bid.php',
 secureuri:false,
 uploadform: document.bid_form,
 dataType: 'html',  
 success: function (response, status){  
 
 if(response.substr(0,6)!='error=')
 {
      show_promt(response, 25, 7000);
 }
 else
 {
 //show_popup_text('<span class="error">'+response.substr(6)+'</span>', 450, 100);
 show_error_promt(response.substr(6), 43, 7000);
 } 
 jQuery.ajax({
      type: "GET",
      url: _BASE_URL+"ajax_update_auction_main.php",
      data: "id="+product[0],
      success: function(msg){
      eval(msg);
      if(document.getElementById('bid')) document.getElementById('bid').value='';  
     }
     });
  },
  error: function (data, status, e)
  {
  //alert('+'+e);
  } 
 }); 
}



function place_bid_confirm(auto, small, id)
{
  var text = document.getElementById('place_bid_confirm' + (id!=undefined?id:'')).innerHTML;
  text = str_replace("[TEMP]",'',text);
  if(document.getElementById('orig_price')) 
    text = str_replace("[CURRENT_PRICE]",document.getElementById('orig_price').innerHTML,text);
  if(document.getElementById('orig_min')) 
    text = str_replace("[MIN_BID]",document.getElementById('orig_min').innerHTML,text);
  //if(typeof this.window['convert_bid_to_currency'] == 'function') text = str_replace("[MY_BID_PRICE]",convert_bid_to_currency(document.getElementById('bid').value),text);
    show_popup_text(text ,450,400);
    jQuery('#on_off').iphoneStyle();
    bubbleInfoInit();
}

function offers_confirm()
{
  var text = document.getElementById('offers_confirm').innerHTML;
  text = str_replace("[TEMP]",'',text);
  show_popup_text(text ,450,400);
}

function buy_now_confirm(small)
{
    show_popup_text(document.getElementById('buy_now_confirm').innerHTML, 450, 300);
  
}

function show_feedback_form(id)
{
  if(jQuery("#feedback_comment_form"+id).css('display')=='none')
  jQuery("#feedback_comment_form"+id).css({'display':'block'});
  else
  jQuery("#feedback_comment_form"+id).css({'display':'none'});
}

function submit_ajax_form(value,type,container)
{ 
  jQuery.ajaxUpload({
 url:_BASE_URL+type+'.php',
 secureuri:false,
 uploadform: value,
 dataType: 'html',  
 success: function (response, status){ 
 if(response.substr(0,6)!='error=')
 {
 if(container==undefined)
 {
  response = str_replace("amp;","",response);
  eval(response); 
 }
 else
 {
  disablePopup();
  if(container=='about_me')
  {
  window.location = '/profile';
  }
  document.getElementById(container).innerHTML = response;
 }
 }  
 else
 document.getElementById('form_error').innerHTML= response.substr(6);
  },
  error: function (data, status, e)
  {
  if(e=='TypeError: i.contentWindow is null') 
  add_post();
  //else
  //alert('+'+e);  
  } 
 }); 
}


  



var timers = new Array();
var timer_time = false;
var last_item_timer = false;
var last_buzz_timer = false;
var current_params = '';
var current_type = '';
var current_container = '';
var max_last_items = 0;
var max_home_buzz = 0;
  
function profile_show_content(params, type, id, wait_container, concat)
{
  if(typeof(concat) == 'undefined') var concat = 0;  
  if(typeof(last_hash_load) !== 'undefined' && last_hash_load == type+id)  
  {
      last_hash_load = '';
      return true;
  }
  if(id=='main_listing')
  {
  timers = new Array();
  clearTimeout(timer_time);
  }  
  
  if(wait_container == undefined) var wait_container = 'wait_container';
  // Show wait animation
  var content = document.getElementById(id);
  if(-[1,]) jQuery("#"+id).fadeTo("fast", 0.33);
  var wait = document.getElementById(wait_container);
  if(wait) wait.innerHTML='<img src="/templates/default/n_img/wait.gif">';
  jQuery.ajax({
  type: "GET",
  url: _BASE_URL+type+".php",
  data: params,
  success: function(msg){  
 
  var js_start = strpos(msg,'<SCRIPT>/*');
  var js_end = strpos(msg,'*/</SCRIPT>');
  if(js_start==undefined || js_start==0)
  {
  var js_start = strpos(msg,'<script>/*');
  var js_end = strpos(msg,'*/</script>');
  }  
  if(js_start<js_end)
  {
  var js = msg.substr(js_start+10,js_end-js_start-10);
  msg = msg.substr(0,js_start)+msg.substr(js_end+11);
  eval(js);
  }  
  if(concat == 0) 
      content.innerHTML=msg;
  else if(concat == 1)
  {
      jQuery('#more_buzz').remove();
      content.innerHTML+=msg;
  }
  else if(concat == 2)
  {
      jQuery('#most_recent_buzz').remove();
      jQuery('#new_buzzs').html('');
      content.innerHTML=msg+content.innerHTML;
  }
  if(id=='main_listing' || id=='my_activity_cont')  
  {
      current_params = params;
      current_type = type;
      current_container = id;  
      timers = new Array();
      jQuery(".timer_container").each(function(ind,obj){eval(obj.innerHTML)});
      timer_calc();
  }
  if(type=='wall')  
  {
      if(document.getElementById('write_timer')) go_wall_timer(document.getElementById('write_timer').innerHTML);
  }  
  if(type=='index_listings')
  {
     
  }
  if(id=='main_listing')
  {
      title_from_breadcrumb();
  } 
  if(type=='index_announcements' && document.getElementById('tab_ann')) change_tab_home('tab_ann');
  if((type=='forum_categories' || type=='forum_topics') && document.getElementById('tab_forum')) change_tab_home('tab_forum');
  if(type=='index_listings' && document.getElementById('tab_listings')) change_tab_home('tab_listings');
  if(wait) wait.innerHTML=''; 
  if(-[1,]) jQuery("#"+id).fadeTo("fast", 1); 
 }
 });
 
}

function implode( glue, pieces ) { 
    return ( ( pieces instanceof Array ) ? pieces.join ( glue ) : pieces );
}


function title_from_breadcrumb()
{
    var bread = [];
    jQuery('#breadcrumb span a').each(function(id,obj){
        bread.push(jQuery(obj).html())
    });
    if(bread.length == 0 && jQuery('#breadcrumb span').html().substr(0,11) == 'Search for ')
        bread.push(jQuery('#breadcrumb span').html());
    bread.reverse();
    if(bread.length > 0)
        document.title = implode(' | ', bread) + ' | Buzzmart';
    else
        document.title = 'Search - Bid or buy now on a variety of Buzzmart bargains';
}

var start_photo_changing = 16;
function change_last_items()
{
    if(!document.getElementById('last_item0'))
    {
        clearTimeout(last_item_timer);
        return true;
    }
    if(-[1,]) jQuery("#hot").fadeTo("fast", 0); 
    for(var i=0;i<max_last_items;i++)
        document.getElementById('last_item'+i).style.display='none';
    var counter = 0;    
    while(counter<16)
    {
        counter++;
        document.getElementById('last_item'+start_photo_changing).style.display='block';
        start_photo_changing++;
        if(start_photo_changing>max_last_items-1) start_photo_changing = 0;
    }
    
    if(-[1,]) jQuery("#hot").fadeTo("slow", 1); 
    last_item_timer = setTimeout("change_last_items()", 8000);
}

function update_auction(id)
{
  jQuery.ajax({
  type: "GET",
  url: _BASE_URL+"ajax_update_auction_main.php",
  data: "id="+id,
  success: function(msg){
  eval(msg);  
 }
 });
}

function product_timer_calc()
{  
  product[1] = product[1] - 1;
  if(product[1]<86400 && product[1]>=86390 && product[3]==2) document.getElementById('timer'+product[0]).style.color='#ff0000';
  if(product[1]<=0)
  {
  clearTimeout(timer_time);
  window.location.reload();
  return false;
  }
  if(document.getElementById('timer'+product[0]).innerHTML != 'Forever') document.getElementById('timer'+product[0]).innerHTML = timeBetween(product[1]);
  if((product[3]==2 && ((product[1]>300 && product[2]-product[1]>15) || (product[1]>90 && product[1]<=300 && product[2]-product[1]>5) || (product[1]<=90 && product[2]-product[1]>2))) || (product[3]==1 && ((product[1]>60 && product[2]-product[1]>30) || (product[1]<=60 && product[2]-product[1]>5))))
  {
 update_auction(product[0]);
  }
  timer_time = setTimeout("product_timer_calc()",1000);
}

function timer_calc()
{  
  var for_update = new Array();
  var for_update_id = new Array();
  for(var timer in timers)
  {  
  if(typeof(timers[timer])!='object'||!(timers[timer] instanceof Array)) continue;  
  if(!document.getElementById('timer'+timers[timer][0]))
  {
  continue;
  }
  timers[timer][1] = timers[timer][1] - 1;
  if(timers[timer][1]<86400 && timers[timer][1]>=86390 && timers[timer][3]==2) document.getElementById('timer'+timers[timer][0]).style.color='#ff0000';
  if(timers[timer][1]<=0)
  {
  timers = new Array();
  clearTimeout(timer_time);
  profile_show_content(current_params, current_type, current_container);
  return false;
  }
  
  if(document.getElementById('timer'+timers[timer][0]).innerHTML!='Forever') document.getElementById('timer'+timers[timer][0]).innerHTML = timeBetween(timers[timer][1]);
  if ((timers[timer][3]==2 && ((timers[timer][1]>300 && timers[timer][2]-timers[timer][1]>20) || (timers[timer][1]>90 && timers[timer][1]<=300 && timers[timer][2]-timers[timer][1]>10) || (timers[timer][1]<=90 && timers[timer][2]-timers[timer][1]>3))) || (timers[timer][3]==1 && ((timers[timer][1]>60 && timers[timer][2]-timers[timer][1]>30) || (timers[timer][1]<=60 && timers[timer][2]-timers[timer][1]>5)))) 
  {
 for_update[for_update.length] = timers[timer][0]; 
 for_update_id[for_update_id.length] = timer;

  }
  }  
  if(for_update.length>0)
  {
     jQuery.ajax({
      type: "POST",
      url: _BASE_URL+"ajax_update_auction.php",
      data: "for_update="+for_update+"&for_update_id="+for_update_id+"&current_container="+current_container,
      success: function(msg){
        eval(msg);  
        timer_time = setTimeout("timer_calc()",1000);
     }
     });
  }
  else
    timer_time = setTimeout("timer_calc()",1000);
}

function change_additional_ship()
{
  if(document.getElementById('quantity').value>1)
  jQuery(".row_additional_ship").each(function(ind,obj){obj.style.display='table-row';  });
  else
  jQuery(".row_additional_ship").each(function(ind,obj){obj.style.display='none';  });
}

function timeBetween(diff)
{ 
  if(diff<60) return (diff)+' '+_LANGS_key383;
  
  var hours = 0;  
  var minutes = 0;  
  var days = 0;  

  if(diff % 86400 <= 0){days = diff / 86400;}  // 86,400 seconds in a day  
  if(diff % 86400 > 0)  
  {  
  var rest = (diff % 86400);  
  days = (diff - rest) / 86400;  
  if(rest % 3600 > 0)  
  {  
  var rest1 = (rest % 3600);  
  hours = (rest - rest1) / 3600;  
  if(rest1 % 60 > 0)  
  {  
  var rest2 = (rest1 % 60);  
  minutes = (rest1 - rest2) / 60;  
  }  
  else{minutes = rest1 / 60;}  
  }  
  else{hours = rest / 3600;}  
  }  

  if(days > 0){days = days+' '+_LANGS_key280+' ';}  
  else{days = '';}  
  if(hours > 0){hours = hours+' '+_LANGS_key281+' ';}  
  else{hours = '';}  
  if(minutes > 0){minutes = minutes+' '+_LANGS_key282+' ';}  
  else{minutes = '';} 
  
  if(!days) return hours+minutes+' '; 
  else  return days+hours;  
 
}

function change_tab_home(id)
{
  document.getElementById('tab_forum').className='';
  document.getElementById('tab_listings').className='';
  document.getElementById('tab_ann').className='';
  document.getElementById(id).className='active';
}

function change_tab_product(id)
{
  document.getElementById('tab_desc').style.display='none';
  document.getElementById('tab_shipping').style.display='none';
  document.getElementById('tab_videos').style.display='none';
  jQuery('#tab_return').hide();
  document.getElementById(id).style.display='block';
  
  document.getElementById('tab_desc_sw').className='';
  jQuery('#tab_return_sw').removeClass('active');
  if(document.getElementById('tab_shipping_sw')) document.getElementById('tab_shipping_sw').className='';
  if(document.getElementById('tab_videos_sw')) document.getElementById('tab_videos_sw').className='';
  document.getElementById(id+'_sw').className='active';
  
}

function change_tab_profile(id)
{
  document.getElementById('network').style.display='none';
  document.getElementById('forsale').style.display='none';
  document.getElementById('exp').style.display='none';
  document.getElementById(id).style.display='block';
  
  if(document.getElementById('network_sw')) document.getElementById('network_sw').className='';
  if(document.getElementById('forsale_sw')) document.getElementById('forsale_sw').className='';
  if(document.getElementById('exp_sw')) document.getElementById('exp_sw').className='';
  document.getElementById(id+'_sw').className='active';
}

function detectIE6(){
  var browser = navigator.appName;
  if (browser == "Microsoft Internet Explorer"){
  var b_version = navigator.appVersion;
  var re = /\MSIE\s+(\d\.\d\b)/;
  var res = b_version.match(re);
  if (res[1] <= 6){
  return true;
  }
  }
  return false;
}

function add_to_friends(user,type,remove)
{ 
  jQuery.ajax({
  type: "GET",
  url: _BASE_URL+"add_to_friends.php",
  data: 'user='+user+'&type='+type,
  success: function(msg){
  //if(msg!='')
  if(remove==undefined)
  jQuery(".seller"+user).each(function(ind,obj){obj.innerHTML=msg;});
  else
  jQuery(".seller"+user).remove();
  
  if(msg.substr(0,4) != 'Add ') show_promt("Your friend request has been sent");
 }
 }); 
}

function add_to_block(user,refresh,show)
{ 
  jQuery.ajax({
  type: "GET",
  url: _BASE_URL+"add_to_block.php",
  data: 'user='+user,
  success: function(msg){
  var temp = strpos(msg,'|'); 
  var us = msg.substr(temp + 1);   
  msg = msg.substr(0,temp); 
  if(msg!='')
  {
  if(refresh=='1') 
  {
  if(show=='1')
  document.getElementById('block_block').style.display='block';
  profile_show_content('ID='+_MEMBER_ID+'&action=blocked','friends', 'blocked_cont','wait_container_blocked');
  profile_show_content('ID='+_MEMBER_ID,'friends', 'friends_cont','wait_container_friends');
  }
  
  jQuery(".block_list"+user).each(function(ind,obj){jQuery(obj).html(msg);});
  
  if(strpos(msg, 'unblock.png') > 0) 
    show_promt("You have successfully blocked "+us);
  else
    show_promt("You have successfully unblocked "+us);
  }
 }
 }); 
}

function move_to_cart(wid)
{ 
  jQuery.ajax({
  type: "GET",
  url: _BASE_URL+"tocart.php",
  data: 'wid='+wid,
  success: function(msg){
  if(msg=='ok')
  {
  jQuery("#tocart"+wid).html('');
  jQuery('#cart_head_counter').html(jQuery('#cart_head_counter').html()/1 + 1);
  }
  else
  alert(msg);
 }
 }); 
}

function sub_unsub(id, type)
{ 
  jQuery.ajax({
  type: "GET",
  url: _BASE_URL+"sub_unsub.php",
  data: 'id='+id+'&type='+type,
  success: function(msg){
  if(msg!='')
  jQuery(".subscribe"+id).each(function(ind,obj){obj.innerHTML=msg;});
 }
 }); 
}

function delete_account()
{
  jQuery.ajax({
  type: "GET",
  url: _BASE_URL+"check_delete.php",
  data: '',
  success: function(msg){
  if(msg == 'ok') 
  show_popup_text(document.getElementById('delete_confirm').innerHTML, 450, 230);
  else
  show_popup_text(msg, 450, 100);  
 }
  });  
}

function change_currency(id)
{ 
  jQuery.ajax({
  type: "GET",
  url: _BASE_URL+"change_currency.php",
  data: 'id='+id,
  success: function(msg){
  window.location.reload();  
 }
 }); 
}

function calc_all_total()
{
  var total = 0;
  jQuery(".shippingsel").each(function(ind,obj){  if(obj.id.substr(0,3)=='pay')
  { 
  var totals = explode("<br>",document.getElementById(str_replace("payment","total",obj.id)).innerHTML);
  if(totals.length==1)
  total = total + parseFloat(totals[0].replace(/[^0-9.]/g,''));
  else
  total = total + parseFloat(totals[1].replace(/[^0-9.]/g,''));
 // document.getElementById("all_total").innerHTML = number_format(total,2,".",","); 
  }});
  
  calc_for_seller();
}

function calc_for_seller()
{
  jQuery('.total_seller').each(function(id0, obj0){
      var ind = obj0.id.substr(12);
      var total = 0;
      jQuery('.forseller'+ind).each(function(id, obj){
          var ind_wid = obj.id.substr(5);
          if(document.getElementById('check'+ind_wid).checked)
          {
              var totals = explode("<br>",document.getElementById(str_replace("payment","total",obj.id)).innerHTML);
              if(totals.length==1)
                total = total + parseFloat(totals[0].replace(/[^0-9.]/g,''));
              else
                total = total + parseFloat(totals[1].replace(/[^0-9.]/g,''));
          }
      });
      jQuery('#total_seller'+ind).html(number_format(total,2,".",","));
  });
}

function change_cart_service(wid, service)
{ 
  jQuery.ajax({
  type: "GET",
  url: _BASE_URL+"ajax_get_shipping_price.php",
  data: 'wid='+wid+'&service='+service,
  success: function(msg){
  eval(msg);
  calc_all_total();
 }
 }); 
}

function checkout(pid, wid)
{ 
  var payment = document.getElementById('payment'+wid).value;
  if(document.getElementById('service'+wid)) var service = document.getElementById('service'+wid).value; else var service = '';
  if(payment!='')
  {
  window.location= _BASE_URL + 'checkout/'+wid+'/'+payment+'/'+service;
  }
  else  
  alert('Select payment method');
}

function checkout_all(wids_str)
{ 
    var error = '';
    var wids = explode(".", wids_str);
    var payment_all = '';
    var service_all = '';
    var wids_all = '';
    for (var key in wids) {
        if(wids[key]!='' && typeof wids[key] == 'string')
        {
              if(document.getElementById('check'+wids[key]).checked) 
              {           
                  var payment = document.getElementById('payment'+wids[key]).value;
                  if(payment=='') 
                    error = 'Select same payment method for all seller products';
                  else
                  {
                    payment_all += '.'+jQuery('#payment'+wids[key]).val();
                    service_all += '.'+jQuery('#service'+wids[key]).val();
                    wids_all += '.'+wids[key];
                  }
              }
        }
    }
    window.location= _BASE_URL + 'checkout/'+wids_all+'/'+payment_all+'/'+service_all;
}

function twitter_click()
{ 
    document.getElementById('twitter_box').checked = !document.getElementById('twitter_box').checked;
    jQuery.ajax({
      type: "GET",
      url: _BASE_URL+"twitter.php",
      data: '',
      success: function(msg){
          if(msg.substr(0,10) == 'Location: ')
            window.location = msg.substr(10);
          else
            show_popup_text(msg, 400, 300);
     }
     }); 
}

function enable_textfield(obj, name)
{ 
  if(obj.checked)
  {
  document.getElementById(name).disabled = false;
  document.getElementById(name).style.color = '#5F7784';
  }
  else
  {
  document.getElementById(name).disabled = true; 
  document.getElementById(name).style.color = '#dddddd';
  }
  
  if(name == 'offer_range_price_min')
  {
  if(obj.checked)
  {
  document.getElementById('offer_range_price_max').disabled = false;
  document.getElementById('offer_range_price_max').style.color = '#5F7784';
  document.getElementById('buy_out').checked = false;
  document.getElementById('buy_out_price').disabled = true;
  document.getElementById('buy_out_price').style.color = '#dddddd';
  }
  else
  {
  document.getElementById('offer_range_price_max').disabled = true;
  document.getElementById('offer_range_price_max').style.color = '#dddddd';
  }
  }
  if(name == 'buy_out_price')
  {
  if(obj.checked)
  {
  document.getElementById('offer_range_price_max').disabled = true;
  document.getElementById('offer_range_price_max').style.color = '#dddddd';
  document.getElementById('offer_range_price_min').disabled = true;
  document.getElementById('offer_range_price_min').style.color = '#dddddd';
  document.getElementById('offer_range').checked = false;
  }
  }
  if(name == 'return_days')
  {
  if(obj.checked)
  {
  document.getElementById('return_descr').disabled = false;
  document.getElementById('return_descr').style.color = '#5F7784';
  document.getElementById('return_type').disabled = false;
  document.getElementById('return_type').style.color = '#5F7784';
  }
  else
  {
  document.getElementById('return_descr').disabled = true;
  document.getElementById('return_descr').style.color = '#dddddd';
  document.getElementById('return_type').disabled = true;
  document.getElementById('return_type').style.color = '#dddddd';
  }
  }
  if(name == 'start_price')
  {
  if(obj.checked)
  {
  document.getElementById('offers').checked = false;
  document.getElementById('offers').disabled = true;
  }
  else
  {
  document.getElementById('offers').disabled = false;
  }
  }
}


function show_payment_email(obj, name)
{ 
  if(obj.checked)
  document.getElementById('email_'+name+'_cont').style.display = 'block';
  else
  document.getElementById('email_'+name+'_cont').style.display = 'none';
}

function resize_textarea(obj)
{
  var rows = 10;
  if(rows == 0 && (obj.scrollHeight > obj.clientHeight)) {
  
  obj.rows += 1;
  
  } 
  else if((obj.rows <= rows) && (obj.scrollHeight > obj.clientHeight)) {

  obj.rows += 1;

  } 
  else if(rows != 0 && obj.rows > rows) {


  }
}


/*!
 * jQuery JavaScript Library v1.3.2
 * http://jquery.com/
 *
 * Copyright (c) 2009 John Resig
 * Dual licensed under the MIT and GPL licenses.
 * http://docs.jquery.com/License
 *
 * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009)
 * Revision: 6246
 */
(function(){

var 
  // Will speed up references to window, and allows munging its name.
  window = this,
  // Will speed up references to undefined, and allows munging its name.
  undefined,
  // Map over jQuery in case of overwrite
  _jQuery = window.jQuery,
  // Map over the jQuery in case of overwrite
  _$ = window.$,

  jQuery = window.jQuery = window.$ = function( selector, context ) {
  // The jQuery object is actually just the init constructor 'enhanced'
  return new jQuery.fn.init( selector, context );
  },

  // A simple way to check for HTML strings or ID strings
  // (both of which we optimize for)
  quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,
  // Is it a simple selector
  isSimple = /^.[^:#\[\.,]*$/;

jQuery.fn = jQuery.prototype = {
  init: function( selector, context ) {
  // Make sure that a selection was provided
  selector = selector || document;

  // Handle $(DOMElement)
  if ( selector.nodeType ) {
  this[0] = selector;
  this.length = 1;
  this.context = selector;
  return this;
  }
  // Handle HTML strings
  if ( typeof selector === "string" ) {
  // Are we dealing with HTML string or an ID?
  var match = quickExpr.exec( selector );

  // Verify a match, and that no context was specified for #id
  if ( match && (match[1] || !context) ) {

  // HANDLE: $(html) -> $(array)
  if ( match[1] )
  selector = jQuery.clean( [ match[1] ], context );

  // HANDLE: $("#id")
  else {
  var elem = document.getElementById( match[3] );

  // Handle the case where IE and Opera return items
  // by name instead of ID
  if ( elem && elem.id != match[3] )
  return jQuery().find( selector );

  // Otherwise, we inject the element directly into the jQuery object
  var ret = jQuery( elem || [] );
  ret.context = document;
  ret.selector = selector;
  return ret;
  }

  // HANDLE: $(expr, [context])
  // (which is just equivalent to: $(content).find(expr)
  } else
  return jQuery( context ).find( selector );

  // HANDLE: $(function)
  // Shortcut for document ready
  } else if ( jQuery.isFunction( selector ) )
  return jQuery( document ).ready( selector );

  // Make sure that old selector state is passed along
  if ( selector.selector && selector.context ) {
  this.selector = selector.selector;
  this.context = selector.context;
  }

  return this.setArray(jQuery.isArray( selector ) ?
  selector :
  jQuery.makeArray(selector));
  },

  // Start with an empty selector
  selector: "",

  // The current version of jQuery being used
  jquery: "1.3.2",

  // The number of elements contained in the matched element set
  size: function() {
  return this.length;
  },

  // Get the Nth element in the matched element set OR
  // Get the whole matched element set as a clean array
  get: function( num ) {
  return num === undefined ?

  // Return a 'clean' array
  Array.prototype.slice.call( this ) :

  // Return just the object
  this[ num ];
  },

  // Take an array of elements and push it onto the stack
  // (returning the new matched element set)
  pushStack: function( elems, name, selector ) {
  // Build a new jQuery matched element set
  var ret = jQuery( elems );

  // Add the old object onto the stack (as a reference)
  ret.prevObject = this;

  ret.context = this.context;

  if ( name === "find" )
  ret.selector = this.selector + (this.selector ? " " : "") + selector;
  else if ( name )
  ret.selector = this.selector + "." + name + "(" + selector + ")";

  // Return the newly-formed element set
  return ret;
  },

  // Force the current matched set of elements to become
  // the specified array of elements (destroying the stack in the process)
  // You should use pushStack() in order to do this, but maintain the stack
  setArray: function( elems ) {
  // Resetting the length to 0, then using the native Array push
  // is a super-fast way to populate an object with array-like properties
  this.length = 0;
  Array.prototype.push.apply( this, elems );

  return this;
  },

  // Execute a callback for every element in the matched set.
  // (You can seed the arguments with an array of args, but this is
  // only used internally.)
  each: function( callback, args ) {
  return jQuery.each( this, callback, args );
  },

  // Determine the position of an element within
  // the matched set of elements
  index: function( elem ) {
  // Locate the position of the desired element
  return jQuery.inArray(
  // If it receives a jQuery object, the first element is used
  elem && elem.jquery ? elem[0] : elem
  , this );
  },

  attr: function( name, value, type ) {
  var options = name;

  // Look for the case where we're accessing a style value
  if ( typeof name === "string" )
  if ( value === undefined )
  return this[0] && jQuery[ type || "attr" ]( this[0], name );

  else {
  options = {};
  options[ name ] = value;
  }

  // Check to see if we're setting style values
  return this.each(function(i){
  // Set all the styles
  for ( name in options )
  jQuery.attr(
  type ?
  this.style :
  this,
  name, jQuery.prop( this, options[ name ], type, i, name )
  );
  });
  },

  css: function( key, value ) {
  // ignore negative width and height values
  if ( (key == 'width' || key == 'height') && parseFloat(value) < 0 )
  value = undefined;
  return this.attr( key, value, "curCSS" );
  },

  text: function( text ) {
  if ( typeof text !== "object" && text != null )
  return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );

  var ret = "";

  jQuery.each( text || this, function(){
  jQuery.each( this.childNodes, function(){
  if ( this.nodeType != 8 )
  ret += this.nodeType != 1 ?
  this.nodeValue :
  jQuery.fn.text( [ this ] );
  });
  });

  return ret;
  },

  wrapAll: function( html ) {
  if ( this[0] ) {
  // The elements to wrap the target around
  var wrap = jQuery( html, this[0].ownerDocument ).clone();

  if ( this[0].parentNode )
  wrap.insertBefore( this[0] );

  wrap.map(function(){
  var elem = this;

  while ( elem.firstChild )
  elem = elem.firstChild;

  return elem;
  }).append(this);
  }

  return this;
  },

  wrapInner: function( html ) {
  return this.each(function(){
  jQuery( this ).contents().wrapAll( html );
  });
  },

  wrap: function( html ) {
  return this.each(function(){
  jQuery( this ).wrapAll( html );
  });
  },

  append: function() {
  return this.domManip(arguments, true, function(elem){
  if (this.nodeType == 1)
  this.appendChild( elem );
  });
  },

  prepend: function() {
  return this.domManip(arguments, true, function(elem){
  if (this.nodeType == 1)
  this.insertBefore( elem, this.firstChild );
  });
  },

  before: function() {
  return this.domManip(arguments, false, function(elem){
  this.parentNode.insertBefore( elem, this );
  });
  },

  after: function() {
  return this.domManip(arguments, false, function(elem){
  this.parentNode.insertBefore( elem, this.nextSibling );
  });
  },

  end: function() {
  return this.prevObject || jQuery( [] );
  },

  // For internal use only.
  // Behaves like an Array's method, not like a jQuery method.
  push: [].push,
  sort: [].sort,
  splice: [].splice,

  find: function( selector ) {
  if ( this.length === 1 ) {
  var ret = this.pushStack( [], "find", selector );
  ret.length = 0;
  jQuery.find( selector, this[0], ret );
  return ret;
  } else {
  return this.pushStack( jQuery.unique(jQuery.map(this, function(elem){
  return jQuery.find( selector, elem );
  })), "find", selector );
  }
  },

  clone: function( events ) {
  // Do the clone
  var ret = this.map(function(){
  if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) {
  // IE copies events bound via attachEvent when
  // using cloneNode. Calling detachEvent on the
  // clone will also remove the events from the orignal
  // In order to get around this, we use innerHTML.
  // Unfortunately, this means some modifications to
  // attributes in IE that are actually only stored
  // as properties will not be copied (such as the
  // the name attribute on an input).
  var html = this.outerHTML;
  if ( !html ) {
  var div = this.ownerDocument.createElement("div");
  div.appendChild( this.cloneNode(true) );
  html = div.innerHTML;
  }

  return jQuery.clean([html.replace(/ jQuery\d+="(?:\d+|null)"/g, "").replace(/^\s*/, "")])[0];
  } else
  return this.cloneNode(true);
  });

  // Copy the events from the original to the clone
  if ( events === true ) {
  var orig = this.find("*").andSelf(), i = 0;

  ret.find("*").andSelf().each(function(){
  if ( this.nodeName !== orig[i].nodeName )
  return;

  var events = jQuery.data( orig[i], "events" );

  for ( var type in events ) {
  for ( var handler in events[ type ] ) {
  jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data );
  }
  }

  i++;
  });
  }

  // Return the cloned set
  return ret;
  },

  filter: function( selector ) {
  return this.pushStack(
  jQuery.isFunction( selector ) &&
  jQuery.grep(this, function(elem, i){
  return selector.call( elem, i );
  }) ||

  jQuery.multiFilter( selector, jQuery.grep(this, function(elem){
  return elem.nodeType === 1;
  }) ), "filter", selector );
  },

  closest: function( selector ) {
  var pos = jQuery.expr.match.POS.test( selector ) ? jQuery(selector) : null,
  closer = 0;

  return this.map(function(){
  var cur = this;
  while ( cur && cur.ownerDocument ) {
  if ( pos ? pos.index(cur) > -1 : jQuery(cur).is(selector) ) {
  jQuery.data(cur, "closest", closer);
  return cur;
  }
  cur = cur.parentNode;
  closer++;
  }
  });
  },

  not: function( selector ) {
  if ( typeof selector === "string" )
  // test special case where just one selector is passed in
  if ( isSimple.test( selector ) )
  return this.pushStack( jQuery.multiFilter( selector, this, true ), "not", selector );
  else
  selector = jQuery.multiFilter( selector, this );

  var isArrayLike = selector.length && selector[selector.length - 1] !== undefined && !selector.nodeType;
  return this.filter(function() {
  return isArrayLike ? jQuery.inArray( this, selector ) < 0 : this != selector;
  });
  },

  add: function( selector ) {
  return this.pushStack( jQuery.unique( jQuery.merge(
  this.get(),
  typeof selector === "string" ?
  jQuery( selector ) :
  jQuery.makeArray( selector )
  )));
  },

  is: function( selector ) {
  return !!selector && jQuery.multiFilter( selector, this ).length > 0;
  },

  hasClass: function( selector ) {
  return !!selector && this.is( "." + selector );
  },

  val: function( value ) {
  if ( value === undefined ) {  
  var elem = this[0];

  if ( elem ) {
  if( jQuery.nodeName( elem, 'option' ) )
  return (elem.attributes.value || {}).specified ? elem.value : elem.text;
  
  // We need to handle select boxes special
  if ( jQuery.nodeName( elem, "select" ) ) {
  var index = elem.selectedIndex,
  values = [],
  options = elem.options,
  one = elem.type == "select-one";

  // Nothing was selected
  if ( index < 0 )
  return null;

  // Loop through all the selected options
  for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
  var option = options[ i ];

  if ( option.selected ) {
  // Get the specifc value for the option
  value = jQuery(option).val();

  // We don't need an array for one selects
  if ( one )
  return value;

  // Multi-Selects return an array
  values.push( value );
  }
  }

  return values;  
  }

  // Everything else, we just grab the value
  return (elem.value || "").replace(/\r/g, "");

  }

  return undefined;
  }

  if ( typeof value === "number" )
  value += '';

  return this.each(function(){
  if ( this.nodeType != 1 )
  return;

  if ( jQuery.isArray(value) && /radio|checkbox/.test( this.type ) )
  this.checked = (jQuery.inArray(this.value, value) >= 0 ||
  jQuery.inArray(this.name, value) >= 0);

  else if ( jQuery.nodeName( this, "select" ) ) {
  var values = jQuery.makeArray(value);

  jQuery( "option", this ).each(function(){
  this.selected = (jQuery.inArray( this.value, values ) >= 0 ||
  jQuery.inArray( this.text, values ) >= 0);
  });

  if ( !values.length )
  this.selectedIndex = -1;

  } else
  this.value = value;
  });
  },

  html: function( value ) {
  return value === undefined ?
  (this[0] ?
  this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g, "") :
  null) :
  this.empty().append( value );
  },

  replaceWith: function( value ) {
  return this.after( value ).remove();
  },

  eq: function( i ) {
  return this.slice( i, +i + 1 );
  },

  slice: function() {
  return this.pushStack( Array.prototype.slice.apply( this, arguments ),
  "slice", Array.prototype.slice.call(arguments).join(",") );
  },

  map: function( callback ) {
  return this.pushStack( jQuery.map(this, function(elem, i){
  return callback.call( elem, i, elem );
  }));
  },

  andSelf: function() {
  return this.add( this.prevObject );
  },

  domManip: function( args, table, callback ) {
  if ( this[0] ) {
  var fragment = (this[0].ownerDocument || this[0]).createDocumentFragment(),
  scripts = jQuery.clean( args, (this[0].ownerDocument || this[0]), fragment ),
  first = fragment.firstChild;

  if ( first )
  for ( var i = 0, l = this.length; i < l; i++ )
  callback.call( root(this[i], first), this.length > 1 || i > 0 ?
  fragment.cloneNode(true) : fragment );
  
  if ( scripts )
  jQuery.each( scripts, evalScript );
  }

  return this;
  
  function root( elem, cur ) {
  return table && jQuery.nodeName(elem, "table") && jQuery.nodeName(cur, "tr") ?
  (elem.getElementsByTagName("tbody")[0] ||
  elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
  elem;
  }
  }
};

// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;

function evalScript( i, elem ) {
  if ( elem.src )
  jQuery.ajax({
  url: elem.src,
  async: false,
  dataType: "script"
  });

  else
  jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );

  if ( elem.parentNode )
  elem.parentNode.removeChild( elem );
}

function now(){
  return +new Date;
}

jQuery.extend = jQuery.fn.extend = function() {
  // copy reference to target object
  var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options;

  // Handle a deep copy situation
  if ( typeof target === "boolean" ) {
  deep = target;
  target = arguments[1] || {};
  // skip the boolean and the target
  i = 2;
  }

  // Handle case when target is a string or something (possible in deep copy)
  if ( typeof target !== "object" && !jQuery.isFunction(target) )
  target = {};

  // extend jQuery itself if only one argument is passed
  if ( length == i ) {
  target = this;
  --i;
  }

  for ( ; i < length; i++ )
  // Only deal with non-null/undefined values
  if ( (options = arguments[ i ]) != null )
  // Extend the base object
  for ( var name in options ) {
  var src = target[ name ], copy = options[ name ];

  // Prevent never-ending loop
  if ( target === copy )
  continue;

  // Recurse if we're merging object values
  if ( deep && copy && typeof copy === "object" && !copy.nodeType )
  target[ name ] = jQuery.extend( deep, 
  // Never move original objects, clone them
  src || ( copy.length != null ? [ ] : { } )
  , copy );

  // Don't bring in undefined values
  else if ( copy !== undefined )
  target[ name ] = copy;

  }

  // Return the modified object
  return target;
};

// exclude the following css properties to add px
var  exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i,
  // cache defaultView
  defaultView = document.defaultView || {},
  toString = Object.prototype.toString;

jQuery.extend({
  noConflict: function( deep ) {
  window.$ = _$;

  if ( deep )
  window.jQuery = _jQuery;

  return jQuery;
  },

  // See test/unit/core.js for details concerning isFunction.
  // Since version 1.3, DOM methods and functions like alert
  // aren't supported. They return false on IE (#2968).
  isFunction: function( obj ) {
  return toString.call(obj) === "[object Function]";
  },

  isArray: function( obj ) {
  return toString.call(obj) === "[object Array]";
  },

  // check if an element is in a (or is an) XML document
  isXMLDoc: function( elem ) {
  return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" ||
  !!elem.ownerDocument && jQuery.isXMLDoc( elem.ownerDocument );
  },

  // Evalulates a script in a global context
  globalEval: function( data ) {
  if ( data && /\S/.test(data) ) {
  // Inspired by code by Andrea Giammarchi
  // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
  var head = document.getElementsByTagName("head")[0] || document.documentElement,
  script = document.createElement("script");

  script.type = "text/javascript";
  if ( jQuery.support.scriptEval )
  script.appendChild( document.createTextNode( data ) );
  else
  script.text = data;

  // Use insertBefore instead of appendChild  to circumvent an IE6 bug.
  // This arises when a base node is used (#2709).
  head.insertBefore( script, head.firstChild );
  head.removeChild( script );
  }
  },

  nodeName: function( elem, name ) {
  return elem.nodeName && elem.nodeName.toUpperCase() == name.toUpperCase();
  },

  // args is for internal usage only
  each: function( object, callback, args ) {
  var name, i = 0, length = object.length;

  if ( args ) {
  if ( length === undefined ) {
  for ( name in object )
  if ( callback.apply( object[ name ], args ) === false )
  break;
  } else
  for ( ; i < length; )
  if ( callback.apply( object[ i++ ], args ) === false )
  break;

  // A special, fast, case for the most common use of each
  } else {
  if ( length === undefined ) {
  for ( name in object )
  if ( callback.call( object[ name ], name, object[ name ] ) === false )
  break;
  } else
  for ( var value = object[0];
  i < length && callback.call( value, i, value ) !== false; value = object[++i] ){}
  }

  return object;
  },

  prop: function( elem, value, type, i, name ) {
  // Handle executable functions
  if ( jQuery.isFunction( value ) )
  value = value.call( elem, i );

  // Handle passing in a number to a CSS property
  return typeof value === "number" && type == "curCSS" && !exclude.test( name ) ?
  value + "px" :
  value;
  },

  className: {
  // internal only, use addClass("class")
  add: function( elem, classNames ) {
  jQuery.each((classNames || "").split(/\s+/), function(i, className){
  if ( elem.nodeType == 1 && !jQuery.className.has( elem.className, className ) )
  elem.className += (elem.className ? " " : "") + className;
  });
  },

  // internal only, use removeClass("class")
  remove: function( elem, classNames ) {
  if (elem.nodeType == 1)
  elem.className = classNames !== undefined ?
  jQuery.grep(elem.className.split(/\s+/), function(className){
  return !jQuery.className.has( classNames, className );
  }).join(" ") :
  "";
  },

  // internal only, use hasClass("class")
  has: function( elem, className ) {
  return elem && jQuery.inArray( className, (elem.className || elem).toString().split(/\s+/) ) > -1;
  }
  },

  // A method for quickly swapping in/out CSS properties to get correct calculations
  swap: function( elem, options, callback ) {
  var old = {};
  // Remember the old values, and insert the new ones
  for ( var name in options ) {
  old[ name ] = elem.style[ name ];
  elem.style[ name ] = options[ name ];
  }

  callback.call( elem );

  // Revert the old values
  for ( var name in options )
  elem.style[ name ] = old[ name ];
  },

  css: function( elem, name, force, extra ) {
  if ( name == "width" || name == "height" ) {
  var val, props = { position: "absolute", visibility: "hidden", display:"block" }, which = name == "width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ];

  function getWH() {
  val = name == "width" ? elem.offsetWidth : elem.offsetHeight;

  if ( extra === "border" )
  return;

  jQuery.each( which, function() {
  if ( !extra )
  val -= parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0;
  if ( extra === "margin" )
  val += parseFloat(jQuery.curCSS( elem, "margin" + this, true)) || 0;
  else
  val -= parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0;
  });
  }

  if ( elem.offsetWidth !== 0 )
  getWH();
  else
  jQuery.swap( elem, props, getWH );

  return Math.max(0, Math.round(val));
  }

  return jQuery.curCSS( elem, name, force );
  },

  curCSS: function( elem, name, force ) {
  var ret, style = elem.style;

  // We need to handle opacity special in IE
  if ( name == "opacity" && !jQuery.support.opacity ) {
  ret = jQuery.attr( style, "opacity" );

  return ret == "" ?
  "1" :
  ret;
  }

  // Make sure we're using the right name for getting the float value
  if ( name.match( /float/i ) )
  name = styleFloat;

  if ( !force && style && style[ name ] )
  ret = style[ name ];

  else if ( defaultView.getComputedStyle ) {

  // Only "float" is needed here
  if ( name.match( /float/i ) )
  name = "float";

  name = name.replace( /([A-Z])/g, "-$1" ).toLowerCase();

  var computedStyle = defaultView.getComputedStyle( elem, null );

  if ( computedStyle )
  ret = computedStyle.getPropertyValue( name );

  // We should always get a number back from opacity
  if ( name == "opacity" && ret == "" )
  ret = "1";

  } else if ( elem.currentStyle ) {
  var camelCase = name.replace(/\-(\w)/g, function(all, letter){
  return letter.toUpperCase();
  });

  ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ];

  // From the awesome hack by Dean Edwards
  // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291

  // If we're not dealing with a regular pixel number
  // but a number that has a weird ending, we need to convert it to pixels
  if ( !/^\d+(px)?$/i.test( ret ) && /^\d/.test( ret ) ) {
  // Remember the original values
  var left = style.left, rsLeft = elem.runtimeStyle.left;

  // Put in the new values to get a computed value out
  elem.runtimeStyle.left = elem.currentStyle.left;
  style.left = ret || 0;
  ret = style.pixelLeft + "px";

  // Revert the changed values
  style.left = left;
  elem.runtimeStyle.left = rsLeft;
  }
  }

  return ret;
  },

  clean: function( elems, context, fragment ) {
  context = context || document;

  // !context.createElement fails in IE with an error but returns typeof 'object'
  if ( typeof context.createElement === "undefined" )
  context = context.ownerDocument || context[0] && context[0].ownerDocument || document;

  // If a single string is passed in and it's a single tag
  // just do a createElement and skip the rest
  if ( !fragment && elems.length === 1 && typeof elems[0] === "string" ) {
  var match = /^<(\w+)\s*\/?>$/.exec(elems[0]);
  if ( match )
  return [ context.createElement( match[1] ) ];
  }

  var ret = [], scripts = [], div = context.createElement("div");

  jQuery.each(elems, function(i, elem){
  if ( typeof elem === "number" )
  elem += '';

  if ( !elem )
  return;

  // Convert html string into DOM nodes
  if ( typeof elem === "string" ) {
  // Fix "XHTML"-style tags in all browsers
  elem = elem.replace(/(<(\w+)[^>]*?)\/>/g, function(all, front, tag){
  return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ?
  all :
  front + "></" + tag + ">";
  });

  // Trim whitespace, otherwise indexOf won't work as expected
  var tags = elem.replace(/^\s+/, "").substring(0, 10).toLowerCase();

  var wrap =
  // option or optgroup
  !tags.indexOf("<opt") &&
  [ 1, "<select multiple='multiple'>", "</select>" ] ||

  !tags.indexOf("<leg") &&
  [ 1, "<fieldset>", "</fieldset>" ] ||

  tags.match(/^<(thead|tbody|tfoot|colg|cap)/) &&
  [ 1, "<table>", "</table>" ] ||

  !tags.indexOf("<tr") &&
  [ 2, "<table><tbody>", "</tbody></table>" ] ||

 // <thead> matched above
  (!tags.indexOf("<td") || !tags.indexOf("<th")) &&
  [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ] ||

  !tags.indexOf("<col") &&
  [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ] ||

  // IE can't serialize <link> and <script> tags normally
  !jQuery.support.htmlSerialize &&
  [ 1, "div<div>", "</div>" ] ||

  [ 0, "", "" ];

  // Go to html and back, then peel off extra wrappers
  div.innerHTML = wrap[1] + elem + wrap[2];

  // Move to the right depth
  while ( wrap[0]-- )
  div = div.lastChild;

  // Remove IE's autoinserted <tbody> from table fragments
  if ( !jQuery.support.tbody ) {

  // String was a <table>, *may* have spurious <tbody>
  var hasBody = /<tbody/i.test(elem),
  tbody = !tags.indexOf("<table") && !hasBody ?
  div.firstChild && div.firstChild.childNodes :

  // String was a bare <thead> or <tfoot>
  wrap[1] == "<table>" && !hasBody ?
  div.childNodes :
  [];

  for ( var j = tbody.length - 1; j >= 0 ; --j )
  if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length )
  tbody[ j ].parentNode.removeChild( tbody[ j ] );

  }

  // IE completely kills leading whitespace when innerHTML is used
  if ( !jQuery.support.leadingWhitespace && /^\s/.test( elem ) )
  div.insertBefore( context.createTextNode( elem.match(/^\s*/)[0] ), div.firstChild );
  
  elem = jQuery.makeArray( div.childNodes );
  }

  if ( elem.nodeType )
  ret.push( elem );
  else
  ret = jQuery.merge( ret, elem );

  });

  if ( fragment ) {
  for ( var i = 0; ret[i]; i++ ) {
  if ( jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
  scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
  } else {
  if ( ret[i].nodeType === 1 )
  ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
  fragment.appendChild( ret[i] );
  }
  }
  
  return scripts;
  }

  return ret;
  },

  attr: function( elem, name, value ) {
  // don't set attributes on text and comment nodes
  if (!elem || elem.nodeType == 3 || elem.nodeType == 8)
  return undefined;

  var notxml = !jQuery.isXMLDoc( elem ),
  // Whether we are setting (or getting)
  set = value !== undefined;

  // Try to normalize/fix the name
  name = notxml && jQuery.props[ name ] || name;

  // Only do all the following if this is a node (faster for style)
  // IE elem.getAttribute passes even for style
  if ( elem.tagName ) {

  // These attributes require special treatment
  var special = /href|src|style/.test( name );

  // Safari mis-reports the default selected property of a hidden option
  // Accessing the parent's selectedIndex property fixes it
  if ( name == "selected" && elem.parentNode )
  elem.parentNode.selectedIndex;

  // If applicable, access the attribute via the DOM 0 way
  if ( name in elem && notxml && !special ) {
  if ( set ){
  // We can't allow the type property to be changed (since it causes problems in IE)
  if ( name == "type" && jQuery.nodeName( elem, "input" ) && elem.parentNode )
  throw "type property can't be changed";

  elem[ name ] = value;
  }

  // browsers index elements by id/name on forms, give priority to attributes.
  if( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) )
  return elem.getAttributeNode( name ).nodeValue;

  // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
  // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
  if ( name == "tabIndex" ) {
  var attributeNode = elem.getAttributeNode( "tabIndex" );
  return attributeNode && attributeNode.specified
  ? attributeNode.value
  : elem.nodeName.match(/(button|input|object|select|textarea)/i)
  ? 0
  : elem.nodeName.match(/^(a|area)$/i) && elem.href
  ? 0
  : undefined;
  }

  return elem[ name ];
  }

  if ( !jQuery.support.style && notxml &&  name == "style" )
  return jQuery.attr( elem.style, "cssText", value );

  if ( set )
  // convert the value to a string (all browsers do this but IE) see #1070
  elem.setAttribute( name, "" + value );

  var attr = !jQuery.support.hrefNormalized && notxml && special
  // Some attributes require a special call on IE
  ? elem.getAttribute( name, 2 )
  : elem.getAttribute( name );

  // Non-existent attributes return null, we normalize to undefined
  return attr === null ? undefined : attr;
  }

  // elem is actually elem.style ... set the style

  // IE uses filters for opacity
  if ( !jQuery.support.opacity && name == "opacity" ) {
  if ( set ) {
  // IE has trouble with opacity if it does not have layout
  // Force it by setting the zoom level
  elem.zoom = 1;

  // Set the alpha filter to set the opacity
  elem.filter = (elem.filter || "").replace( /alpha\([^)]*\)/, "" ) +
  (parseInt( value ) + '' == "NaN" ? "" : "alpha(opacity=" + value * 100 + ")");
  }

  return elem.filter && elem.filter.indexOf("opacity=") >= 0 ?
  (parseFloat( elem.filter.match(/opacity=([^)]*)/)[1] ) / 100) + '':
  "";
  }

  name = name.replace(/-([a-z])/ig, function(all, letter){
  return letter.toUpperCase();
  });

  if ( set && value != 'undefinedpx')
  {
    elem[ name ] = value;
  }


  return elem[ name ];
  },

  trim: function( text ) {
  return (text || "").replace( /^\s+|\s+$/g, "" );
  },

  makeArray: function( array ) {
  var ret = [];

  if( array != null ){
  var i = array.length;
  // The window, strings (and functions) also have 'length'
  if( i == null || typeof array === "string" || jQuery.isFunction(array) || array.setInterval )
  ret[0] = array;
  else
  while( i )
  ret[--i] = array[i];
  }

  return ret;
  },

  inArray: function( elem, array ) {
  for ( var i = 0, length = array.length; i < length; i++ )
  // Use === because on IE, window == document
  if ( array[ i ] === elem )
  return i;

  return -1;
  },

  merge: function( first, second ) {
  // We have to loop this way because IE & Opera overwrite the length
  // expando of getElementsByTagName
  var i = 0, elem, pos = first.length;
  // Also, we need to make sure that the correct elements are being returned
  // (IE returns comment nodes in a '*' query)
  if ( !jQuery.support.getAll ) {
  while ( (elem = second[ i++ ]) != null )
  if ( elem.nodeType != 8 )
  first[ pos++ ] = elem;

  } else
  while ( (elem = second[ i++ ]) != null )
  first[ pos++ ] = elem;

  return first;
  },

  unique: function( array ) {
  var ret = [], done = {};

  try {

  for ( var i = 0, length = array.length; i < length; i++ ) {
  var id = jQuery.data( array[ i ] );

  if ( !done[ id ] ) {
  done[ id ] = true;
  ret.push( array[ i ] );
  }
  }

  } catch( e ) {
  ret = array;
  }

  return ret;
  },

  grep: function( elems, callback, inv ) {
  var ret = [];

  // Go through the array, only saving the items
  // that pass the validator function
  for ( var i = 0, length = elems.length; i < length; i++ )
  if ( !inv != !callback( elems[ i ], i ) )
  ret.push( elems[ i ] );

  return ret;
  },

  map: function( elems, callback ) {
  var ret = [];

  // Go through the array, translating each of the items to their
  // new value (or values).
  for ( var i = 0, length = elems.length; i < length; i++ ) {
  var value = callback( elems[ i ], i );

  if ( value != null )
  ret[ ret.length ] = value;
  }

  return ret.concat.apply( [], ret );
  }
});

// Use of jQuery.browser is deprecated.
// It's included for backwards compatibility and plugins,
// although they should work to migrate away.

var userAgent = navigator.userAgent.toLowerCase();

// Figure out what browser is being used
jQuery.browser = {
  version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1],
  safari: /webkit/.test( userAgent ),
  opera: /opera/.test( userAgent ),
  msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
  mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
};

jQuery.each({
  parent: function(elem){return elem.parentNode;},
  parents: function(elem){return jQuery.dir(elem,"parentNode");},
  next: function(elem){return jQuery.nth(elem,2,"nextSibling");},
  prev: function(elem){return jQuery.nth(elem,2,"previousSibling");},
  nextAll: function(elem){return jQuery.dir(elem,"nextSibling");},
  prevAll: function(elem){return jQuery.dir(elem,"previousSibling");},
  siblings: function(elem){return jQuery.sibling(elem.parentNode.firstChild,elem);},
  children: function(elem){return jQuery.sibling(elem.firstChild);},
  contents: function(elem){return jQuery.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:jQuery.makeArray(elem.childNodes);}
}, function(name, fn){
  jQuery.fn[ name ] = function( selector ) {
  var ret = jQuery.map( this, fn );

  if ( selector && typeof selector == "string" )
  ret = jQuery.multiFilter( selector, ret );

  return this.pushStack( jQuery.unique( ret ), name, selector );
  };
});

jQuery.each({
  appendTo: "append",
  prependTo: "prepend",
  insertBefore: "before",
  insertAfter: "after",
  replaceAll: "replaceWith"
}, function(name, original){
  jQuery.fn[ name ] = function( selector ) {
  var ret = [], insert = jQuery( selector );

  for ( var i = 0, l = insert.length; i < l; i++ ) {
  var elems = (i > 0 ? this.clone(true) : this).get();
  jQuery.fn[ original ].apply( jQuery(insert[i]), elems );
  ret = ret.concat( elems );
  }

  return this.pushStack( ret, name, selector );
  };
});

jQuery.each({
  removeAttr: function( name ) {
  jQuery.attr( this, name, "" );
  if (this.nodeType == 1)
  this.removeAttribute( name );
  },

  addClass: function( classNames ) {
  jQuery.className.add( this, classNames );
  },

  removeClass: function( classNames ) {
  jQuery.className.remove( this, classNames );
  },

  toggleClass: function( classNames, state ) {
  if( typeof state !== "boolean" )
  state = !jQuery.className.has( this, classNames );
  jQuery.className[ state ? "add" : "remove" ]( this, classNames );
  },

  remove: function( selector ) {
  if ( !selector || jQuery.filter( selector, [ this ] ).length ) {
  // Prevent memory leaks
  jQuery( "*", this ).add([this]).each(function(){
  jQuery.event.remove(this);
  jQuery.removeData(this);
  });
  if (this.parentNode)
  this.parentNode.removeChild( this );
  }
  },

  empty: function() {
  // Remove element nodes and prevent memory leaks
  jQuery(this).children().remove();

  // Remove any remaining nodes
  while ( this.firstChild )
  this.removeChild( this.firstChild );
  }
}, function(name, fn){
  jQuery.fn[ name ] = function(){
  return this.each( fn, arguments );
  };
});

// Helper function used by the dimensions and offset modules
function num(elem, prop) {
  return elem[0] && parseInt( jQuery.curCSS(elem[0], prop, true), 10 ) || 0;
}
var expando = "jQuery" + now(), uuid = 0, windowData = {};

jQuery.extend({
  cache: {},

  data: function( elem, name, data ) {
  elem = elem == window ?
  windowData :
  elem;

  var id = elem[ expando ];

  // Compute a unique ID for the element
  if ( !id )
  id = elem[ expando ] = ++uuid;

  // Only generate the data cache if we're
  // trying to access or manipulate it
  if ( name && !jQuery.cache[ id ] )
  jQuery.cache[ id ] = {};

  // Prevent overriding the named cache with undefined values
  if ( data !== undefined )
  jQuery.cache[ id ][ name ] = data;

  // Return the named cache data, or the ID for the element
  return name ?
  jQuery.cache[ id ][ name ] :
  id;
  },

  removeData: function( elem, name ) {
  elem = elem == window ?
  windowData :
  elem;

  var id = elem[ expando ];

  // If we want to remove a specific section of the element's data
  if ( name ) {
  if ( jQuery.cache[ id ] ) {
  // Remove the section of cache data
  delete jQuery.cache[ id ][ name ];

  // If we've removed all the data, remove the element's cache
  name = "";

  for ( name in jQuery.cache[ id ] )
  break;

  if ( !name )
  jQuery.removeData( elem );
  }

  // Otherwise, we want to remove all of the element's data
  } else {
  // Clean up the element expando
  try {
  delete elem[ expando ];
  } catch(e){
  // IE has trouble directly removing the expando
  // but it's ok with using removeAttribute
  if ( elem.removeAttribute )
  elem.removeAttribute( expando );
  }

  // Completely remove the data cache
  delete jQuery.cache[ id ];
  }
  },
  queue: function( elem, type, data ) {
  if ( elem ){
  
  type = (type || "fx") + "queue";
  
  var q = jQuery.data( elem, type );
  
  if ( !q || jQuery.isArray(data) )
  q = jQuery.data( elem, type, jQuery.makeArray(data) );
  else if( data )
  q.push( data );
  
  }
  return q;
  },

  dequeue: function( elem, type ){
  var queue = jQuery.queue( elem, type ),
  fn = queue.shift();
  
  if( !type || type === "fx" )
  fn = queue[0];
  
  if( fn !== undefined )
  fn.call(elem);
  }
});

jQuery.fn.extend({
  data: function( key, value ){
  var parts = key.split(".");
  parts[1] = parts[1] ? "." + parts[1] : "";

  if ( value === undefined ) {
  var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);

  if ( data === undefined && this.length )
  data = jQuery.data( this[0], key );

  return data === undefined && parts[1] ?
  this.data( parts[0] ) :
  data;
  } else
  return this.trigger("setData" + parts[1] + "!", [parts[0], value]).each(function(){
  jQuery.data( this, key, value );
  });
  },

  removeData: function( key ){
  return this.each(function(){
  jQuery.removeData( this, key );
  });
  },
  queue: function(type, data){
  if ( typeof type !== "string" ) {
  data = type;
  type = "fx";
  }

  if ( data === undefined )
  return jQuery.queue( this[0], type );

  return this.each(function(){
  var queue = jQuery.queue( this, type, data );
  
 if( type == "fx" && queue.length == 1 )
  queue[0].call(this);
  });
  },
  dequeue: function(type){
  return this.each(function(){
  jQuery.dequeue( this, type );
  });
  }
});/*!
 * Sizzle CSS Selector Engine - v0.9.3
 *  Copyright 2009, The Dojo Foundation
 *  Released under the MIT, BSD, and GPL Licenses.
 *  More information: http://sizzlejs.com/
 */
(function(){

var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,
  done = 0,
  toString = Object.prototype.toString;

var Sizzle = function(selector, context, results, seed) {
  results = results || [];
  context = context || document;

  if ( context.nodeType !== 1 && context.nodeType !== 9 )
  return [];
  
  if ( !selector || typeof selector !== "string" ) {
  return results;
  }

  var parts = [], m, set, checkSet, check, mode, extra, prune = true;
  
  // Reset the position of the chunker regexp (start from head)
  chunker.lastIndex = 0;
  
  while ( (m = chunker.exec(selector)) !== null ) {
  parts.push( m[1] );
  
  if ( m[2] ) {
  extra = RegExp.rightContext;
  break;
  }
  }

  if ( parts.length > 1 && origPOS.exec( selector ) ) {
  if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
  set = posProcess( parts[0] + parts[1], context );
  } else {
  set = Expr.relative[ parts[0] ] ?
  [ context ] :
  Sizzle( parts.shift(), context );

  while ( parts.length ) {
  selector = parts.shift();

  if ( Expr.relative[ selector ] )
  selector += parts.shift();

  set = posProcess( selector, set );
  }
  }
  } else {
  var ret = seed ?
  { expr: parts.pop(), set: makeArray(seed) } :
  Sizzle.find( parts.pop(), parts.length === 1 && context.parentNode ? context.parentNode : context, isXML(context) );
  set = Sizzle.filter( ret.expr, ret.set );

  if ( parts.length > 0 ) {
  checkSet = makeArray(set);
  } else {
  prune = false;
  }

  while ( parts.length ) {
  var cur = parts.pop(), pop = cur;

  if ( !Expr.relative[ cur ] ) {
  cur = "";
  } else {
  pop = parts.pop();
  }

  if ( pop == null ) {
  pop = context;
  }

  Expr.relative[ cur ]( checkSet, pop, isXML(context) );
  }
  }

  if ( !checkSet ) {
  checkSet = set;
  }

  if ( !checkSet ) {
  throw "Syntax error, unrecognized expression: " + (cur || selector);
  }

  if ( toString.call(checkSet) === "[object Array]" ) {
  if ( !prune ) {
  results.push.apply( results, checkSet );
  } else if ( context.nodeType === 1 ) {
  for ( var i = 0; checkSet[i] != null; i++ ) {
  if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains(context, checkSet[i])) ) {
  results.push( set[i] );
  }
  }
  } else {
  for ( var i = 0; checkSet[i] != null; i++ ) {
  if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
  results.push( set[i] );
  }
  }
  }
  } else {
  makeArray( checkSet, results );
  }

  if ( extra ) {
  Sizzle( extra, context, results, seed );

  if ( sortOrder ) {
  hasDuplicate = false;
  results.sort(sortOrder);

  if ( hasDuplicate ) {
  for ( var i = 1; i < results.length; i++ ) {
  if ( results[i] === results[i-1] ) {
  results.splice(i--, 1);
  }
  }
  }
  }
  }

  return results;
};

Sizzle.matches = function(expr, set){
  return Sizzle(expr, null, null, set);
};

Sizzle.find = function(expr, context, isXML){
  var set, match;

  if ( !expr ) {
  return [];
  }

  for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
  var type = Expr.order[i], match;
  
  if ( (match = Expr.match[ type ].exec( expr )) ) {
  var left = RegExp.leftContext;

  if ( left.substr( left.length - 1 ) !== "\\" ) {
  match[1] = (match[1] || "").replace(/\\/g, "");
  set = Expr.find[ type ]( match, context, isXML );
  if ( set != null ) {
  expr = expr.replace( Expr.match[ type ], "" );
  break;
  }
  }
  }
  }

  if ( !set ) {
  set = context.getElementsByTagName("*");
  }

  return {set: set, expr: expr};
};

Sizzle.filter = function(expr, set, inplace, not){
  var old = expr, result = [], curLoop = set, match, anyFound,
  isXMLFilter = set && set[0] && isXML(set[0]);

  while ( expr && set.length ) {
  for ( var type in Expr.filter ) {
  if ( (match = Expr.match[ type ].exec( expr )) != null ) {
  var filter = Expr.filter[ type ], found, item;
  anyFound = false;

  if ( curLoop == result ) {
  result = [];
  }

  if ( Expr.preFilter[ type ] ) {
  match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );

  if ( !match ) {
  anyFound = found = true;
  } else if ( match === true ) {
  continue;
  }
  }

  if ( match ) {
  for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
  if ( item ) {
  found = filter( item, match, i, curLoop );
  var pass = not ^ !!found;

  if ( inplace && found != null ) {
  if ( pass ) {
  anyFound = true;
  } else {
  curLoop[i] = false;
  }
  } else if ( pass ) {
  result.push( item );
  anyFound = true;
  }
  }
  }
  }

  if ( found !== undefined ) {
  if ( !inplace ) {
  curLoop = result;
  }

  expr = expr.replace( Expr.match[ type ], "" );

  if ( !anyFound ) {
  return [];
  }

  break;
  }
  }
  }

  // Improper expression
  if ( expr == old ) {
  if ( anyFound == null ) {
  throw "Syntax error, unrecognized expression: " + expr;
  } else {
  break;
  }
  }

  old = expr;
  }

  return curLoop;
};

var Expr = Sizzle.selectors = {
  order: [ "ID", "NAME", "TAG" ],
  match: {
  ID: /#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,
  CLASS: /\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,
  NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,
  ATTR: /\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,
  TAG: /^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,
  CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,
  POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,
  PSEUDO: /:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/
  },
  attrMap: {
  "class": "className",
  "for": "htmlFor"
  },
  attrHandle: {
  href: function(elem){
  return elem.getAttribute("href");
  }
  },
  relative: {
  "+": function(checkSet, part, isXML){
  var isPartStr = typeof part === "string",
  isTag = isPartStr && !/\W/.test(part),
  isPartStrNotTag = isPartStr && !isTag;

  if ( isTag && !isXML ) {
  part = part.toUpperCase();
  }

  for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
  if ( (elem = checkSet[i]) ) {
  while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}

  checkSet[i] = isPartStrNotTag || elem && elem.nodeName === part ?
  elem || false :
  elem === part;
  }
  }

  if ( isPartStrNotTag ) {
  Sizzle.filter( part, checkSet, true );
  }
  },
  ">": function(checkSet, part, isXML){
  var isPartStr = typeof part === "string";

  if ( isPartStr && !/\W/.test(part) ) {
  part = isXML ? part : part.toUpperCase();

  for ( var i = 0, l = checkSet.length; i < l; i++ ) {
  var elem = checkSet[i];
  if ( elem ) {
  var parent = elem.parentNode;
  checkSet[i] = parent.nodeName === part ? parent : false;
  }
  }
  } else {
  for ( var i = 0, l = checkSet.length; i < l; i++ ) {
  var elem = checkSet[i];
  if ( elem ) {
  checkSet[i] = isPartStr ?
  elem.parentNode :
  elem.parentNode === part;
  }
  }

  if ( isPartStr ) {
  Sizzle.filter( part, checkSet, true );
  }
  }
  },
  "": function(checkSet, part, isXML){
  var doneName = done++, checkFn = dirCheck;

  if ( !part.match(/\W/) ) {
  var nodeCheck = part = isXML ? part : part.toUpperCase();
  checkFn = dirNodeCheck;
  }

  checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML);
  },
  "~": function(checkSet, part, isXML){
  var doneName = done++, checkFn = dirCheck;

  if ( typeof part === "string" && !part.match(/\W/) ) {
  var nodeCheck = part = isXML ? part : part.toUpperCase();
  checkFn = dirNodeCheck;
  }

  checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML);
  }
  },
  find: {
  ID: function(match, context, isXML){
  if ( typeof context.getElementById !== "undefined" && !isXML ) {
  var m = context.getElementById(match[1]);
  return m ? [m] : [];
  }
  },
  NAME: function(match, context, isXML){
  if ( typeof context.getElementsByName !== "undefined" ) {
  var ret = [], results = context.getElementsByName(match[1]);

  for ( var i = 0, l = results.length; i < l; i++ ) {
  if ( results[i].getAttribute("name") === match[1] ) {
  ret.push( results[i] );
  }
  }

  return ret.length === 0 ? null : ret;
  }
  },
  TAG: function(match, context){
  return context.getElementsByTagName(match[1]);
  }
  },
  preFilter: {
  CLASS: function(match, curLoop, inplace, result, not, isXML){
  match = " " + match[1].replace(/\\/g, "") + " ";

  if ( isXML ) {
  return match;
  }

  for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
  if ( elem ) {
  if ( not ^ (elem.className && (" " + elem.className + " ").indexOf(match) >= 0) ) {
  if ( !inplace )
  result.push( elem );
  } else if ( inplace ) {
  curLoop[i] = false;
  }
  }
  }

  return false;
  },
  ID: function(match){
  return match[1].replace(/\\/g, "");
  },
  TAG: function(match, curLoop){
  for ( var i = 0; curLoop[i] === false; i++ ){}
  return curLoop[i] && isXML(curLoop[i]) ? match[1] : match[1].toUpperCase();
  },
  CHILD: function(match){
  if ( match[1] == "nth" ) {
  // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
  var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
  match[2] == "even" && "2n" || match[2] == "odd" && "2n+1" ||
  !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);

  // calculate the numbers (first)n+(last) including if they are negative
  match[2] = (test[1] + (test[2] || 1)) - 0;
  match[3] = test[3] - 0;
  }

  // TODO: Move to normal caching system
  match[0] = done++;

  return match;
  },
  ATTR: function(match, curLoop, inplace, result, not, isXML){
  var name = match[1].replace(/\\/g, "");
  
  if ( !isXML && Expr.attrMap[name] ) {
  match[1] = Expr.attrMap[name];
  }

  if ( match[2] === "~=" ) {
  match[4] = " " + match[4] + " ";
  }

  return match;
  },
  PSEUDO: function(match, curLoop, inplace, result, not){
  if ( match[1] === "not" ) {
  // If we're dealing with a complex expression, or a simple one
  if ( match[3].match(chunker).length > 1 || /^\w/.test(match[3]) ) {
  match[3] = Sizzle(match[3], null, null, curLoop);
  } else {
  var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
  if ( !inplace ) {
  result.push.apply( result, ret );
  }
  return false;
  }
  } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
  return true;
  }
  
  return match;
  },
  POS: function(match){
  match.unshift( true );
  return match;
  }
  },
  filters: {
  enabled: function(elem){
  return elem.disabled === false && elem.type !== "hidden";
  },
  disabled: function(elem){
  return elem.disabled === true;
  },
  checked: function(elem){
  return elem.checked === true;
  },
  selected: function(elem){
  // Accessing this property makes selected-by-default
  // options in Safari work properly
  elem.parentNode.selectedIndex;
  return elem.selected === true;
  },
  parent: function(elem){
  return !!elem.firstChild;
  },
  empty: function(elem){
  return !elem.firstChild;
  },
  has: function(elem, i, match){
  return !!Sizzle( match[3], elem ).length;
  },
  header: function(elem){
  return /h\d/i.test( elem.nodeName );
  },
  text: function(elem){
  return "text" === elem.type;
  },
  radio: function(elem){
  return "radio" === elem.type;
  },
  checkbox: function(elem){
  return "checkbox" === elem.type;
  },
  file: function(elem){
  return "file" === elem.type;
  },
  password: function(elem){
  return "password" === elem.type;
  },
  submit: function(elem){
  return "submit" === elem.type;
  },
  image: function(elem){
  return "image" === elem.type;
  },
  reset: function(elem){
  return "reset" === elem.type;
  },
  button: function(elem){
  return "button" === elem.type || elem.nodeName.toUpperCase() === "BUTTON";
  },
  input: function(elem){
  return /input|select|textarea|button/i.test(elem.nodeName);
  }
  },
  setFilters: {
  first: function(elem, i){
  return i === 0;
  },
  last: function(elem, i, match, array){
  return i === array.length - 1;
  },
  even: function(elem, i){
  return i % 2 === 0;
  },
  odd: function(elem, i){
  return i % 2 === 1;
  },
  lt: function(elem, i, match){
  return i < match[3] - 0;
  },
  gt: function(elem, i, match){
  return i > match[3] - 0;
  },
  nth: function(elem, i, match){
  return match[3] - 0 == i;
  },
  eq: function(elem, i, match){
  return match[3] - 0 == i;
  }
  },
  filter: {
  PSEUDO: function(elem, match, i, array){
  var name = match[1], filter = Expr.filters[ name ];

  if ( filter ) {
  return filter( elem, i, match, array );
  } else if ( name === "contains" ) {
  return (elem.textContent || elem.innerText || "").indexOf(match[3]) >= 0;
  } else if ( name === "not" ) {
  var not = match[3];

  for ( var i = 0, l = not.length; i < l; i++ ) {
  if ( not[i] === elem ) {
  return false;
  }
  }

  return true;
  }
  },
  CHILD: function(elem, match){
  var type = match[1], node = elem;
  switch (type) {
  case 'only':
  case 'first':
  while (node = node.previousSibling)  {
  if ( node.nodeType === 1 ) return false;
  }
  if ( type == 'first') return true;
  node = elem;
  case 'last':
  while (node = node.nextSibling)  {
  if ( node.nodeType === 1 ) return false;
  }
  return true;
  case 'nth':
  var first = match[2], last = match[3];

  if ( first == 1 && last == 0 ) {
  return true;
  }
  
  var doneName = match[0],
  parent = elem.parentNode;
  
  if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
  var count = 0;
  for ( node = parent.firstChild; node; node = node.nextSibling ) {
  if ( node.nodeType === 1 ) {
  node.nodeIndex = ++count;
  }
  } 
  parent.sizcache = doneName;
  }
  
  var diff = elem.nodeIndex - last;
  if ( first == 0 ) {
  return diff == 0;
  } else {
  return ( diff % first == 0 && diff / first >= 0 );
  }
  }
  },
  ID: function(elem, match){
  return elem.nodeType === 1 && elem.getAttribute("id") === match;
  },
  TAG: function(elem, match){
  return (match === "*" && elem.nodeType === 1) || elem.nodeName === match;
  },
  CLASS: function(elem, match){
  return (" " + (elem.className || elem.getAttribute("class")) + " ")
  .indexOf( match ) > -1;
  },
  ATTR: function(elem, match){
  var name = match[1],
  result = Expr.attrHandle[ name ] ?
  Expr.attrHandle[ name ]( elem ) :
  elem[ name ] != null ?
  elem[ name ] :
  elem.getAttribute( name ),
  value = result + "",
  type = match[2],
  check = match[4];

  return result == null ?
  type === "!=" :
  type === "=" ?
  value === check :
  type === "*=" ?
  value.indexOf(check) >= 0 :
  type === "~=" ?
  (" " + value + " ").indexOf(check) >= 0 :
  !check ?
  value && result !== false :
  type === "!=" ?
  value != check :
  type === "^=" ?
  value.indexOf(check) === 0 :
  type === "$=" ?
  value.substr(value.length - check.length) === check :
  type === "|=" ?
  value === check || value.substr(0, check.length + 1) === check + "-" :
  false;
  },
  POS: function(elem, match, i, array){
  var name = match[2], filter = Expr.setFilters[ name ];

  if ( filter ) {
  return filter( elem, i, match, array );
  }
  }
  }
};

var origPOS = Expr.match.POS;

for ( var type in Expr.match ) {
  Expr.match[ type ] = RegExp( Expr.match[ type ].source + /(?![^\[]*\])(?![^\(]*\))/.source );
}

var makeArray = function(array, results) {
  array = Array.prototype.slice.call( array );

  if ( results ) {
  results.push.apply( results, array );
  return results;
  }
  
  return array;
};

// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
try {
  Array.prototype.slice.call( document.documentElement.childNodes );

// Provide a fallback method if it does not work
} catch(e){
  makeArray = function(array, results) {
  var ret = results || [];

  if ( toString.call(array) === "[object Array]" ) {
  Array.prototype.push.apply( ret, array );
  } else {
  if ( typeof array.length === "number" ) {
  for ( var i = 0, l = array.length; i < l; i++ ) {
  ret.push( array[i] );
  }
  } else {
  for ( var i = 0; array[i]; i++ ) {
  ret.push( array[i] );
  }
  }
  }

  return ret;
  };
}

var sortOrder;

if ( document.documentElement.compareDocumentPosition ) {
  sortOrder = function( a, b ) {
  var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1;
  if ( ret === 0 ) {
  hasDuplicate = true;
  }
  return ret;
  };
} else if ( "sourceIndex" in document.documentElement ) {
  sortOrder = function( a, b ) {
  var ret = a.sourceIndex - b.sourceIndex;
  if ( ret === 0 ) {
  hasDuplicate = true;
  }
  return ret;
  };
} else if ( document.createRange ) {
  sortOrder = function( a, b ) {
  var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange();
  aRange.selectNode(a);
  aRange.collapse(true);
  bRange.selectNode(b);
  bRange.collapse(true);
  var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange);
  if ( ret === 0 ) {
  hasDuplicate = true;
  }
  return ret;
  };
}

// Check to see if the browser returns elements by name when
// querying by getElementById (and provide a workaround)
(function(){
  // We're going to inject a fake input element with a specified name
  var form = document.createElement("form"),
  id = "script" + (new Date).getTime();
  form.innerHTML = "<input name='" + id + "'/>";

  // Inject it into the root element, check its status, and remove it quickly
  var root = document.documentElement;
  root.insertBefore( form, root.firstChild );

  // The workaround has to do additional checks after a getElementById
  // Which slows things down for other browsers (hence the branching)
  if ( !!document.getElementById( id ) ) {
  Expr.find.ID = function(match, context, isXML){
  if ( typeof context.getElementById !== "undefined" && !isXML ) {
  var m = context.getElementById(match[1]);
  return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : [];
  }
  };

  Expr.filter.ID = function(elem, match){
  var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
  return elem.nodeType === 1 && node && node.nodeValue === match;
  };
  }

  root.removeChild( form );
})();

(function(){
  // Check to see if the browser returns only elements
  // when doing getElementsByTagName("*")

  // Create a fake element
  var div = document.createElement("div");
  div.appendChild( document.createComment("") );

  // Make sure no comments are found
  if ( div.getElementsByTagName("*").length > 0 ) {
  Expr.find.TAG = function(match, context){
  var results = context.getElementsByTagName(match[1]);

  // Filter out possible comments
  if ( match[1] === "*" ) {
  var tmp = [];

  for ( var i = 0; results[i]; i++ ) {
  if ( results[i].nodeType === 1 ) {
  tmp.push( results[i] );
  }
  }

  results = tmp;
  }

  return results;
  };
  }

  // Check to see if an attribute returns normalized href attributes
  div.innerHTML = "<a href='#'></a>";
  if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
  div.firstChild.getAttribute("href") !== "#" ) {
  Expr.attrHandle.href = function(elem){
  return elem.getAttribute("href", 2);
  };
  }
})();

if ( document.querySelectorAll ) (function(){
  var oldSizzle = Sizzle, div = document.createElement("div");
  div.innerHTML = "<p class='TEST'></p>";

  // Safari can't handle uppercase or unicode characters when
  // in quirks mode.
  if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
  return;
  }
  
  Sizzle = function(query, context, extra, seed){
  context = context || document;

  // Only use querySelectorAll on non-XML documents
  // (ID selectors don't work in non-HTML documents)
  if ( !seed && context.nodeType === 9 && !isXML(context) ) {
  try {
  return makeArray( context.querySelectorAll(query), extra );
  } catch(e){}
  }
  
  return oldSizzle(query, context, extra, seed);
  };

  Sizzle.find = oldSizzle.find;
  Sizzle.filter = oldSizzle.filter;
  Sizzle.selectors = oldSizzle.selectors;
  Sizzle.matches = oldSizzle.matches;
})();

if ( document.getElementsByClassName && document.documentElement.getElementsByClassName ) (function(){
  var div = document.createElement("div");
  div.innerHTML = "<div class='test e'></div><div class='test'></div>";

  // Opera can't find a second classname (in 9.6)
  if ( div.getElementsByClassName("e").length === 0 )
  return;

  // Safari caches class attributes, doesn't catch changes (in 3.2)
  div.lastChild.className = "e";

  if ( div.getElementsByClassName("e").length === 1 )
  return;

  Expr.order.splice(1, 0, "CLASS");
  Expr.find.CLASS = function(match, context, isXML) {
  if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
  return context.getElementsByClassName(match[1]);
  }
  };
})();

function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
  var sibDir = dir == "previousSibling" && !isXML;
  for ( var i = 0, l = checkSet.length; i < l; i++ ) {
  var elem = checkSet[i];
  if ( elem ) {
  if ( sibDir && elem.nodeType === 1 ){
  elem.sizcache = doneName;
  elem.sizset = i;
  }
  elem = elem[dir];
  var match = false;

  while ( elem ) {
  if ( elem.sizcache === doneName ) {
  match = checkSet[elem.sizset];
  break;
  }

  if ( elem.nodeType === 1 && !isXML ){
  elem.sizcache = doneName;
  elem.sizset = i;
  }

  if ( elem.nodeName === cur ) {
  match = elem;
  break;
  }

  elem = elem[dir];
  }

  checkSet[i] = match;
  }
  }
}

function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
  var sibDir = dir == "previousSibling" && !isXML;
  for ( var i = 0, l = checkSet.length; i < l; i++ ) {
  var elem = checkSet[i];
  if ( elem ) {
  if ( sibDir && elem.nodeType === 1 ) {
  elem.sizcache = doneName;
  elem.sizset = i;
  }
  elem = elem[dir];
  var match = false;

  while ( elem ) {
  if ( elem.sizcache === doneName ) {
  match = checkSet[elem.sizset];
  break;
  }

  if ( elem.nodeType === 1 ) {
  if ( !isXML ) {
  elem.sizcache = doneName;
  elem.sizset = i;
  }
  if ( typeof cur !== "string" ) {
  if ( elem === cur ) {
  match = true;
  break;
  }

  } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
  match = elem;
  break;
  }
  }

  elem = elem[dir];
  }

  checkSet[i] = match;
  }
  }
}

var contains = document.compareDocumentPosition ?  function(a, b){
  return a.compareDocumentPosition(b) & 16;
} : function(a, b){
  return a !== b && (a.contains ? a.contains(b) : true);
};

var isXML = function(elem){
  return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" ||
  !!elem.ownerDocument && isXML( elem.ownerDocument );
};

var posProcess = function(selector, context){
  var tmpSet = [], later = "", match,
  root = context.nodeType ? [context] : context;

  // Position selectors must be done after the filter
  // And so must :not(positional) so we move all PSEUDOs to the end
  while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
  later += match[0];
  selector = selector.replace( Expr.match.PSEUDO, "" );
  }

  selector = Expr.relative[selector] ? selector + "*" : selector;

  for ( var i = 0, l = root.length; i < l; i++ ) {
  Sizzle( selector, root[i], tmpSet );
  }

  return Sizzle.filter( later, tmpSet );
};

// EXPOSE
jQuery.find = Sizzle;
jQuery.filter = Sizzle.filter;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;

Sizzle.selectors.filters.hidden = function(elem){
  return elem.offsetWidth === 0 || elem.offsetHeight === 0;
};

Sizzle.selectors.filters.visible = function(elem){
  return elem.offsetWidth > 0 || elem.offsetHeight > 0;
};

Sizzle.selectors.filters.animated = function(elem){
  return jQuery.grep(jQuery.timers, function(fn){
  return elem === fn.elem;
  }).length;
};

jQuery.multiFilter = function( expr, elems, not ) {
  if ( not ) {
  expr = ":not(" + expr + ")";
  }

  return Sizzle.matches(expr, elems);
};

jQuery.dir = function( elem, dir ){
  var matched = [], cur = elem[dir];
  while ( cur && cur != document ) {
  if ( cur.nodeType == 1 )
  matched.push( cur );
  cur = cur[dir];
  }
  return matched;
};

jQuery.nth = function(cur, result, dir, elem){
  result = result || 1;
  var num = 0;

  for ( ; cur; cur = cur[dir] )
  if ( cur.nodeType == 1 && ++num == result )
  break;

  return cur;
};

jQuery.sibling = function(n, elem){
  var r = [];

  for ( ; n; n = n.nextSibling ) {
  if ( n.nodeType == 1 && n != elem )
  r.push( n );
  }

  return r;
};

return;

window.Sizzle = Sizzle;

})();
/*
 * A number of helper functions used for managing events.
 * Many of the ideas behind this code originated from
 * Dean Edwards' addEvent library.
 */
jQuery.event = {

  // Bind an event to an element
  // Original by Dean Edwards
  add: function(elem, types, handler, data) {
  if ( elem.nodeType == 3 || elem.nodeType == 8 )
  return;

  // For whatever reason, IE has trouble passing the window object
  // around, causing it to be cloned in the process
  if ( elem.setInterval && elem != window )
  elem = window;

  // Make sure that the function being executed has a unique ID
  if ( !handler.guid )
  handler.guid = this.guid++;

  // if data is passed, bind to handler
  if ( data !== undefined ) {
  // Create temporary function pointer to original handler
  var fn = handler;

  // Create unique handler function, wrapped around original handler
  handler = this.proxy( fn );

  // Store data in unique handler
  handler.data = data;
  }

  // Init the element's event structure
  var events = jQuery.data(elem, "events") || jQuery.data(elem, "events", {}),
  handle = jQuery.data(elem, "handle") || jQuery.data(elem, "handle", function(){
  // Handle the second event of a trigger and when
  // an event is called after a page has unloaded
  return typeof jQuery !== "undefined" && !jQuery.event.triggered ?
  jQuery.event.handle.apply(arguments.callee.elem, arguments) :
  undefined;
  });
  // Add elem as a property of the handle function
  // This is to prevent a memory leak with non-native
  // event in IE.
  handle.elem = elem;

  // Handle multiple events separated by a space
  // jQuery(...).bind("mouseover mouseout", fn);
  jQuery.each(types.split(/\s+/), function(index, type) {
  // Namespaced event handlers
  var namespaces = type.split(".");
  type = namespaces.shift();
  handler.type = namespaces.slice().sort().join(".");

  // Get the current list of functions bound to this event
  var handlers = events[type];
  
  if ( jQuery.event.specialAll[type] )
  jQuery.event.specialAll[type].setup.call(elem, data, namespaces);

  // Init the event handler queue
  if (!handlers) {
  handlers = events[type] = {};

  // Check for a special event handler
  // Only use addEventListener/attachEvent if the special
  // events handler returns false
  if ( !jQuery.event.special[type] || jQuery.event.special[type].setup.call(elem, data, namespaces) === false ) {
  // Bind the global event handler to the element
  if (elem.addEventListener)
  elem.addEventListener(type, handle, false);
  else if (elem.attachEvent)
  elem.attachEvent("on" + type, handle);
  }
  }

  // Add the function to the element's handler list
  handlers[handler.guid] = handler;

  // Keep track of which events have been used, for global triggering
  jQuery.event.global[type] = true;
  });

  // Nullify elem to prevent memory leaks in IE
  elem = null;
  },

  guid: 1,
  global: {},

  // Detach an event or set of events from an element
  remove: function(elem, types, handler) {
  // don't do events on text and comment nodes
  if ( elem.nodeType == 3 || elem.nodeType == 8 )
  return;

  var events = jQuery.data(elem, "events"), ret, index;

  if ( events ) {
  // Unbind all events for the element
  if ( types === undefined || (typeof types === "string" && types.charAt(0) == ".") )
  for ( var type in events )
  this.remove( elem, type + (types || "") );
  else {
  // types is actually an event object here
  if ( types.type ) {
  handler = types.handler;
  types = types.type;
  }

  // Handle multiple events seperated by a space
  // jQuery(...).unbind("mouseover mouseout", fn);
  jQuery.each(types.split(/\s+/), function(index, type){
  // Namespaced event handlers
  var namespaces = type.split(".");
  type = namespaces.shift();
  var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");

  if ( events[type] ) {
  // remove the given handler for the given type
  if ( handler )
  delete events[type][handler.guid];

  // remove all handlers for the given type
  else
  for ( var handle in events[type] )
  // Handle the removal of namespaced events
  if ( namespace.test(events[type][handle].type) )
  delete events[type][handle];
  
  if ( jQuery.event.specialAll[type] )
  jQuery.event.specialAll[type].teardown.call(elem, namespaces);

  // remove generic event handler if no more handlers exist
  for ( ret in events[type] ) break;
  if ( !ret ) {
  if ( !jQuery.event.special[type] || jQuery.event.special[type].teardown.call(elem, namespaces) === false ) {
  if (elem.removeEventListener)
  elem.removeEventListener(type, jQuery.data(elem, "handle"), false);
  else if (elem.detachEvent)
  elem.detachEvent("on" + type, jQuery.data(elem, "handle"));
  }
  ret = null;
  delete events[type];
  }
  }
  });
  }

  // Remove the expando if it's no longer used
  for ( ret in events ) break;
  if ( !ret ) {
  var handle = jQuery.data( elem, "handle" );
  if ( handle ) handle.elem = null;
  jQuery.removeData( elem, "events" );
  jQuery.removeData( elem, "handle" );
  }
  }
  },

  // bubbling is internal
  trigger: function( event, data, elem, bubbling ) {
  // Event object or event type
  var type = event.type || event;

  if( !bubbling ){
  event = typeof event === "object" ?
  // jQuery.Event object
  event[expando] ? event :
  // Object literal
  jQuery.extend( jQuery.Event(type), event ) :
  // Just the event type (string)
  jQuery.Event(type);

  if ( type.indexOf("!") >= 0 ) {
  event.type = type = type.slice(0, -1);
  event.exclusive = true;
  }

  // Handle a global trigger
  if ( !elem ) {
  // Don't bubble custom events when global (to avoid too much overhead)
  event.stopPropagation();
  // Only trigger if we've ever bound an event for it
  if ( this.global[type] )
  jQuery.each( jQuery.cache, function(){
  if ( this.events && this.events[type] )
  jQuery.event.trigger( event, data, this.handle.elem );
  });
  }

  // Handle triggering a single element

  // don't do events on text and comment nodes
  if ( !elem || elem.nodeType == 3 || elem.nodeType == 8 )
  return undefined;
  
  // Clean up in case it is reused
  event.result = undefined;
  event.target = elem;
  
  // Clone the incoming data, if any
  data = jQuery.makeArray(data);
  data.unshift( event );
  }

  event.currentTarget = elem;

  // Trigger the event, it is assumed that "handle" is a function
  var handle = jQuery.data(elem, "handle");
  if ( handle )
  handle.apply( elem, data );

  // Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
  if ( (!elem[type] || (jQuery.nodeName(elem, 'a') && type == "click")) && elem["on"+type] && elem["on"+type].apply( elem, data ) === false )
  event.result = false;

  // Trigger the native events (except for clicks on links)
  if ( !bubbling && elem[type] && !event.isDefaultPrevented() && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
  this.triggered = true;
  try {
  elem[ type ]();
  // prevent IE from throwing an error for some hidden elements
  } catch (e) {}
  }

  this.triggered = false;

  if ( !event.isPropagationStopped() ) {
  var parent = elem.parentNode || elem.ownerDocument;
  if ( parent )
  jQuery.event.trigger(event, data, parent, true);
  }
  },

  handle: function(event) {
  // returned undefined or false
  var all, handlers;

  event = arguments[0] = jQuery.event.fix( event || window.event );
  event.currentTarget = this;
  
  // Namespaced event handlers
  var namespaces = event.type.split(".");
  event.type = namespaces.shift();

  // Cache this now, all = true means, any handler
  all = !namespaces.length && !event.exclusive;
  
  var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");

  handlers = ( jQuery.data(this, "events") || {} )[event.type];

  for ( var j in handlers ) {
  var handler = handlers[j];

  // Filter the functions by class
  if ( all || namespace.test(handler.type) ) {
  // Pass in a reference to the handler function itself
  // So that we can later remove it
  event.handler = handler;
  event.data = handler.data;

  var ret = handler.apply(this, arguments);

  if( ret !== undefined ){
  event.result = ret;
  if ( ret === false ) {
  event.preventDefault();
  event.stopPropagation();
  }
  }

  if( event.isImmediatePropagationStopped() )
  break;

  }
  }
  },

  props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),

  fix: function(event) {
  if ( event[expando] )
  return event;

  // store a copy of the original event object
  // and "clone" to set read-only properties
  var originalEvent = event;
  event = jQuery.Event( originalEvent );

  for ( var i = this.props.length, prop; i; ){
  prop = this.props[ --i ];
  event[ prop ] = originalEvent[ prop ];
  }

  // Fix target property, if necessary
  if ( !event.target )
  event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either

  // check if target is a textnode (safari)
  if ( event.target.nodeType == 3 )
  event.target = event.target.parentNode;

  // Add relatedTarget, if necessary
  if ( !event.relatedTarget && event.fromElement )
  event.relatedTarget = event.fromElement == event.target ? event.toElement : event.fromElement;

  // Calculate pageX/Y if missing and clientX/Y available
  if ( event.pageX == null && event.clientX != null ) {
  var doc = document.documentElement, body = document.body;
  event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc.clientLeft || 0);
  event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc.clientTop || 0);
  }

  // Add which for key events
  if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) )
  event.which = event.charCode || event.keyCode;

  // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
  if ( !event.metaKey && event.ctrlKey )
  event.metaKey = event.ctrlKey;

  // Add which for click: 1 == left; 2 == middle; 3 == right
  // Note: button is not normalized, so don't use it
  if ( !event.which && event.button )
  event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));

  return event;
  },

  proxy: function( fn, proxy ){
  proxy = proxy || function(){ return fn.apply(this, arguments); };
  // Set the guid of unique handler to the same of original handler, so it can be removed
  proxy.guid = fn.guid = fn.guid || proxy.guid || this.guid++;
  // So proxy can be declared as an argument
  return proxy;
  },

  special: {
  ready: {
  // Make sure the ready event is setup
  setup: bindReady,
  teardown: function() {}
  }
  },
  
  specialAll: {
  live: {
  setup: function( selector, namespaces ){
  jQuery.event.add( this, namespaces[0], liveHandler );
  },
  teardown:  function( namespaces ){
  if ( namespaces.length ) {
  var remove = 0, name = RegExp("(^|\\.)" + namespaces[0] + "(\\.|$)");
  
  jQuery.each( (jQuery.data(this, "events").live || {}), function(){
  if ( name.test(this.type) )
  remove++;
  });
  
  if ( remove < 1 )
  jQuery.event.remove( this, namespaces[0], liveHandler );
  }
  }
  }
  }
};

jQuery.Event = function( src ){
  // Allow instantiation without the 'new' keyword
  if( !this.preventDefault )
  return new jQuery.Event(src);
  
  // Event object
  if( src && src.type ){
  this.originalEvent = src;
  this.type = src.type;
  // Event type
  }else
  this.type = src;

  // timeStamp is buggy for some events on Firefox(#3843)
  // So we won't rely on the native value
  this.timeStamp = now();
  
  // Mark it as fixed
  this[expando] = true;
};

function returnFalse(){
  return false;
}
function returnTrue(){
  return true;
}

// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
  preventDefault: function() {
  this.isDefaultPrevented = returnTrue;

  var e = this.originalEvent;
  if( !e )
  return;
  // if preventDefault exists run it on the original event
  if (e.preventDefault)
  e.preventDefault();
  // otherwise set the returnValue property of the original event to false (IE)
  e.returnValue = false;
  },
  stopPropagation: function() {
  this.isPropagationStopped = returnTrue;

  var e = this.originalEvent;
  if( !e )
  return;
  // if stopPropagation exists run it on the original event
  if (e.stopPropagation)
  e.stopPropagation();
  // otherwise set the cancelBubble property of the original event to true (IE)
  e.cancelBubble = true;
  },
  stopImmediatePropagation:function(){
  this.isImmediatePropagationStopped = returnTrue;
  this.stopPropagation();
  },
  isDefaultPrevented: returnFalse,
  isPropagationStopped: returnFalse,
  isImmediatePropagationStopped: returnFalse
};
// Checks if an event happened on an element within another element
// Used in jQuery.event.special.mouseenter and mouseleave handlers
var withinElement = function(event) {
  // Check if mouse(over|out) are still within the same parent element
  var parent = event.relatedTarget;
  // Traverse up the tree
  while ( parent && parent != this )
  try { parent = parent.parentNode; }
  catch(e) { parent = this; }
  
  if( parent != this ){
  // set the correct event type
  event.type = event.data;
  // handle event if we actually just moused on to a non sub-element
  jQuery.event.handle.apply( this, arguments );
  }
};
  
jQuery.each({ 
  mouseover: 'mouseenter', 
  mouseout: 'mouseleave'
}, function( orig, fix ){
  jQuery.event.special[ fix ] = {
  setup: function(){
  jQuery.event.add( this, orig, withinElement, fix );
  },
  teardown: function(){
  jQuery.event.remove( this, orig, withinElement );
  }
  }; 
});

jQuery.fn.extend({
  bind: function( type, data, fn ) {
  return type == "unload" ? this.one(type, data, fn) : this.each(function(){
  jQuery.event.add( this, type, fn || data, fn && data );
  });
  },

  one: function( type, data, fn ) {
  var one = jQuery.event.proxy( fn || data, function(event) {
  jQuery(this).unbind(event, one);
  return (fn || data).apply( this, arguments );
  });
  return this.each(function(){
  jQuery.event.add( this, type, one, fn && data);
  });
  },

  unbind: function( type, fn ) {
  return this.each(function(){
  jQuery.event.remove( this, type, fn );
  });
  },

  trigger: function( type, data ) {
  return this.each(function(){
  jQuery.event.trigger( type, data, this );
  });
  },

  triggerHandler: function( type, data ) {
  if( this[0] ){
  var event = jQuery.Event(type);
  event.preventDefault();
  event.stopPropagation();
  jQuery.event.trigger( event, data, this[0] );
  return event.result;
  }  
  },

  toggle: function( fn ) {
  // Save reference to arguments for access in closure
  var args = arguments, i = 1;

  // link all the functions, so any of them can unbind this click handler
  while( i < args.length )
  jQuery.event.proxy( fn, args[i++] );

  return this.click( jQuery.event.proxy( fn, function(event) {
  // Figure out which function to execute
  this.lastToggle = ( this.lastToggle || 0 ) % i;

  // Make sure that clicks stop
  event.preventDefault();

  // and execute the function
  return args[ this.lastToggle++ ].apply( this, arguments ) || false;
  }));
  },

  hover: function(fnOver, fnOut) {
  return this.mouseenter(fnOver).mouseleave(fnOut);
  },

  ready: function(fn) {
  // Attach the listeners
  bindReady();

  // If the DOM is already ready
  if ( jQuery.isReady )
  // Execute the function immediately
  fn.call( document, jQuery );

  // Otherwise, remember the function for later
  else
  // Add the function to the wait list
  jQuery.readyList.push( fn );

  return this;
  },
  
  live: function( type, fn ){
  var proxy = jQuery.event.proxy( fn );
  proxy.guid += this.selector + type;

  jQuery(document).bind( liveConvert(type, this.selector), this.selector, proxy );

  return this;
  },
  
  die: function( type, fn ){
  jQuery(document).unbind( liveConvert(type, this.selector), fn ? { guid: fn.guid + this.selector + type } : null );
  return this;
  }
});

function liveHandler( event ){
  var check = RegExp("(^|\\.)" + event.type + "(\\.|$)"),
  stop = true,
  elems = [];

  jQuery.each(jQuery.data(this, "events").live || [], function(i, fn){
  if ( check.test(fn.type) ) {
  var elem = jQuery(event.target).closest(fn.data)[0];
  if ( elem )
  elems.push({ elem: elem, fn: fn });
  }
  });

  elems.sort(function(a,b) {
  return jQuery.data(a.elem, "closest") - jQuery.data(b.elem, "closest");
  });
  
  jQuery.each(elems, function(){
  if ( this.fn.call(this.elem, event, this.fn.data) === false )
  return (stop = false);
  });

  return stop;
}

function liveConvert(type, selector){
  return ["live", type, selector.replace(/\./g, "`").replace(/ /g, "|")].join(".");
}

jQuery.extend({
  isReady: false,
  readyList: [],
  // Handle when the DOM is ready
  ready: function() {
  // Make sure that the DOM is not already loaded
  if ( !jQuery.isReady ) {
  // Remember that the DOM is ready
  jQuery.isReady = true;

  // If there are functions bound, to execute
  if ( jQuery.readyList ) {
  // Execute all of them
  jQuery.each( jQuery.readyList, function(){
  this.call( document, jQuery );
  });

  // Reset the list of functions
  jQuery.readyList = null;
  }

  // Trigger any bound ready events
  jQuery(document).triggerHandler("ready");
  }
  }
});

var readyBound = false;

function bindReady(){
  if ( readyBound ) return;
  readyBound = true;

  // Mozilla, Opera and webkit nightlies currently support this event
  if ( document.addEventListener ) {
  // Use the handy event callback
  document.addEventListener( "DOMContentLoaded", function(){
  document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
  jQuery.ready();
  }, false );

  // If IE event model is used
  } else if ( document.attachEvent ) {
  // ensure firing before onload,
  // maybe late but safe also for iframes
  document.attachEvent("onreadystatechange", function(){
  if ( document.readyState === "complete" ) {
  document.detachEvent( "onreadystatechange", arguments.callee );
  jQuery.ready();
  }
  });

  // If IE and not an iframe
  // continually check to see if the document is ready
  if ( document.documentElement.doScroll && window == window.top ) (function(){
  if ( jQuery.isReady ) return;

  try {
  // If IE is used, use the trick by Diego Perini
  // http://javascript.nwbox.com/IEContentLoaded/
  document.documentElement.doScroll("left");
  } catch( error ) {
  setTimeout( arguments.callee, 0 );
  return;
  }

  // and execute any waiting functions
  jQuery.ready();
  })();
  }

  // A fallback to window.onload, that will always work
  jQuery.event.add( window, "load", jQuery.ready );
}

jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
  "mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave," +
  "change,select,submit,keydown,keypress,keyup,error").split(","), function(i, name){

  // Handle event binding
  jQuery.fn[name] = function(fn){
  return fn ? this.bind(name, fn) : this.trigger(name);
  };
});

// Prevent memory leaks in IE
// And prevent errors on refresh with events like mouseover in other browsers
// Window isn't included so as not to unbind existing unload events
jQuery( window ).bind( 'unload', function(){ 
  for ( var id in jQuery.cache )
  // Skip the window
  if ( id != 1 && jQuery.cache[ id ].handle )
  jQuery.event.remove( jQuery.cache[ id ].handle.elem );
}); 
(function(){

  jQuery.support = {};

  var root = document.documentElement,
  script = document.createElement("script"),
  div = document.createElement("div"),
  id = "script" + (new Date).getTime();

  div.style.display = "none";
  div.innerHTML = ' <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';

  var all = div.getElementsByTagName("*"),
  a = div.getElementsByTagName("a")[0];

  // Can't get basic test support
  if ( !all || !all.length || !a ) {
  return;
  }

  jQuery.support = {
  // IE strips leading whitespace when .innerHTML is used
  leadingWhitespace: div.firstChild.nodeType == 3,
  
  // Make sure that tbody elements aren't automatically inserted
  // IE will insert them into empty tables
  tbody: !div.getElementsByTagName("tbody").length,
  
  // Make sure that you can get all elements in an <object> element
  // IE 7 always returns no results
  objectAll: !!div.getElementsByTagName("object")[0]
  .getElementsByTagName("*").length,
  
  // Make sure that link elements get serialized correctly by innerHTML
  // This requires a wrapper element in IE
  htmlSerialize: !!div.getElementsByTagName("link").length,
  
  // Get the style information from getAttribute
  // (IE uses .cssText insted)
  style: /red/.test( a.getAttribute("style") ),
  
  // Make sure that URLs aren't manipulated
  // (IE normalizes it by default)
  hrefNormalized: a.getAttribute("href") === "/a",
  
  // Make sure that element opacity exists
  // (IE uses filter instead)
  opacity: a.style.opacity === "0.5",
  
  // Verify style float existence
  // (IE uses styleFloat instead of cssFloat)
  cssFloat: !!a.style.cssFloat,

  // Will be defined later
  scriptEval: false,
  noCloneEvent: true,
  boxModel: null
  };
  
  script.type = "text/javascript";
  try {
  script.appendChild( document.createTextNode( "window." + id + "=1;" ) );
  } catch(e){}

  root.insertBefore( script, root.firstChild );
  
  // Make sure that the execution of code works by injecting a script
  // tag with appendChild/createTextNode
  // (IE doesn't support this, fails, and uses .text instead)
  if ( window[ id ] ) {
  jQuery.support.scriptEval = true;
  delete window[ id ];
  }

  root.removeChild( script );

  if ( div.attachEvent && div.fireEvent ) {
  div.attachEvent("onclick", function(){
  // Cloning a node shouldn't copy over any
  // bound event handlers (IE does this)
  jQuery.support.noCloneEvent = false;
  div.detachEvent("onclick", arguments.callee);
  });
  div.cloneNode(true).fireEvent("onclick");
  }

  // Figure out if the W3C box model works as expected
  // document.body must exist before we can do this
  jQuery(function(){
  var div = document.createElement("div");
  div.style.width = div.style.paddingLeft = "1px";

  document.body.appendChild( div );
  jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2;
  document.body.removeChild( div ).style.display = 'none';
  });
})();

var styleFloat = jQuery.support.cssFloat ? "cssFloat" : "styleFloat";

jQuery.props = {
  "for": "htmlFor",
  "class": "className",
  "float": styleFloat,
  cssFloat: styleFloat,
  styleFloat: styleFloat,
  readonly: "readOnly",
  maxlength: "maxLength",
  cellspacing: "cellSpacing",
  rowspan: "rowSpan",
  tabindex: "tabIndex"
};
jQuery.fn.extend({
  // Keep a copy of the old load
  _load: jQuery.fn.load,

  load: function( url, params, callback ) {
  if ( typeof url !== "string" )
  return this._load( url );

  var off = url.indexOf(" ");
  if ( off >= 0 ) {
  var selector = url.slice(off, url.length);
  url = url.slice(0, off);
  }

  // Default to a GET request
  var type = "GET";

  // If the second parameter was provided
  if ( params )
  // If it's a function
  if ( jQuery.isFunction( params ) ) {
  // We assume that it's the callback
  callback = params;
  params = null;

  // Otherwise, build a param string
  } else if( typeof params === "object" ) {
  params = jQuery.param( params );
  type = "POST";
  }

  var self = this;

  // Request the remote document
  jQuery.ajax({
  url: url,
  type: type,
  dataType: "html",
  data: params,
  complete: function(res, status){
  // If successful, inject the HTML into all the matched elements
  if ( status == "success" || status == "notmodified" )
  // See if a selector was specified
  self.html( selector ?
  // Create a dummy div to hold the results
  jQuery("<div/>")
  // inject the contents of the document in, removing the scripts
  // to avoid any 'Permission Denied' errors in IE
  .append(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))

  // Locate the specified elements
  .find(selector) :

  // If not, just inject the full result
  res.responseText );

  if( callback )
  self.each( callback, [res.responseText, status, res] );
  }
  });
  return this;
  },

  serialize: function() {
  return jQuery.param(this.serializeArray());
  },
  serializeArray: function() {
  return this.map(function(){
  return this.elements ? jQuery.makeArray(this.elements) : this;
  })
  .filter(function(){
  return this.name && !this.disabled &&
  (this.checked || /select|textarea/i.test(this.nodeName) ||
  /text|hidden|password|search/i.test(this.type));
  })
  .map(function(i, elem){
  var val = jQuery(this).val();
  return val == null ? null :
  jQuery.isArray(val) ?
  jQuery.map( val, function(val, i){
  return {name: elem.name, value: val};
  }) :
  {name: elem.name, value: val};
  }).get();
  }
});

// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){
  jQuery.fn[o] = function(f){
  return this.bind(o, f);
  };
});

var jsc = now();

jQuery.extend({
  
  get: function( url, data, callback, type ) {
  // shift arguments if data argument was ommited
  if ( jQuery.isFunction( data ) ) {
  callback = data;
  data = null;
  }

  return jQuery.ajax({
  type: "GET",
  url: url,
  data: data,
  success: callback,
  dataType: type
  });
  },

  getScript: function( url, callback ) {
  return jQuery.get(url, null, callback, "script");
  },

  getJSON: function( url, data, callback ) {
  return jQuery.get(url, data, callback, "json");
  },

  post: function( url, data, callback, type ) {
  if ( jQuery.isFunction( data ) ) {
  callback = data;
  data = {};
  }

  return jQuery.ajax({
  type: "POST",
  url: url,
  data: data,
  success: callback,
  dataType: type
  });
  },

  ajaxSetup: function( settings ) {
  jQuery.extend( jQuery.ajaxSettings, settings );
  },

  ajaxSettings: {
  url: location.href,
  global: true,
  type: "GET",
  contentType: "application/x-www-form-urlencoded",
  processData: true,
  async: true,
  /*
  timeout: 0,
  data: null,
  username: null,
  password: null,
  */
  // Create the request object; Microsoft failed to properly
  // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
  // This function can be overriden by calling jQuery.ajaxSetup
  xhr:function(){
  return window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
  },
  accepts: {
  xml: "application/xml, text/xml",
  html: "text/html",
  script: "text/javascript, application/javascript",
  json: "application/json, text/javascript",
  text: "text/plain",
  _default: "*/*"
  }
  },

  // Last-Modified header cache for next request
  lastModified: {},

  ajax: function( s ) {
  // Extend the settings, but re-extend 's' so that it can be
  // checked again later (in the test suite, specifically)
  s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));

  var jsonp, jsre = /=\?(&|$)/g, status, data,
  type = s.type.toUpperCase();

  // convert data if not already a string
  if ( s.data && s.processData && typeof s.data !== "string" )
  s.data = jQuery.param(s.data);

  // Handle JSONP Parameter Callbacks
  if ( s.dataType == "jsonp" ) {
  if ( type == "GET" ) {
  if ( !s.url.match(jsre) )
  s.url += (s.url.match(/\?/) ? "&" : "?") + (s.jsonp || "callback") + "=?";
  } else if ( !s.data || !s.data.match(jsre) )
  s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
  s.dataType = "json";
  }

  // Build temporary JSONP function
  if ( s.dataType == "json" && (s.data && s.data.match(jsre) || s.url.match(jsre)) ) {
  jsonp = "jsonp" + jsc++;

  // Replace the =? sequence both in the query string and the data
  if ( s.data )
  s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
  s.url = s.url.replace(jsre, "=" + jsonp + "$1");

  // We need to make sure
  // that a JSONP style response is executed properly
  s.dataType = "script";

  // Handle JSONP-style loading
  window[ jsonp ] = function(tmp){
  data = tmp;
  success();
  complete();
  // Garbage collect
  window[ jsonp ] = undefined;
  try{ delete window[ jsonp ]; } catch(e){}
  if ( head )
  head.removeChild( script );
  };
  }

  if ( s.dataType == "script" && s.cache == null )
  s.cache = false;

  if ( s.cache === false && type == "GET" ) {
  var ts = now();
  // try replacing _= if it is there
  var ret = s.url.replace(/(\?|&)_=.*?(&|$)/, "$1_=" + ts + "$2");
  // if nothing was replaced, add timestamp to the end
  s.url = ret + ((ret == s.url) ? (s.url.match(/\?/) ? "&" : "?") + "_=" + ts : "");
  }

  // If data is available, append data to url for get requests
  if ( s.data && type == "GET" ) {
  s.url += (s.url.match(/\?/) ? "&" : "?") + s.data;

  // IE likes to send both get and post data, prevent this
  s.data = null;
  }

  // Watch for a new set of requests
  if ( s.global && ! jQuery.active++ )
  jQuery.event.trigger( "ajaxStart" );

  // Matches an absolute URL, and saves the domain
  var parts = /^(\w+:)?\/\/([^\/?#]+)/.exec( s.url );

  // If we're requesting a remote document
  // and trying to load JSON or Script with a GET
  if ( s.dataType == "script" && type == "GET" && parts
  && ( parts[1] && parts[1] != location.protocol || parts[2] != location.host )){

  var head = document.getElementsByTagName("head")[0];
  var script = document.createElement("script");
  script.src = s.url;
  if (s.scriptCharset)
  script.charset = s.scriptCharset;

  // Handle Script loading
  if ( !jsonp ) {
  var done = false;

  // Attach handlers for all browsers
  script.onload = script.onreadystatechange = function(){
  if ( !done && (!this.readyState ||
  this.readyState == "loaded" || this.readyState == "complete") ) {
  done = true;
  success();
  complete();

  // Handle memory leak in IE
  script.onload = script.onreadystatechange = null;
  head.removeChild( script );
  }
  };
  }

  head.appendChild(script);

  // We handle everything using the script element injection
  return undefined;
  }

  var requestDone = false;

  // Create the request object
  var xhr = s.xhr();

  // Open the socket
  // Passing null username, generates a login popup on Opera (#2865)
  if( s.username )
  xhr.open(type, s.url, s.async, s.username, s.password);
  else
  xhr.open(type, s.url, s.async);

  // Need an extra try/catch for cross domain requests in Firefox 3
  try {
  // Set the correct header, if data is being sent
  if ( s.data )
  xhr.setRequestHeader("Content-Type", s.contentType);

  // Set the If-Modified-Since header, if ifModified mode.
  if ( s.ifModified )
  xhr.setRequestHeader("If-Modified-Since",
  jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );

  // Set header so the called script knows that it's an XMLHttpRequest
  xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");

  // Set the Accepts header for the server, depending on the dataType
  xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
  s.accepts[ s.dataType ] + ", */*" :
  s.accepts._default );
  } catch(e){}

  // Allow custom headers/mimetypes and early abort
  if ( s.beforeSend && s.beforeSend(xhr, s) === false ) {
  // Handle the global AJAX counter
  if ( s.global && ! --jQuery.active )
  jQuery.event.trigger( "ajaxStop" );
  // close opended socket
  xhr.abort();
  return false;
  }

  if ( s.global )
  jQuery.event.trigger("ajaxSend", [xhr, s]);

  // Wait for a response to come back
  var onreadystatechange = function(isTimeout){
  // The request was aborted, clear the interval and decrement jQuery.active
  if (xhr.readyState == 0) {
  if (ival) {
  // clear poll interval
  clearInterval(ival);
  ival = null;
  // Handle the global AJAX counter
  if ( s.global && ! --jQuery.active )
  jQuery.event.trigger( "ajaxStop" );
  }
  // The transfer is complete and the data is available, or the request timed out
  } else if ( !requestDone && xhr && (xhr.readyState == 4 || isTimeout == "timeout") ) {
  requestDone = true;

  // clear poll interval
  if (ival) {
  clearInterval(ival);
  ival = null;
  }

  status = isTimeout == "timeout" ? "timeout" :
  !jQuery.httpSuccess( xhr ) ? "error" :
  s.ifModified && jQuery.httpNotModified( xhr, s.url ) ? "notmodified" :
  "success";

  if ( status == "success" ) {
  // Watch for, and catch, XML document parse errors
  try {
  // process the data (runs the xml through httpData regardless of callback)
  data = jQuery.httpData( xhr, s.dataType, s );
  } catch(e) {
  status = "parsererror";
  }
  }

  // Make sure that the request was successful or notmodified
  if ( status == "success" ) {
  // Cache Last-Modified header, if ifModified mode.
  var modRes;
  try {
  modRes = xhr.getResponseHeader("Last-Modified");
  } catch(e) {} // swallow exception thrown by FF if header is not available

  if ( s.ifModified && modRes )
  jQuery.lastModified[s.url] = modRes;

  // JSONP handles its own success callback
  if ( !jsonp )
  success();
  } else
  jQuery.handleError(s, xhr, status);

  // Fire the complete handlers
  complete();

  if ( isTimeout )
  xhr.abort();

  // Stop memory leaks
  if ( s.async )
  xhr = null;
  }
  };

  if ( s.async ) {
  // don't attach the handler to the request, just poll it instead
  var ival = setInterval(onreadystatechange, 13);

  // Timeout checker
  if ( s.timeout > 0 )
  setTimeout(function(){
  // Check to see if the request is still happening
  if ( xhr && !requestDone )
  onreadystatechange( "timeout" );
  }, s.timeout);
  }

  // Send the data
  try {
  xhr.send(s.data);
  } catch(e) {
  jQuery.handleError(s, xhr, null, e);
  }

  // firefox 1.5 doesn't fire statechange for sync requests
  if ( !s.async )
  onreadystatechange();

  function success(){
  // 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", [xhr, s] );
  }

  function complete(){
  // Process result
  if ( s.complete )
  s.complete(xhr, status);

  // The request was completed
  if ( s.global )
  jQuery.event.trigger( "ajaxComplete", [xhr, s] );

  // Handle the global AJAX counter
  if ( s.global && ! --jQuery.active )
  jQuery.event.trigger( "ajaxStop" );
  }

  // return XMLHttpRequest to allow aborting the request etc.
  return xhr;
  },

  handleError: function( s, xhr, status, e ) {
  // If a local callback was specified, fire it
  if ( s.error ) s.error( xhr, status, e );

  // Fire the global callback
  if ( s.global )
  jQuery.event.trigger( "ajaxError", [xhr, s, e] );
  },

  // Counter for holding the number of active queries
  active: 0,

  // Determines if an XMLHttpRequest was successful or not
  httpSuccess: function( xhr ) {
  try {
  // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
  return !xhr.status && location.protocol == "file:" ||
  ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status == 304 || xhr.status == 1223;
  } catch(e){}
  return false;
  },

  // Determines if an XMLHttpRequest returns NotModified
  httpNotModified: function( xhr, url ) {
  try {
  var xhrRes = xhr.getResponseHeader("Last-Modified");

  // Firefox always returns 200. check Last-Modified date
  return xhr.status == 304 || xhrRes == jQuery.lastModified[url];
  } catch(e){}
  return false;
  },

  httpData: function( xhr, type, s ) {
  var ct = xhr.getResponseHeader("content-type"),
  xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0,
  data = xml ? xhr.responseXML : xhr.responseText;

  if ( xml && data.documentElement.tagName == "parsererror" )
  throw "parsererror";
  
  // Allow a pre-filtering function to sanitize the response
  // s != null is checked to keep backwards compatibility
  if( s && s.dataFilter )
  data = s.dataFilter( data, type );

  // The filter can actually parse the response
  if( typeof data === "string" ){

  // 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" )
  data = window["eval"]("(" + data + ")");
  }
  
  return data;
  },

  // Serialize an array of form elements or a set of
  // key/values into a query string
  param: function( a ) {
  var s = [ ];

  function add( key, value ){
  s[ s.length ] = encodeURIComponent(key) + '=' + encodeURIComponent(value);
  };

  // If an array was passed in, assume that it is an array
  // of form elements
  if ( jQuery.isArray(a) || a.jquery )
  // Serialize the form elements
  jQuery.each( a, function(){
  add( this.name, this.value );
  });

  // Otherwise, assume that it's an object of key/value pairs
  else
  // Serialize the key/values
  for ( var j in a )
  // If the value is an array then the key names need to be repeated
  if ( jQuery.isArray(a[j]) )
  jQuery.each( a[j], function(){
  add( j, this );
  });
  else
  add( j, jQuery.isFunction(a[j]) ? a[j]() : a[j] );

  // Return the resulting serialization
  return s.join("&").replace(/%20/g, "+");
  }

});
var elemdisplay = {},
  timerId,
  fxAttrs = [
  // height animations
  [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
  // width animations
  [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
  // opacity animations
  [ "opacity" ]
  ];

function genFx( type, num ){
  var obj = {};
  jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function(){
  obj[ this ] = type;
  });
  return obj;
}

jQuery.fn.extend({
  show: function(speed,callback){
  if ( speed ) {
  return this.animate( genFx("show", 3), speed, callback);
  } else {
  for ( var i = 0, l = this.length; i < l; i++ ){
  var old = jQuery.data(this[i], "olddisplay");
  
  this[i].style.display = old || "";
  
  if ( jQuery.css(this[i], "display") === "none" ) {
  var tagName = this[i].tagName, display;
  
  if ( elemdisplay[ tagName ] ) {
  display = elemdisplay[ tagName ];
  } else {
  var elem = jQuery("<" + tagName + " />").appendTo("body");
  
  display = elem.css("display");
  if ( display === "none" )
  display = "block";
  
  elem.remove();
  
  elemdisplay[ tagName ] = display;
  }
  
  jQuery.data(this[i], "olddisplay", display);
  }
  }

  // Set the display of the elements in a second loop
  // to avoid the constant reflow
  for ( var i = 0, l = this.length; i < l; i++ ){
  this[i].style.display = jQuery.data(this[i], "olddisplay") || "";
  }
  
  return this;
  }
  },

  hide: function(speed,callback){
  if ( speed ) {
  return this.animate( genFx("hide", 3), speed, callback);
  } else {
  for ( var i = 0, l = this.length; i < l; i++ ){
  var old = jQuery.data(this[i], "olddisplay");
  if ( !old && old !== "none" )
  jQuery.data(this[i], "olddisplay", jQuery.css(this[i], "display"));
  }

  // Set the display of the elements in a second loop
  // to avoid the constant reflow
  for ( var i = 0, l = this.length; i < l; i++ ){
  this[i].style.display = "none";
  }

  return this;
  }
  },

  // Save the old toggle function
  _toggle: jQuery.fn.toggle,

  toggle: function( fn, fn2 ){
  var bool = typeof fn === "boolean";

  return jQuery.isFunction(fn) && jQuery.isFunction(fn2) ?
  this._toggle.apply( this, arguments ) :
  fn == null || bool ?
  this.each(function(){
  var state = bool ? fn : jQuery(this).is(":hidden");
  jQuery(this)[ state ? "show" : "hide" ]();
  }) :
  this.animate(genFx("toggle", 3), fn, fn2);
  },

  fadeTo: function(speed,to,callback){
  return this.animate({opacity: to}, speed, callback);
  },

  animate: function( prop, speed, easing, callback ) {
  var optall = jQuery.speed(speed, easing, callback);

  return this[ optall.queue === false ? "each" : "queue" ](function(){
  
  var opt = jQuery.extend({}, optall), p,
  hidden = this.nodeType == 1 && jQuery(this).is(":hidden"),
  self = this;
  
  for ( p in prop ) {
  if ( prop[p] == "hide" && hidden || prop[p] == "show" && !hidden )
  return opt.complete.call(this);

  if ( ( p == "height" || p == "width" ) && this.style ) {
  // Store display property
  opt.display = jQuery.css(this, "display");

  // Make sure that nothing sneaks out
  opt.overflow = this.style.overflow;
  }
  }

  if ( opt.overflow != null )
  this.style.overflow = "hidden";

  opt.curAnim = jQuery.extend({}, prop);

  jQuery.each( prop, function(name, val){
  var e = new jQuery.fx( self, opt, name );

  if ( /toggle|show|hide/.test(val) )
  e[ val == "toggle" ? hidden ? "show" : "hide" : val ]( prop );
  else {
  var parts = val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),
  start = e.cur(true) || 0;

  if ( parts ) {
  var end = parseFloat(parts[2]),
  unit = parts[3] || "px";

  // We need to compute starting value
  if ( unit != "px" ) {
  self.style[ name ] = (end || 1) + unit;
  start = ((end || 1) / e.cur(true)) * start;
  self.style[ name ] = start + unit;
  }

  // If a +=/-= token was provided, we're doing a relative animation
  if ( parts[1] )
  end = ((parts[1] == "-=" ? -1 : 1) * end) + start;

  e.custom( start, end, unit );
  } else
  e.custom( start, val, "" );
  }
  });

  // For JS strict compliance
  return true;
  });
  },

  stop: function(clearQueue, gotoEnd){
  var timers = jQuery.timers;

  if (clearQueue)
  this.queue([]);

  this.each(function(){
  // go in reverse order so anything added to the queue during the loop is ignored
  for ( var i = timers.length - 1; i >= 0; i-- )
  if ( timers[i].elem == this ) {
  if (gotoEnd)
  // force the next step to be the last
  timers[i](true);
  timers.splice(i, 1);
  }
  });

  // start the next in the queue if the last step wasn't forced
  if (!gotoEnd)
  this.dequeue();

  return this;
  }

});

// Generate shortcuts for custom animations
jQuery.each({
  slideDown: genFx("show", 1),
  slideUp: genFx("hide", 1),
  slideToggle: genFx("toggle", 1),
  fadeIn: { opacity: "show" },
  fadeOut: { opacity: "hide" }
}, function( name, props ){
  jQuery.fn[ name ] = function( speed, callback ){
  return this.animate( props, speed, callback );
  };
});

jQuery.extend({

  speed: function(speed, easing, fn) {
  var opt = typeof speed === "object" ? speed : {
  complete: fn || !fn && easing ||
  jQuery.isFunction( speed ) && speed,
  duration: speed,
  easing: fn && easing || easing && !jQuery.isFunction(easing) && easing
  };

  opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
  jQuery.fx.speeds[opt.duration] || jQuery.fx.speeds._default;

  // Queueing
  opt.old = opt.complete;
  opt.complete = function(){
  if ( opt.queue !== false )
  jQuery(this).dequeue();
  if ( jQuery.isFunction( opt.old ) )
  opt.old.call( this );
  };

  return opt;
  },

  easing: {
  linear: function( p, n, firstNum, diff ) {
  return firstNum + diff * p;
  },
  swing: function( p, n, firstNum, diff ) {
  return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum;
  }
  },

  timers: [],

  fx: function( elem, options, prop ){
  this.options = options;
  this.elem = elem;
  this.prop = prop;

  if ( !options.orig )
  options.orig = {};
  }

});

jQuery.fx.prototype = {

  // Simple function for setting a style value
  update: function(){
  if ( this.options.step )
  this.options.step.call( this.elem, this.now, this );

  (jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this );

  // Set display property to block for height/width animations
  if ( ( this.prop == "height" || this.prop == "width" ) && this.elem.style )
  this.elem.style.display = "block";
  },

  // Get the current size
  cur: function(force){
  if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) )
  return this.elem[ this.prop ];

  var r = parseFloat(jQuery.css(this.elem, this.prop, force));
  return r && r > -10000 ? r : parseFloat(jQuery.curCSS(this.elem, this.prop)) || 0;
  },

  // Start an animation from one number to another
  custom: function(from, to, unit){
  this.startTime = now();
  this.start = from;
  this.end = to;
  this.unit = unit || this.unit || "px";
  this.now = this.start;
  this.pos = this.state = 0;

  var self = this;
  function t(gotoEnd){
  return self.step(gotoEnd);
  }

  t.elem = this.elem;

  if ( t() && jQuery.timers.push(t) && !timerId ) {
  timerId = setInterval(function(){
  var timers = jQuery.timers;

  for ( var i = 0; i < timers.length; i++ )
  if ( !timers[i]() )
  timers.splice(i--, 1);

  if ( !timers.length ) {
  clearInterval( timerId );
  timerId = undefined;
  }
  }, 13);
  }
  },

  // Simple 'show' function
  show: function(){
  // Remember where we started, so that we can go back to it later
  this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop );
  this.options.show = true;

  // Begin the animation
  // Make sure that we start at a small width/height to avoid any
  // flash of content
  this.custom(this.prop == "width" || this.prop == "height" ? 1 : 0, this.cur());

  // Start by showing the element
  jQuery(this.elem).show();
  },

  // Simple 'hide' function
  hide: function(){
  // Remember where we started, so that we can go back to it later
  this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop );
  this.options.hide = true;

  // Begin the animation
  this.custom(this.cur(), 0);
  },

  // Each step of an animation
  step: function(gotoEnd){
  var t = now();

  if ( gotoEnd || t >= this.options.duration + this.startTime ) {
  this.now = this.end;
  this.pos = this.state = 1;
  this.update();

  this.options.curAnim[ this.prop ] = true;

  var done = true;
  for ( var i in this.options.curAnim )
  if ( this.options.curAnim[i] !== true )
  done = false;

  if ( done ) {
  if ( this.options.display != null ) {
  // Reset the overflow
  this.elem.style.overflow = this.options.overflow;

  // Reset the display
  this.elem.style.display = this.options.display;
  if ( jQuery.css(this.elem, "display") == "none" )
  this.elem.style.display = "block";
  }

  // Hide the element if the "hide" operation was done
  if ( this.options.hide )
  jQuery(this.elem).hide();

  // Reset the properties, if the item has been hidden or shown
  if ( this.options.hide || this.options.show )
  for ( var p in this.options.curAnim )
  jQuery.attr(this.elem.style, p, this.options.orig[p]);
  
  // Execute the complete function
  this.options.complete.call( this.elem );
  }

  return false;
  } else {
  var n = t - this.startTime;
  this.state = n / this.options.duration;

  // Perform the easing function, defaults to swing
  this.pos = jQuery.easing[this.options.easing || (jQuery.easing.swing ? "swing" : "linear")](this.state, n, 0, 1, this.options.duration);
  this.now = this.start + ((this.end - this.start) * this.pos);

  // Perform the next step of the animation
  this.update();
  }

  return true;
  }

};

jQuery.extend( jQuery.fx, {
  speeds:{
  slow: 600,
 fast: 200,
 // Default speed
 _default: 400
  },
  step: {

  opacity: function(fx){
  jQuery.attr(fx.elem.style, "opacity", fx.now);
  },

  _default: function(fx){
  if ( fx.elem.style && fx.elem.style[ fx.prop ] != null )
  fx.elem.style[ fx.prop ] = fx.now + fx.unit;
  else
  fx.elem[ fx.prop ] = fx.now;
  }
  }
});
if ( document.documentElement["getBoundingClientRect"] )
  jQuery.fn.offset = function() {
  if ( !this[0] ) return { top: 0, left: 0 };
  if ( this[0] === this[0].ownerDocument.body ) return jQuery.offset.bodyOffset( this[0] );
  var box  = this[0].getBoundingClientRect(), doc = this[0].ownerDocument, body = doc.body, docElem = doc.documentElement,
  clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0,
  top  = box.top  + (self.pageYOffset || jQuery.boxModel && docElem.scrollTop  || body.scrollTop ) - clientTop,
  left = box.left + (self.pageXOffset || jQuery.boxModel && docElem.scrollLeft || body.scrollLeft) - clientLeft;
  return { top: top, left: left };
  };
else 
  jQuery.fn.offset = function() {
  if ( !this[0] ) return { top: 0, left: 0 };
  if ( this[0] === this[0].ownerDocument.body ) return jQuery.offset.bodyOffset( this[0] );
  jQuery.offset.initialized || jQuery.offset.initialize();

  var elem = this[0], offsetParent = elem.offsetParent, prevOffsetParent = elem,
  doc = elem.ownerDocument, computedStyle, docElem = doc.documentElement,
  body = doc.body, defaultView = doc.defaultView,
  prevComputedStyle = defaultView.getComputedStyle(elem, null),
  top = elem.offsetTop, left = elem.offsetLeft;

  while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
  computedStyle = defaultView.getComputedStyle(elem, null);
  top -= elem.scrollTop, left -= elem.scrollLeft;
  if ( elem === offsetParent ) {
  top += elem.offsetTop, left += elem.offsetLeft;
  if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && /^t(able|d|h)$/i.test(elem.tagName)) )
  top  += parseInt( computedStyle.borderTopWidth,  10) || 0,
  left += parseInt( computedStyle.borderLeftWidth, 10) || 0;
  prevOffsetParent = offsetParent, offsetParent = elem.offsetParent;
  }
  if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" )
  top  += parseInt( computedStyle.borderTopWidth,  10) || 0,
  left += parseInt( computedStyle.borderLeftWidth, 10) || 0;
  prevComputedStyle = computedStyle;
  }

  if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" )
  top  += body.offsetTop,
  left += body.offsetLeft;

  if ( prevComputedStyle.position === "fixed" )
  top  += Math.max(docElem.scrollTop, body.scrollTop),
  left += Math.max(docElem.scrollLeft, body.scrollLeft);

  return { top: top, left: left };
  };

jQuery.offset = {
  initialize: function() {
  if ( this.initialized ) return;
  var body = document.body, container = document.createElement('div'), innerDiv, checkDiv, table, td, rules, prop, bodyMarginTop = body.style.marginTop,
  html = '<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;" cellpadding="0" cellspacing="0"><tr><td></td></tr></table>';

  rules = { position: 'absolute', top: 0, left: 0, margin: 0, border: 0, width: '1px', height: '1px', visibility: 'hidden' };
  for ( prop in rules ) container.style[prop] = rules[prop];

  container.innerHTML = html;
  body.insertBefore(container, body.firstChild);
  innerDiv = container.firstChild, checkDiv = innerDiv.firstChild, td = innerDiv.nextSibling.firstChild.firstChild;

  this.doesNotAddBorder = (checkDiv.offsetTop !== 5);
  this.doesAddBorderForTableAndCells = (td.offsetTop === 5);

  innerDiv.style.overflow = 'hidden', innerDiv.style.position = 'relative';
  this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5);

  body.style.marginTop = '1px';
  this.doesNotIncludeMarginInBodyOffset = (body.offsetTop === 0);
  body.style.marginTop = bodyMarginTop;

  body.removeChild(container);
  this.initialized = true;
  },

  bodyOffset: function(body) {
  jQuery.offset.initialized || jQuery.offset.initialize();
  var top = body.offsetTop, left = body.offsetLeft;
  if ( jQuery.offset.doesNotIncludeMarginInBodyOffset )
  top  += parseInt( jQuery.curCSS(body, 'marginTop',  true), 10 ) || 0,
  left += parseInt( jQuery.curCSS(body, 'marginLeft', true), 10 ) || 0;
  return { top: top, left: left };
  }
};


jQuery.fn.extend({
  position: function() {
  var left = 0, top = 0, results;

  if ( this[0] ) {
  // Get *real* offsetParent
  var offsetParent = this.offsetParent(),

  // Get correct offsets
  offset = this.offset(),
  parentOffset = /^body|html$/i.test(offsetParent[0].tagName) ? { top: 0, left: 0 } : offsetParent.offset();

  // Subtract element margins
  // note: when an element has margin: auto the offsetLeft and marginLeft 
  // are the same in Safari causing offset.left to incorrectly be 0
  offset.top  -= num( this, 'marginTop'  );
  offset.left -= num( this, 'marginLeft' );

  // Add offsetParent borders
  parentOffset.top  += num( offsetParent, 'borderTopWidth'  );
  parentOffset.left += num( offsetParent, 'borderLeftWidth' );

  // Subtract the two offsets
  results = {
  top:  offset.top  - parentOffset.top,
  left: offset.left - parentOffset.left
  };
  }

  return results;
  },

  offsetParent: function() {
  var offsetParent = this[0].offsetParent || document.body;
  while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && jQuery.css(offsetParent, 'position') == 'static') )
  offsetParent = offsetParent.offsetParent;
  return jQuery(offsetParent);
  }
});


// Create scrollLeft and scrollTop methods
jQuery.each( ['Left', 'Top'], function(i, name) {
  var method = 'scroll' + name;
  
  jQuery.fn[ method ] = function(val) {
  if (!this[0]) return null;

  return val !== undefined ?

  // Set the scroll offset
  this.each(function() {
  this == window || this == document ?
  window.scrollTo(
  !i ? val : jQuery(window).scrollLeft(),
 i ? val : jQuery(window).scrollTop()
  ) :
  this[ method ] = val;
  }) :

  // Return the scroll offset
  this[0] == window || this[0] == document ?
  self[ i ? 'pageYOffset' : 'pageXOffset' ] ||
  jQuery.boxModel && document.documentElement[ method ] ||
  document.body[ method ] :
  this[0][ method ];
  };
});
// Create innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each([ "Height", "Width" ], function(i, name){

  var tl = i ? "Left"  : "Top",  // top or left
  br = i ? "Right" : "Bottom", // bottom or right
  lower = name.toLowerCase();

  // innerHeight and innerWidth
  jQuery.fn["inner" + name] = function(){
  return this[0] ?
  jQuery.css( this[0], lower, false, "padding" ) :
  null;
  };

  // outerHeight and outerWidth
  jQuery.fn["outer" + name] = function(margin) {
  return this[0] ?
  jQuery.css( this[0], lower, false, margin ? "margin" : "border" ) :
  null;
  };
  
  var type = name.toLowerCase();

  jQuery.fn[ type ] = function( size ) {
  // Get window width or height
  return this[0] == window ?
  // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
  document.compatMode == "CSS1Compat" && document.documentElement[ "client" + name ] ||
  document.body[ "client" + name ] :

  // Get document width or height
  this[0] == document ?
  // Either scroll[Width/Height] or offset[Width/Height], whichever is greater
  Math.max(
  document.documentElement["client" + name],
  document.body["scroll" + name], document.documentElement["scroll" + name],
  document.body["offset" + name], document.documentElement["offset" + name]
  ) :

  // Get or set width or height on the element
  size === undefined ?
  // Get width or height on the element
  (this.length ? jQuery.css( this[0], type ) : null) :

  // Set the width or height on the element (default to pixels if value is unitless)
  this.css( type, typeof size === "string" ? size : size + "px" );
  };

});
})();


/*!
 * jQzoom Evolution Library v2.3  - Javascript Image magnifier
 * http://www.mind-projects.it
 *
 * Copyright 2011, Engineer Marco Renzi
 * Licensed under the BSD license.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the organization nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * Date: 03 May 2011 22:16:00
 */
(function ($) {
    //GLOBAL VARIABLES
    var isIE6 = ($.browser.msie && $.browser.version < 7);
    var body = $(document.body);
    var window = $(window);
    var jqzoompluging_disabled = false; //disabilita globalmente il plugin
    $.fn.jqzoom = function (options) {
        return this.each(function () {
            var node = this.nodeName.toLowerCase();
            if (node == 'a') {
                new jqzoom(this, options);
            }
        });
    };
    jqzoom = function (el, options) {
        var api = null;
        api = $(el).data("jqzoom");
        if (api) return api;
        var obj = this;
        var settings = $.extend({}, $.jqzoom.defaults, options || {});
        obj.el = el;
        el.rel = $(el).attr('rel');
        //ANCHOR ELEMENT
        el.zoom_active = false;
        el.zoom_disabled = false; //to disable single zoom instance
        el.largeimageloading = false; //tell us if large image is loading
        el.largeimageloaded = false; //tell us if large image is loaded
        el.scale = {};
        el.timer = null;
        el.mousepos = {};
        el.mouseDown = false;
        $(el).css({
            'outline-style': 'none',
            'text-decoration': 'none'
        });
        //BASE IMAGE
        var img = $("img:eq(0)", el);
        el.title = $(el).attr('title');
        el.imagetitle = img.attr('title');
        var zoomtitle = ($.trim(el.title).length > 0) ? el.title : el.imagetitle;
        var smallimage = new Smallimage(img);
        var lens = new Lens();
        var stage = new Stage();
        var largeimage = new Largeimage();
        var loader = new Loader();
        //preventing default click,allowing the onclick event [exmple: lightbox]
        $(el).bind('click', function (e) {
            e.preventDefault();
            return false;
        });
        //setting the default zoomType if not in settings
        var zoomtypes = ['standard', 'drag', 'innerzoom', 'reverse'];
        if ($.inArray($.trim(settings.zoomType), zoomtypes) < 0) {
            settings.zoomType = 'standard';
        }
        $.extend(obj, {
            create: function () { //create the main objects
                //create ZoomPad
                if ($(".zoomPad", el).length == 0) {
                    el.zoomPad = $('<div/>').addClass('zoomPad');
                    img.wrap(el.zoomPad);
                }
                if(settings.zoomType == 'innerzoom'){
                    settings.zoomWidth  = smallimage.w;
                    settings.zoomHeight  =   smallimage.h;
                }
                //creating ZoomPup
                if ($(".zoomPup", el).length == 0) {
                    lens.append();
                }
                //creating zoomWindow
                if ($(".zoomWindow", el).length == 0) {
                    stage.append();
                }
                //creating Preload
                if ($(".zoomPreload", el).length == 0) {
                    loader.append();
                }
                //preloading images
                if (settings.preloadImages || settings.zoomType == 'drag' || settings.alwaysOn) {
                    obj.load();
                }
                obj.init();
            },
            init: function () {
                //drag option
                if (settings.zoomType == 'drag') {
                    $(".zoomPad", el).mousedown(function () {
                        el.mouseDown = true;
                    });
                    $(".zoomPad", el).mouseup(function () {
                        el.mouseDown = false;
                    });
                    document.body.ondragstart = function () {
                        return false;
                    };
                    $(".zoomPad", el).css({
                        cursor: 'default'
                    });
                    $(".zoomPup", el).css({
                        cursor: 'move'
                    });
                }
                if (settings.zoomType == 'innerzoom') {
                    $(".zoomWrapper", el).css({
                        cursor: 'crosshair'
                    });
                }
                $(el).bind('changeimage', function(){
                       
                       largeimage.loadimage($(el).attr('href'));
                       
                       //smallimage.loadimage($("img:eq(0)", el).attr('src'));
                       
                    });
                $(".zoomPad", el).bind('mouseenter mouseover', function (event) {
                    img.attr('title', '');
                    $(el).attr('title', '');
                    el.zoom_active = true;
                    //if loaded then activate else load large image
                    smallimage.fetchdata();
                    if (el.largeimageloaded) {
                        obj.activate(event);
                    } else {
                        obj.load();
                    }
                });
                $(".zoomPad", el).bind('mouseleave', function (event) {
                    obj.deactivate();
                });
                $(".zoomPad", el).bind('mousemove', function (e) {

                    //prevent fast mouse mevements not to fire the mouseout event
                    if (e.pageX > smallimage.pos.r || e.pageX < smallimage.pos.l || e.pageY < smallimage.pos.t || e.pageY > smallimage.pos.b) {
                        lens.setcenter();
                        return false;
                    }
                    el.zoom_active = true;
                    if (el.largeimageloaded && !$('.zoomWindow', el).is(':visible')) {
                        obj.activate(e);
                    }
                    if (el.largeimageloaded && (settings.zoomType != 'drag' || (settings.zoomType == 'drag' && el.mouseDown))) {
                        lens.setposition(e);
                    }
                });
                var thumb_preload = new Array();
                var i = 0;
                //binding click event on thumbnails
                var thumblist = new Array();
                thumblist = $('a').filter(function () {
                    var regex = new RegExp("gallery[\\s]*:[\\s]*'" + $.trim(el.rel) + "'", "i");
                    var rel = $(this).attr('rel');
                    if (regex.test(rel)) {
                        return this;
                    }
                });
                if (thumblist.length > 0) {
                    //getting the first to the last
                    var first = thumblist.splice(0, 1);
                    thumblist.push(first);
                }
                thumblist.each(function () {
                    //preloading thumbs
                    if (settings.preloadImages) {
                        var thumb_options = $.extend({}, eval("(" + $.trim($(this).attr('rel')) + ")"));
                        thumb_preload[i] = new Image();
                        thumb_preload[i].src = thumb_options.largeimage;
                        i++;
                    }
                    $(this).click(function (e) {
                        if($(this).hasClass('zoomThumbActive')){
                          return false;
                        }
                        thumblist.each(function () {
                            $(this).removeClass('zoomThumbActive');
                        });
                        e.preventDefault();
                        obj.swapimage(this);
                        return false;
                    });
                    
                });
            },
            load: function () {
                if (el.largeimageloaded == false && el.largeimageloading == false) {
                    var url = $(el).attr('href');
                    el.largeimageloading = true;
                    largeimage.loadimage(url);
                }
            },
            activate: function (e) {
                clearTimeout(el.timer);
                //show lens and zoomWindow
                lens.show();
                stage.show();
            },
            deactivate: function (e) {
                switch (settings.zoomType) {
                case 'drag':
                    //nothing or lens.setcenter();
                    break;
                default:
                    img.attr('title', el.imagetitle);
                    $(el).attr('title', el.title);
                    if (settings.alwaysOn) {
                        lens.setcenter();
                    } else {
                        stage.hide();
                        lens.hide();
                    }
                    break;
                }
                el.zoom_active = false;
            },
            swapimage: function (link) {
                el.largeimageloading = false;
                el.largeimageloaded = false;
                var options = new Object();
                options = $.extend({}, eval("(" + $.trim($(link).attr('rel')) + ")"));
                if (options.smallimage && options.largeimage) {
                    var smallimage = options.smallimage;
                    var largeimage = options.largeimage;
                    $(link).addClass('zoomThumbActive');
                    $(el).attr('href', largeimage);
                    img.attr('src', smallimage);
                    lens.hide();
                    stage.hide();
                    obj.load();
                } else {
                    alert('ERROR :: Missing parameter for largeimage or smallimage.');
                    throw 'ERROR :: Missing parameter for largeimage or smallimage.';
                }
                return false;
            }
        });
        //sometimes image is already loaded and onload will not fire
        if (img[0].complete) {
            //fetching data from sallimage if was previously loaded
            smallimage.fetchdata();
            if ($(".zoomPad", el).length == 0) obj.create();
        }
/*========================================================,
|   Smallimage
|---------------------------------------------------------:
|   Base image into the anchor element
`========================================================*/

        function Smallimage(image) {
            var $obj = this;
            this.node = image[0];
            this.findborder = function () {
                var bordertop = 0;
                bordertop = image.css('border-top-width');
                btop = '';
                var borderleft = 0;
                borderleft = image.css('border-left-width');
                bleft = '';
                if (bordertop) {
                    for (i = 0; i < 3; i++) {
                        var x = [];
                        x = bordertop.substr(i, 1);
                        if (isNaN(x) == false) {
                            btop = btop + '' + bordertop.substr(i, 1);
                        } else {
                            break;
                        }
                    }
                }
                if (borderleft) {
                    for (i = 0; i < 3; i++) {
                        if (!isNaN(borderleft.substr(i, 1))) {
                            bleft = bleft + borderleft.substr(i, 1)
                        } else {
                            break;
                        }
                    }
                }
                $obj.btop = (btop.length > 0) ? eval(btop) : 0;
                $obj.bleft = (bleft.length > 0) ? eval(bleft) : 0;
            };
            this.fetchdata = function () {
                $obj.findborder();
                $obj.w = image.width();
                $obj.h = image.height();
                $obj.ow = image.outerWidth();
                $obj.oh = image.outerHeight();
                $obj.pos = image.offset();
                $obj.pos.l = image.offset().left + $obj.bleft;
                $obj.pos.t = image.offset().top + $obj.btop;
                $obj.pos.r = $obj.w + $obj.pos.l;
                $obj.pos.b = $obj.h + $obj.pos.t;
                $obj.rightlimit = image.offset().left + $obj.ow;
                $obj.bottomlimit = image.offset().top + $obj.oh;
                
            };
            this.node.onerror = function () {
                //alert('Problems while loading image.');
                //throw 'Problems while loading image.';
            };
            this.node.onload = function () {
                $obj.fetchdata();
                if ($(".zoomPad", el).length == 0) obj.create();
            };
            return $obj;
        };
/*========================================================,
|  Loader
|---------------------------------------------------------:
|  Show that the large image is loading
`========================================================*/

        function Loader() {
            var $obj = this;
            this.append = function () {
                this.node = $('<div/>').addClass('zoomPreload').css('visibility', 'hidden').html(settings.preloadText);
                $('.zoomPad', el).append(this.node);
            };
            this.show = function () {
                this.node.top = (smallimage.oh - this.node.height()) / 2;
                this.node.left = (smallimage.ow - this.node.width()) / 2;
                //setting position
                this.node.css({
                    top: this.node.top,
                    left: this.node.left,
                    position: 'absolute',
                    visibility: 'visible'
                });
            };
            this.hide = function () {
                this.node.css('visibility', 'hidden');
            };
            return this;
        }
/*========================================================,
|   Lens
|---------------------------------------------------------:
|   Lens over the image
`========================================================*/

        function Lens() {
            var $obj = this;
            this.node = $('<div/>').addClass('zoomPup');
            //this.nodeimgwrapper = $("<div/>").addClass('zoomPupImgWrapper');
            this.append = function () {
                $('.zoomPad', el).append($(this.node).hide());
                if (settings.zoomType == 'reverse') {
                    this.image = new Image();
                    this.image.src = smallimage.node.src; // fires off async
                    $(this.node).empty().append(this.image);
                }
            };
            this.setdimensions = function () {
                this.node.w = (parseInt((settings.zoomWidth) / el.scale.x) > smallimage.w ) ? smallimage.w : (parseInt(settings.zoomWidth / el.scale.x)); 
                this.node.h = (parseInt((settings.zoomHeight) / el.scale.y) > smallimage.h ) ? smallimage.h : (parseInt(settings.zoomHeight / el.scale.y)); 
                this.node.top = (smallimage.oh - this.node.h - 2) / 2;
                this.node.left = (smallimage.ow - this.node.w - 2) / 2;
                //centering lens
                this.node.css({
                    top: 0,
                    left: 0,
                    width: this.node.w + 'px',
                    height: this.node.h + 'px',
                    position: 'absolute',
                    display: 'none',
                    borderWidth: 1 + 'px'
                });



                if (settings.zoomType == 'reverse') {
                    this.image.src = smallimage.node.src;
                    $(this.node).css({
                        'opacity': 1
                    });

                    $(this.image).css({
                        position: 'absolute',
                        display: 'block',
                        left: -(this.node.left + 1 - smallimage.bleft) + 'px',
                        top: -(this.node.top + 1 - smallimage.btop) + 'px'
                    });

                }
            };
            this.setcenter = function () {
                //calculating center position
                this.node.top = (smallimage.oh - this.node.h - 2) / 2;
                this.node.left = (smallimage.ow - this.node.w - 2) / 2;
                //centering lens
                this.node.css({
                    top: this.node.top,
                    left: this.node.left
                });
                if (settings.zoomType == 'reverse') {
                    $(this.image).css({
                        position: 'absolute',
                        display: 'block',
                        left: -(this.node.left + 1 - smallimage.bleft) + 'px',
                        top: -(this.node.top + 1 - smallimage.btop) + 'px'
                    });

                }
                //centering large image
                largeimage.setposition();
            };
            this.setposition = function (e) {
                el.mousepos.x = e.pageX;
                el.mousepos.y = e.pageY;
                var lensleft = 0;
                var lenstop = 0;

                function overleft(lens) {
                    return el.mousepos.x - (lens.w) / 2 < smallimage.pos.l; 
                }

                function overright(lens) {
                    return el.mousepos.x + (lens.w) / 2 > smallimage.pos.r; 
                   
                }

                function overtop(lens) {
                    return el.mousepos.y - (lens.h) / 2 < smallimage.pos.t; 
                }

                function overbottom(lens) {
                    return el.mousepos.y + (lens.h) / 2 > smallimage.pos.b; 
                }
                
                lensleft = el.mousepos.x + smallimage.bleft - smallimage.pos.l - (this.node.w + 2) / 2;
                lenstop = el.mousepos.y + smallimage.btop - smallimage.pos.t - (this.node.h + 2) / 2;
                if (overleft(this.node)) {
                    lensleft = smallimage.bleft - 1;
                } else if (overright(this.node)) {
                    lensleft = smallimage.w + smallimage.bleft - this.node.w - 1;
                }
                if (overtop(this.node)) {
                    lenstop = smallimage.btop - 1;
                } else if (overbottom(this.node)) {
                    lenstop = smallimage.h + smallimage.btop - this.node.h - 1;
                }
                
                this.node.left = lensleft;
                this.node.top = lenstop;
                this.node.css({
                    'left': lensleft + 'px',
                    'top': lenstop + 'px'
                });
                if (settings.zoomType == 'reverse') {
                    if ($.browser.msie && $.browser.version > 7) {
                        $(this.node).empty().append(this.image);
                    }

                    $(this.image).css({
                        position: 'absolute',
                        display: 'block',
                        left: -(this.node.left + 1 - smallimage.bleft) + 'px',
                        top: -(this.node.top + 1 - smallimage.btop) + 'px'
                    });
                }
               
                largeimage.setposition();
            };
            this.hide = function () {
                img.css({
                    'opacity': 1
                });
                this.node.hide();
            };
            this.show = function () {  
                
                if (settings.zoomType != 'innerzoom' && (settings.lens || settings.zoomType == 'drag')) {
                    this.node.show();
                }       

                if (settings.zoomType == 'reverse') {
                    img.css({
                        'opacity': settings.imageOpacity
                    });
                }
            };
            this.getoffset = function () {
                var o = {};
                o.left = $obj.node.left;
                o.top = $obj.node.top;
                return o;
            };
            return this;
        };
/*========================================================,
|   Stage
|---------------------------------------------------------:
|   Window area that contains the large image
`========================================================*/

        function Stage() {
            var $obj = this;
            this.node = $("<div class='zoomWindow'><div class='zoomWrapper'><div class='zoomWrapperTitle'></div><div class='zoomWrapperImage'></div></div></div>");
            this.ieframe = $('<iframe class="zoomIframe" src="javascript:\'\';" marginwidth="0" marginheight="0" align="bottom" scrolling="no" frameborder="0" ></iframe>');
            this.setposition = function () {
                this.node.leftpos = 0;
                this.node.toppos = 0;
                if (settings.zoomType != 'innerzoom') {
                    //positioning
                    switch (settings.position) {
                    case "left":
                        this.node.leftpos = (smallimage.pos.l - smallimage.bleft - Math.abs(settings.xOffset) - settings.zoomWidth > 0) ? (0 - settings.zoomWidth - Math.abs(settings.xOffset)) : (smallimage.ow + Math.abs(settings.xOffset));
                        this.node.toppos = Math.abs(settings.yOffset);
                        break;
                    case "top":
                        this.node.leftpos = Math.abs(settings.xOffset);
                        this.node.toppos = (smallimage.pos.t - smallimage.btop - Math.abs(settings.yOffset) - settings.zoomHeight > 0) ? (0 - settings.zoomHeight - Math.abs(settings.yOffset)) : (smallimage.oh + Math.abs(settings.yOffset));
                        break;
                    case "bottom":
                        this.node.leftpos = Math.abs(settings.xOffset);
                        this.node.toppos = (smallimage.pos.t - smallimage.btop + smallimage.oh + Math.abs(settings.yOffset) + settings.zoomHeight < screen.height) ? (smallimage.oh + Math.abs(settings.yOffset)) : (0 - settings.zoomHeight - Math.abs(settings.yOffset));
                        break;
                    default:
                        this.node.leftpos = (smallimage.rightlimit + Math.abs(settings.xOffset) + settings.zoomWidth < screen.width) ? (smallimage.ow + Math.abs(settings.xOffset)) : (0 - settings.zoomWidth - Math.abs(settings.xOffset));
                        this.node.toppos = Math.abs(settings.yOffset);
                        break;
                    }
                }
                this.node.css({
                    'left': this.node.leftpos + 'px',
                    'top': this.node.toppos + 'px'
                });
                return this;
            };
            this.append = function () {
                $('.zoomPad', el).append(this.node);
                this.node.css({
                    position: 'absolute',
                    display: 'none',
                    zIndex: 5001
                });
                if (settings.zoomType == 'innerzoom') {
                    this.node.css({
                        cursor: 'default'
                    });
                    var thickness = (smallimage.bleft == 0) ? 1 : smallimage.bleft;
                    $('.zoomWrapper', this.node).css({
                        borderWidth: thickness + 'px'
                    });    
                }
                
                  $('.zoomWrapper', this.node).css({
                      width: Math.round(settings.zoomWidth) + 'px' ,
                      borderWidth: thickness + 'px'
                  });
                  $('.zoomWrapperImage', this.node).css({
                      width: '100%',
                      height: Math.round(settings.zoomHeight) + 'px'
                  });
                  //zoom title
                 $('.zoomWrapperTitle', this.node).css({
                        width: '100%',
                        position: 'absolute'
                  });  
              
                $('.zoomWrapperTitle', this.node).hide();
                if (settings.title && zoomtitle.length > 0) {
                    $('.zoomWrapperTitle', this.node).html(zoomtitle).show();
                }
                $obj.setposition();
            };
            this.hide = function () {
                switch (settings.hideEffect) {
                case 'fadeout':
                    this.node.fadeOut(settings.fadeoutSpeed, function () {});
                    break;
                default:
                    this.node.hide();
                    break;
                }
                this.ieframe.hide();
            };
            this.show = function () {
                switch (settings.showEffect) {
                case 'fadein':
                    this.node.fadeIn();
                    this.node.fadeIn(settings.fadeinSpeed, function () {});
                    break;
                default:
                    this.node.show();
                    break;
                }
                if (isIE6 && settings.zoomType != 'innerzoom') {
                    this.ieframe.width = this.node.width();
                    this.ieframe.height = this.node.height();
                    this.ieframe.left = this.node.leftpos;
                    this.ieframe.top = this.node.toppos;
                    this.ieframe.css({
                        display: 'block',
                        position: "absolute",
                        left: this.ieframe.left,
                        top: this.ieframe.top,
                        zIndex: 99,
                        width: this.ieframe.width + 'px',
                        height: this.ieframe.height + 'px'
                    });
                    $('.zoomPad', el).append(this.ieframe);
                    this.ieframe.show();
                };
            };
        };
/*========================================================,
|   LargeImage
|---------------------------------------------------------:
|   The large detailed image
`========================================================*/

        function Largeimage() {
            var $obj = this;
            this.node = new Image();
            this.loadimage = function (url) {
                //showing preload
                loader.show();
                this.url = url;
                this.node.style.position = 'absolute';
                this.node.style.border = '0px';
                this.node.style.display = 'none';
                this.node.style.left = '-5000px';
                this.node.style.top = '0px';
                document.body.appendChild(this.node);
                this.node.src = url; // fires off async
            };
            this.fetchdata = function () {
                var image = $(this.node);
                var scale = {};
                this.node.style.display = 'block';
                $obj.w = image.width();
                $obj.h = image.height();
                $obj.pos = image.offset();
                $obj.pos.l = image.offset().left;
                $obj.pos.t = image.offset().top;
                $obj.pos.r = $obj.w + $obj.pos.l;
                $obj.pos.b = $obj.h + $obj.pos.t;
                scale.x = ($obj.w / smallimage.w);
                scale.y = ($obj.h / smallimage.h);
                el.scale = scale;
                document.body.removeChild(this.node);
                $('.zoomWrapperImage', el).empty().append(this.node);
                //setting lens dimensions;
                lens.setdimensions();
            };
            this.node.onerror = function () {
                alert('Problems while loading the big image.');
                throw 'Problems while loading the big image.';
            };
            this.node.onload = function () {
                //fetching data
                $obj.fetchdata();
                loader.hide();
                el.largeimageloading = false;
                el.largeimageloaded = true;
                if (settings.zoomType == 'drag' || settings.alwaysOn) {
                    lens.show();
                    stage.show();
                    lens.setcenter();
                }
            };
            this.setposition = function () {
                var left = -el.scale.x * (lens.getoffset().left - smallimage.bleft + 1);
                var top = -el.scale.y * (lens.getoffset().top - smallimage.btop + 1);
                $(this.node).css({
                    'left': left + 'px',
                    'top': top + 'px'
                });
            };
            return this;
        };
        $(el).data("jqzoom", obj);
    };
    //es. $.jqzoom.disable('#jqzoom1');
    $.jqzoom = {
        defaults: {
            zoomType: 'standard',
            //innerzoom/standard/reverse/drag
            zoomWidth: 300,
            //zoomWindow  default width
            zoomHeight: 300,
            //zoomWindow  default height
            xOffset: 10,
            //zoomWindow x offset, can be negative(more on the left) or positive(more on the right)
            yOffset: 0,
            //zoomWindow y offset, can be negative(more on the left) or positive(more on the right)
            position: "right",
            //zoomWindow default position
            preloadImages: true,
            //image preload
            preloadText: 'Loading zoom',
            title: true,
            lens: true,
            imageOpacity: 0.4,
            alwaysOn: false,
            showEffect: 'show',
            //show/fadein
            hideEffect: 'hide',
            //hide/fadeout
            fadeinSpeed: 'slow',
            //fast/slow/number
            fadeoutSpeed: '2000' //fast/slow/number
        },
        disable: function (el) {
            var api = $(el).data('jqzoom');
            api.disable();
            return false;
        },
        enable: function (el) {
            var api = $(el).data('jqzoom');
            api.enable();
            return false;
        },
        disableAll: function (el) {
            jqzoompluging_disabled = true;
        },
        enableAll: function (el) {
            jqzoompluging_disabled = false;
        }
    };
})(jQuery);


/**
 * SWFObject v1.4: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2006 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * **SWFObject is the SWF embed script formarly known as FlashObject. The name was changed for
 * legal reasons.
 */
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(_1,id,w,h,_5,c,_7,_8,_9,_a,_b){
if(!document.createElement||!document.getElementById){return;}
this.DETECT_KEY=_b?_b:"detectflash";
this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);
this.params=new Object();
this.variables=new Object();
this.attributes=new Array();
if(_1){this.setAttribute("swf",_1);}
if(id){this.setAttribute("id",id);}
if(w){this.setAttribute("width",w);}
if(h){this.setAttribute("height",h);}
if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}
this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion(this.getAttribute("version"),_7);
if(c){this.addParam("bgcolor",c);}
var q=_8?_8:"high";
this.addParam("quality",q);
this.setAttribute("useExpressInstall",_7);
this.setAttribute("doExpressInstall",false);
var _d=(_9)?_9:window.location;
this.setAttribute("xiRedirectUrl",_d);
this.setAttribute("redirectUrl","");
if(_a){this.setAttribute("redirectUrl",_a);}};
deconcept.SWFObject.prototype={setAttribute:function(_e,_f){
this.attributes[_e]=_f;
},getAttribute:function(_10){
return this.attributes[_10];
},addParam:function(_11,_12){
this.params[_11]=_12;
},getParams:function(){
return this.params;
},addVariable:function(_13,_14){
this.variables[_13]=_14;
},getVariable:function(_15){
return this.variables[_15];
},getVariables:function(){
return this.variables;
},getVariablePairs:function(){
var _16=new Array();
var key;
var _18=this.getVariables();
for(key in _18){
_16.push(key+"="+_18[key]);}
return _16;
},getSWFHTML:function(){
var _19="";
if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){
if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");}
_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\"";
_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";
var _1a=this.getParams();
for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}
var _1c=this.getVariablePairs().join("&");
if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}
_19+="/>";
}else{
if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");}
_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\">";
_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";
var _1d=this.getParams();
for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}
var _1f=this.getVariablePairs().join("&");
if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}
_19+="</object>";}
return _19;
},write:function(_20){
if(this.getAttribute("useExpressInstall")){
var _21=new deconcept.PlayerVersion([6,0,65]);
if(this.installedVer.versionIsValid(_21)&&!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 _20=="string")?document.getElementById(_20):_20;
n.innerHTML=this.getSWFHTML();
return true;
}else{
if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}
return false;}};
deconcept.SWFObjectUtil.getPlayerVersion=function(_23,_24){
var _25=new deconcept.PlayerVersion([0,0,0]);
if(navigator.plugins&&navigator.mimeTypes.length){
var x=navigator.plugins["Shockwave Flash"];
if(x&&x.description){_25=new deconcept.PlayerVersion(x.description.replace(/([a-z]|[A-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}
}else{try{
var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
for(var i=3;axo!=null;i++){
axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+i);
_25=new deconcept.PlayerVersion([i,0,0]);}}
catch(e){}
if(_23&&_25.major>_23.major){return _25;}
if(!_23||((_23.minor!=0||_23.rev!=0)&&_25.major==_23.major)||_25.major!=6||_24){
try{_25=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}
catch(e){}}}
return _25;};
deconcept.PlayerVersion=function(_29){
this.major=parseInt(_29[0])!=null?parseInt(_29[0]):0;
this.minor=parseInt(_29[1])||0;
this.rev=parseInt(_29[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;};
deconcept.util={getRequestParameter:function(_2b){
var q=document.location.search||document.location.hash;
if(q){
var _2d=q.indexOf(_2b+"=");
var _2e=(q.indexOf("&",_2d)>-1)?q.indexOf("&",_2d):q.length;
if(q.length>1&&_2d>-1){
return q.substring(q.indexOf("=",_2d)+1,_2e);
}}return "";}};
if(Array.prototype.push==null){
Array.prototype.push=function(_2f){
this[this.length]=_2f;
return this.length;};}
var getQueryParamValue=deconcept.util.getRequestParameter;
var FlashObject=deconcept.SWFObject; // for backwards compatibility
var SWFObject=deconcept.SWFObject;





// ajax sending form

jQuery.extend({

  createUploadIframe: function(id, uri){

  var frameId = 'jQuery' + id;
  
  if(window.ActiveXObject) {
  var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');

  if(typeof uri== 'boolean'){
  io.src = 'blank.html';
  }
  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

  },

  ajaxUpload: 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()
  io = jQuery.createUploadIframe(id, s.secureuri)

  // 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){  
  try {
  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;
  }
  catch(e){}
  
  data = io.contentWindow.document.body.innerHTML;

  if (data && data!='') {
  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)
  
  // 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(){ document.body.removeChild(io); }, 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 frameId = 'jQuery' + id;
  var io = document.getElementById(frameId);
  // Initialize the HTML form properties in case they are
  // not defined in the HTML form.
  
  
  s.uploadform.method = 'POST';
  s.uploadform.action = s.url;
  s.uploadform.target = frameId;

  if(s.uploadform.encoding){
  // IE does not respect property enctype for HTML forms.
  // Instead use property encoding.
  s.uploadform.encoding = 'multipart/form-data';
  }
  else{
  s.uploadform.enctype = 'multipart/form-data';
  }

  s.uploadform.submit();

  } catch(e) {
  jQuery.handleError(s, xml, null, e);
  }

  if(window.attachEvent){
  io.attachEvent('onload', uploadCallback);
  }
  else{
  io.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();

  return data;
  }
})



//disabling popup with jQuery magic!
function disablePopup(){
  if(document.getElementById('fancy_div'))  
    jQuery.fn.fancybox.close();
}

function getOffsetRect(elem) {
  // (1)
  var box = elem.getBoundingClientRect()

  // (2)
  var body = document.body
  var docElem = document.documentElement

  // (3)
  var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop
  var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft

  // (4)
  var clientTop = docElem.clientTop || body.clientTop || 0
  var clientLeft = docElem.clientLeft || body.clientLeft || 0

  // (5)
  var top  = box.top +  scrollTop - clientTop
  var left = box.left + scrollLeft - clientLeft

  return { top: Math.round(top), left: Math.round(left) }
}







// calendar
function positionInfo(object) {

  var p_elm = object;

  this.getElementLeft = getElementLeft;
  function getElementLeft() {
  var x = 0;
  var elm;
  if(typeof(p_elm) == "object"){
  elm = p_elm;
  } else {
  elm = document.getElementById(p_elm);
  }
  while (elm != null) {
  if(elm.style.position == 'relative') {
  break;
  }
  else {
  x += elm.offsetLeft;
  elm = elm.offsetParent;
  }
  }
  return parseInt(x);
  }

  this.getElementWidth = getElementWidth;
  function getElementWidth(){
  var elm;
  if(typeof(p_elm) == "object"){
  elm = p_elm;
  } else {
  elm = document.getElementById(p_elm);
  }
  return parseInt(elm.offsetWidth);
  }

  this.getElementRight = getElementRight;
  function getElementRight(){
  return getElementLeft(p_elm) + getElementWidth(p_elm);
  }

  this.getElementTop = getElementTop;
  function getElementTop() {
  var y = 0;
  var elm;
  if(typeof(p_elm) == "object"){
  elm = p_elm;
  } else {
  elm = document.getElementById(p_elm);
  }
  while (elm != null) {
  if(elm.style.position == 'relative') {
  break;
  }
  else {
  y+= elm.offsetTop;
  elm = elm.offsetParent;
  }
  }
  return parseInt(y);
  }

  this.getElementHeight = getElementHeight;
  function getElementHeight(){
  var elm;
  if(typeof(p_elm) == "object"){
  elm = p_elm;
  } else {
  elm = document.getElementById(p_elm);
  }
  return parseInt(elm.offsetHeight);
  }

  this.getElementBottom = getElementBottom;
  function getElementBottom(){
  return getElementTop(p_elm) + getElementHeight(p_elm);
  }
}

function CalendarControl() {

  var calendarId = 'CalendarControl';
  var currentYear = 0;
  var currentMonth = 0;
  var currentDay = 0;

  var selectedYear = 0;
  var selectedMonth = 0;
  var selectedDay = 0;

  var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
  var dateField = null;

  function getProperty(p_property){
  var p_elm = calendarId;
  var elm = null;

  if(typeof(p_elm) == "object"){
  elm = p_elm;
  } else {
  elm = document.getElementById(p_elm);
  }
  if (elm != null){
  if(elm.style){
  elm = elm.style;
  if(elm[p_property]){
  return elm[p_property];
  } else {
  return null;
  }
  } else {
  return null;
  }
  }
  }

  function setElementProperty(p_property, p_value, p_elmId){
  var p_elm = p_elmId;
  var elm = null;

  if(typeof(p_elm) == "object"){
  elm = p_elm;
  } else {
  elm = document.getElementById(p_elm);
  }
  if((elm != null) && (elm.style != null)){
  elm = elm.style;
  elm[ p_property ] = p_value;
  }
  }

  function setProperty(p_property, p_value) {
  setElementProperty(p_property, p_value, calendarId);
  }

  function getDaysInMonth(year, month) {
  return [31,((!(year % 4 ) && ( (year % 100 ) || !( year % 400 ) ))?29:28),31,30,31,30,31,31,30,31,30,31][month-1];
  }

  function getDayOfWeek(year, month, day) {
  var date = new Date(year,month-1,day)
  return date.getDay();
  }

  this.clearDate = clearDate;
  function clearDate() {
  dateField.value = '';
  hide();
  }

  this.setDate = setDate;
  function setDate(year, month, day) {
  if (dateField) {
  if (month < 10) {month = "0" + month;}
  if (day < 10) {day = "0" + day;}

  var dateString = month+"-"+day+"-"+year;
  dateField.value = dateString;
  hide();
  }
  return;
  }

  this.changeMonth = changeMonth;
  function changeMonth(change) {
  currentMonth += change;
  currentDay = 0;
  if(currentMonth > 12) {
  currentMonth = 1;
  currentYear++;
  } else if(currentMonth < 1) {
  currentMonth = 12;
  currentYear--;
  }

  calendar = document.getElementById(calendarId);
  calendar.innerHTML = calendarDrawTable();
  }

  this.changeYear = changeYear;
  function changeYear(change) {
  currentYear += change;
  currentDay = 0;
  calendar = document.getElementById(calendarId);
  calendar.innerHTML = calendarDrawTable();
  }

  function getCurrentYear() {
  var year = new Date().getYear();
  if(year < 1900) year += 1900;
  return year;
  }

  function getCurrentMonth() {
  return new Date().getMonth() + 1;
  } 

  function getCurrentDay() {
  return new Date().getDate();
  }

  function calendarDrawTable() {

  var dayOfMonth = 1;
  var validDay = 0;
  var startDayOfWeek = getDayOfWeek(currentYear, currentMonth, dayOfMonth);
  var daysInMonth = getDaysInMonth(currentYear, currentMonth);
  var css_class = null; //CSS class for each day

  var table = "<table cellspacing='0' cellpadding='0' border='0'>";
  table = table + "<tr class='header'>";
  table = table + "  <td colspan='2' class='previous'><a href='javascript:changeCalendarControlMonth(-1);'>&lt;</a> <a href='javascript:changeCalendarControlYear(-1);'>&laquo;</a></td>";
  table = table + "  <td colspan='3' class='title'>" + months[currentMonth-1] + "<br>" + currentYear + "</td>";
  table = table + "  <td colspan='2' class='next'><a href='javascript:changeCalendarControlYear(1);'>&raquo;</a> <a href='javascript:changeCalendarControlMonth(1);'>&gt;</a></td>";
  table = table + "</tr>";
  table = table + "<tr><th>S</th><th>M</th><th>T</th><th>W</th><th>T</th><th>F</th><th>S</th></tr>";

  for(var week=0; week < 6; week++) {
  table = table + "<tr>";
  for(var dayOfWeek=0; dayOfWeek < 7; dayOfWeek++) {
  if(week == 0 && startDayOfWeek == dayOfWeek) {
  validDay = 1;
  } else if (validDay == 1 && dayOfMonth > daysInMonth) {
  validDay = 0;
  }

  if(validDay) {
  if (dayOfMonth == selectedDay && currentYear == selectedYear && currentMonth == selectedMonth) {
  css_class = 'current';
  } else if (dayOfWeek == 0 || dayOfWeek == 6) {
  css_class = 'weekend';
  } else {
  css_class = 'weekday';
  }

  table = table + "<td><a class='"+css_class+"' href=\"javascript:setCalendarControlDate("+currentYear+","+currentMonth+","+dayOfMonth+")\">"+dayOfMonth+"</a></td>";
  dayOfMonth++;
  } else {
  table = table + "<td class='empty'>&nbsp;</td>";
  }
  }
  table = table + "</tr>";
  }

  table = table + "<tr class='header'><th colspan='7' style='padding: 3px;'><a href='javascript:clearCalendarControl();'>Clear</a> | <a href='javascript:hideCalendarControl();'>Close</a></td></tr>";
  table = table + "</table>";

  return table;
  }

  this.show = show;
  function show(field) {
  can_hide = 0;
  
  // If the calendar is visible and associated with
  // this field do not do anything.
  if (dateField == field) {
  return;
  } else {
  dateField = field;
  }

  if(dateField) {
  try {
  var dateString = new String(dateField.value);
  var dateParts = dateString.split("-");
  
  selectedMonth = parseInt(dateParts[0],10);
  selectedDay = parseInt(dateParts[1],10);
  selectedYear = parseInt(dateParts[2],10);
  } catch(e) {}
  }

  if (!(selectedYear && selectedMonth && selectedDay)) {
  selectedMonth = getCurrentMonth();
  selectedDay = getCurrentDay();
  selectedYear = getCurrentYear();
  }

  currentMonth = selectedMonth;
  currentDay = selectedDay;
  currentYear = selectedYear;

  if(document.getElementById){

  calendar = document.getElementById(calendarId);
  calendar.innerHTML = calendarDrawTable(currentYear, currentMonth);

  setProperty('display', 'block');

  var fieldPos = new positionInfo(dateField);
  var calendarPos = new positionInfo(calendarId);

  var x = fieldPos.getElementLeft();
  var y = fieldPos.getElementBottom();

  setProperty('left', x + "px");
  setProperty('top', y + "px");
 
  if (document.all) {
  setElementProperty('display', 'block', 'CalendarControlIFrame');
  setElementProperty('left', x + "px", 'CalendarControlIFrame');
  setElementProperty('top', y + "px", 'CalendarControlIFrame');
  setElementProperty('width', calendarPos.getElementWidth() + "px", 'CalendarControlIFrame');
  setElementProperty('height', calendarPos.getElementHeight() + "px", 'CalendarControlIFrame');
  }
  }
  }

  this.hide = hide;
  function hide() {
  if(dateField) {
  setProperty('display', 'none');
  setElementProperty('display', 'none', 'CalendarControlIFrame');
  dateField = null;
  }
  }

  this.visible = visible;
  function visible() {
  return dateField
  }

  this.can_hide = can_hide;
  var can_hide = 0;
}



/***************************************************************
 *  JS-TrackBar
 *
 * Copyright (C) 2008 by Alexander Burtsev - webew.ru
 * and abarmot - http://abarmot.habrahabr.ru/
 * desing: пїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅ пїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅпїЅ - http://my.mail.ru/bk/concur/
 *
 *  This code is a public domain.
 ***************************************************************/

var trackbar = { // NAMESPACE
	archive : {},
	getObject : function(id) {
		if (typeof this.archive[id] == "undefined") {
			this.archive[id] = new this.hotSearch(id);
		}
		return this.archive[id];
	}
};


function init_star_rating(){eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}(';5(29.1j)(7($){5($.1L.1J)1I{1t.1H("1K",J,H)}1M(e){};$.n.3=7(i){5(4.Q==0)k 4;5(A I[0]==\'1h\'){5(4.Q>1){8 j=I;k 4.W(7(){$.n.3.y($(4),j)})};$.n.3[I[0]].y(4,$.1T(I).1U(1)||[]);k 4};8 i=$.12({},$.n.3.1s,i||{});$.n.3.K++;4.2a(\'.9-3-1f\').o(\'9-3-1f\').W(7(){8 a,l=$(4);8 b=(4.23||\'21-3\').1v(/\\[|\\]/g,\'Z\').1v(/^\\Z+|\\Z+$/g,\'\');8 c=$(4.1X||1t.1W);8 d=c.6(\'3\');5(!d||d.18!=$.n.3.K)d={z:0,18:$.n.3.K};8 e=d[b];5(e)a=e.6(\'3\');5(e&&a)a.z++;x{a=$.12({},i||{},($.1b?l.1b():($.1S?l.6():s))||{},{z:0,F:[],v:[]});a.w=d.z++;e=$(\'<1R V="9-3-1Q"/>\');l.1P(e);e.o(\'3-15-T-17\');5(l.S(\'R\'))a.m=H;e.1c(a.E=$(\'<P V="3-E"><a 14="\'+a.E+\'">\'+a.1d+\'</a></P>\').1g(7(){$(4).3(\'O\');$(4).o(\'9-3-N\')}).1i(7(){$(4).3(\'u\');$(4).G(\'9-3-N\')}).1l(7(){$(4).3(\'r\')}).6(\'3\',a))};8 f=$(\'<P V="9-3 q-\'+a.w+\'"><a 14="\'+(4.14||4.1p)+\'">\'+4.1p+\'</a></P>\');e.1c(f);5(4.11)f.S(\'11\',4.11);5(4.1r)f.o(4.1r);5(a.1F)a.t=2;5(A a.t==\'1u\'&&a.t>0){8 g=($.n.10?f.10():0)||a.1w;8 h=(a.z%a.t),Y=1y.1z(g/a.t);f.10(Y).1A(\'a\').1B({\'1C-1D\':\'-\'+(h*Y)+\'1E\'})};5(a.m)f.o(\'9-3-1o\');x f.o(\'9-3-1G\').1g(7(){$(4).3(\'1n\');$(4).3(\'D\')}).1i(7(){$(4).3(\'u\');$(4).3(\'C\')}).1l(7(){$(4).3(\'r\')});5(4.L)a.p=f;l.1q();l.1N(7(){$(4).3(\'r\')});f.6(\'3.l\',l.6(\'3.9\',f));a.F[a.F.Q]=f[0];a.v[a.v.Q]=l[0];a.q=d[b]=e;a.1O=c;l.6(\'3\',a);e.6(\'3\',a);f.6(\'3\',a);c.6(\'3\',d)});$(\'.3-15-T-17\').3(\'u\').G(\'3-15-T-17\');k 4};$.12($.n.3,{K:0,D:7(){8 a=4.6(\'3\');5(!a)k 4;5(!a.D)k 4;8 b=$(4).6(\'3.l\')||$(4.U==\'13\'?4:s);5(a.D)a.D.y(b[0],[b.M(),$(\'a\',b.6(\'3.9\'))[0]])},C:7(){8 a=4.6(\'3\');5(!a)k 4;5(!a.C)k 4;8 b=$(4).6(\'3.l\')||$(4.U==\'13\'?4:s);5(a.C)a.C.y(b[0],[b.M(),$(\'a\',b.6(\'3.9\'))[0]])},1n:7(){8 a=4.6(\'3\');5(!a)k 4;5(a.m)k;4.3(\'O\');4.1a().19().X(\'.q-\'+a.w).o(\'9-3-N\')},O:7(){8 a=4.6(\'3\');5(!a)k 4;5(a.m)k;a.q.1V().X(\'.q-\'+a.w).G(\'9-3-1k\').G(\'9-3-N\')},u:7(){8 a=4.6(\'3\');5(!a)k 4;4.3(\'O\');5(a.p){a.p.6(\'3.l\').S(\'L\',\'L\');a.p.1a().19().X(\'.q-\'+a.w).o(\'9-3-1k\')}x $(a.v).1m(\'L\');a.E[a.m||a.1Y?\'1q\':\'1Z\']();4.20()[a.m?\'o\':\'G\'](\'9-3-1o\')},r:7(a,b){8 c=4.6(\'3\');5(!c)k 4;5(c.m)k;c.p=s;5(A a!=\'B\'){5(A a==\'1u\')k $(c.F[a]).3(\'r\',B,b);5(A a==\'1h\')$.W(c.F,7(){5($(4).6(\'3.l\').M()==a)$(4).3(\'r\',B,b)})}x c.p=4[0].U==\'13\'?4.6(\'3.9\'):(4.22(\'.q-\'+c.w)?4:s);4.6(\'3\',c);4.3(\'u\');8 d=$(c.p?c.p.6(\'3.l\'):s);5((b||b==B)&&c.1e)c.1e.y(d[0],[d.M(),$(\'a\',c.p)[0]])},m:7(a,b){8 c=4.6(\'3\');5(!c)k 4;c.m=a||a==B?H:J;5(b)$(c.v).S("R","R");x $(c.v).1m("R");4.6(\'3\',c);4.3(\'u\')},1x:7(){4.3(\'m\',H,H)},24:7(){4.3(\'m\',J,J)}});$.n.3.1s={E:\'25 26\',1d:\'\',t:0,1w:16};$(7(){$(\'l[27=28].9\').3()})})(1j);',62,135,'|||rating|this|if|data|function|var|star|||||||||||return|input|readOnly|fn|addClass|current|rater|select|null|split|draw|inputs|serial|else|apply|count|typeof|undefined|blur|focus|cancel|stars|removeClass|true|arguments|false|calls|checked|val|hover|drain|div|length|disabled|attr|be|tagName|class|each|filter|spw|_|width|id|extend|INPUT|title|to||drawn|call|andSelf|prevAll|metadata|append|cancelValue|callback|applied|mouseover|string|mouseout|jQuery|on|click|removeAttr|fill|readonly|value|hide|className|options|document|number|replace|starWidth|disable|Math|floor|find|css|margin|left|px|half|live|execCommand|try|msie|BackgroundImageCache|browser|catch|change|context|before|control|span|meta|makeArray|slice|children|body|form|required|show|siblings|unnamed|is|name|enable|Cancel|Rating|type|radio|window|not'.split('|'),0,{}));}

init_star_rating();

/*
 * Metadata - jQuery plugin for parsing metadata from elements
 *
 * Copyright (c) 2006 John Resig, Yehuda Katz, J?rn Zaefferer, Paul McLanahan
 *
 * 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$
 *
 */

/**
 * Sets the type of metadata to use. Metadata is encoded in JSON, and each property
 * in the JSON will become a property of the element itself.
 *
 * There are three supported types of metadata storage:
 *
 * attr:  Inside an attribute. The name parameter indicates *which* attribute.
 *  
 * class: Inside the class attribute, wrapped in curly braces: { }
 * 
 * elem:  Inside a child element (e.g. a script tag). The
 *  name parameter indicates *which* element.
 *  
 * The metadata for an element is loaded the first time the element is accessed via jQuery.
 *
 * As a result, you can define the metadata type, use $(expr) to load the metadata into the elements
 * matched by expr, then redefine the metadata type and run another $(expr) for other elements.
 * 
 * @name $.metadata.setType
 *
 * @example <p id="one" class="some_class {item_id: 1, item_label: 'Label'}">This is a p</p>
 * @before $.metadata.setType("class")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from the class attribute
 * 
 * @example <p id="one" class="some_class" data="{item_id: 1, item_label: 'Label'}">This is a p</p>
 * @before $.metadata.setType("attr", "data")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from a "data" attribute
 * 
 * @example <p id="one" class="some_class"><script>{item_id: 1, item_label: 'Label'}</script>This is a p</p>
 * @before $.metadata.setType("elem", "script")
 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
 * @desc Reads metadata from a nested script element
 * 
 * @param String type The encoding type
 * @param String name The name of the attribute to be used to get metadata (optional)
 * @cat Plugins/Metadata
 * @descr Sets the type of encoding to be used when loading metadata for the first time
 * @type undefined
 * @see metadata()
 */

(function($) {

$.extend({
  metadata : {
  defaults : {
  type: 'class',
  name: 'metadata',
  cre: /({.*})/,
  single: 'metadata'
  },
  setType: function( type, name ){
  this.defaults.type = type;
  this.defaults.name = name;
  },
  get: function( elem, opts ){
  var settings = $.extend({},this.defaults,opts);
  // check for empty string in single property
  if ( !settings.single.length ) settings.single = 'metadata';
  
  var data = $.data(elem, settings.single);
  // returned cached data if it already exists
  if ( data ) return data;
  
  data = "{}";
  
  if ( settings.type == "class" ) {
  var m = settings.cre.exec( elem.className );
  if ( m )
  data = m[1];
  } else if ( settings.type == "elem" ) {
  if( !elem.getElementsByTagName ) return;
  var e = elem.getElementsByTagName(settings.name);
  if ( e.length )
  data = $.trim(e[0].innerHTML);
  } else if ( elem.getAttribute != undefined ) {
  var attr = elem.getAttribute( settings.name );
  if ( attr )
  data = attr;
  }
  
  if ( data.indexOf( '{' ) <0 )
  data = "{" + data + "}";
  
  data = eval("(" + data + ")");
  
  $.data( elem, settings.single, data );
  return data;
  }
  }
});

/**
 * Returns the metadata object for the first member of the jQuery object.
 *
 * @name metadata
 * @descr Returns element's metadata object
 * @param Object opts An object contianing settings to override the defaults
 * @type jQuery
 * @cat Plugins/Metadata
 */
$.fn.metadata = function( opts ){
  return $.metadata.get( this[0], opts );
};

})(jQuery);

function init_buzzreply_ckeditor(id)
{
    if(document.getElementById('cke_reply_text'+id)) return true;
    var config = {toolbar:[]};
    config.skin = 'office2003';
    config.height = '90px';
    config.enterMode = CKEDITOR.ENTER_BR;
    config.shiftEnterMode = CKEDITOR.ENTER_P;
    
    var ckeditor = CKEDITOR.replace( 'reply_text'+id, config );
    var editor = eval('CKEDITOR.instances.reply_text'+id);
    editor.on("instanceReady", function(event)
    {
         jQuery('#cke_top_reply_text'+id).remove();
         jQuery('#cke_bottom_reply_text'+id).remove();
    });
    editor.on("key", function(event)
    {
         setTimeout(function (){set_editor_counter('reply_text'+id, 400)},50);
    });
}

function init_ckeditor(i, no_source)
{
  //var temp = i-1;
  //if(temp>=0) eval("CKEDITOR.instances.ckeditor"+temp+".destroy()");

  var emptyDivFilter =
 {
  elements : {
 div : function( div )
 {
  //if ( div.attributes[ 'class' ].indexOf ( 'clear-both' ) != -1 )
  {
 // Peak the element content.
 var writer = new CKEDITOR.htmlParser.basicWriter();
 div.writeChildrenHtml( writer );
 var innerHTML = writer.getHtml();

 // Remove the filler node if block is empty.
 if ( CKEDITOR.tools.trim( innerHTML ).match( /^(?:&nbsp;|\xa0|<br \/>)$/ ) )
 div.children = [];
  }
  return div;
 }
  }
 };
 if(no_source==undefined) var temp = 'Source'; else var temp = '';
  var config = {
  toolbar:
  [
  [temp,'Undo','Redo','-','Link','Unlink'],
  ['NumberedList','BulletedList'],
  ['TextColor','BGColor'],
  ['FontSize'],
  ['Bold','Italic','Underline','Strike','-','Subscript','Superscript','-','MediaEmbed','Image']
  ],
  on :
 {
  'pluginsLoaded' : function ( evt )
  {
 var editor = evt.editor;
 var htmlFilter = editor.dataProcessor.htmlFilter,
 dataFilter = editor.dataProcessor.dataFilter;

 // Give the filters lower priority makes it get applied after the default ones.
 htmlFilter.addRules( emptyDivFilter, 100 );
 dataFilter.addRules( emptyDivFilter, 100 );
  }
 }
  };
  var ckeditor = CKEDITOR.replace( 'ckeditor'+i, config );
  CKEDITOR.config.contentsCss = '/templates/default/style.css';
  CKEDITOR.config.FillEmptyBlocks = false;
  CKEDITOR.config.FormatOutput = false;
}

/*  Prototype JavaScript framework, version 1.5.1
 *  (c) 2005-2007 Sam Stephenson
 *
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *  For details, see the Prototype web site: http://www.prototypejs.org/
 *
/*--------------------------------------------------------------------------*/

var Prototype = {
  Version: '1.5.1',

  Browser: {
    IE:     !!(window.attachEvent && !window.opera),
    Opera:  !!window.opera,
    WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
    Gecko:  navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1
  },

  BrowserFeatures: {
    XPath: !!document.evaluate,
    ElementExtensions: !!window.HTMLElement,
    SpecificElementExtensions:
      (document.createElement('div').__proto__ !==
       document.createElement('form').__proto__)
  },

  ScriptFragment: '<script[^>]*>([\u0001-\uFFFF]*?)</script>',
  JSONFilter: /^\/\*-secure-\s*(.*)\s*\*\/\s*$/,

  emptyFunction: function() { },
  K: function(x) { return x }
}

var Class = {
  create: function() {
    return function() {
      this.initialize.apply(this, arguments);
    }
  }
}

var Abstract = new Object();

Object.extend = function(destination, source) {
  for (var property in source) {
    destination[property] = source[property];
  }
  return destination;
}

Object.extend(Object, {
  inspect: function(object) {
    try {
      if (object === undefined) return 'undefined';
      if (object === null) return 'null';
      return object.inspect ? object.inspect() : object.toString();
    } catch (e) {
      if (e instanceof RangeError) return '...';
      throw e;
    }
  },

  toJSON: function(object) {
    var type = typeof object;
    switch(type) {
      case 'undefined':
      case 'function':
      case 'unknown': return;
      case 'boolean': return object.toString();
    }
    if (object === null) return 'null';
    if (object.toJSON) return object.toJSON();
    if (object.ownerDocument === document) return;
    var results = [];
    for (var property in object) {
      var value = Object.toJSON(object[property]);
      if (value !== undefined)
        results.push(property.toJSON() + ': ' + value);
    }
    return '{' + results.join(', ') + '}';
  },

  keys: function(object) {
    var keys = [];
    for (var property in object)
      keys.push(property);
    return keys;
  },

  values: function(object) {
    var values = [];
    for (var property in object)
      values.push(object[property]);
    return values;
  },

  clone: function(object) {
    return Object.extend({}, object);
  }
});

Function.prototype.bind = function() {
  var __method = this, args = $A(arguments), object = args.shift();
  return function() {
    return __method.apply(object, args.concat($A(arguments)));
  }
}

Function.prototype.bindAsEventListener = function(object) {
  var __method = this, args = $A(arguments), object = args.shift();
  return function(event) {
    return __method.apply(object, [event || window.event].concat(args));
  }
}

Object.extend(Number.prototype, {
  toColorPart: function() {
    return this.toPaddedString(2, 16);
  },

  succ: function() {
    return this + 1;
  },

  times: function(iterator) {
    $R(0, this, true).each(iterator);
    return this;
  },

  toPaddedString: function(length, radix) {
    var string = this.toString(radix || 10);
    return '0'.times(length - string.length) + string;
  },

  toJSON: function() {
    return isFinite(this) ? this.toString() : 'null';
  }
});

Date.prototype.toJSON = function() {
  return '"' + this.getFullYear() + '-' +
    (this.getMonth() + 1).toPaddedString(2) + '-' +
    this.getDate().toPaddedString(2) + 'T' +
    this.getHours().toPaddedString(2) + ':' +
    this.getMinutes().toPaddedString(2) + ':' +
    this.getSeconds().toPaddedString(2) + '"';
};

var Try = {
  these: function() {
    var returnValue;

    for (var i = 0, length = arguments.length; i < length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) {}
    }

    return returnValue;
  }
}

/*--------------------------------------------------------------------------*/

var PeriodicalExecuter = Class.create();
PeriodicalExecuter.prototype = {
  initialize: function(callback, frequency) {
    this.callback = callback;
    this.frequency = frequency;
    this.currentlyExecuting = false;

    this.registerCallback();
  },

  registerCallback: function() {
    this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  stop: function() {
    if (!this.timer) return;
    clearInterval(this.timer);
    this.timer = null;
  },

  onTimerEvent: function() {
    if (!this.currentlyExecuting) {
      try {
        this.currentlyExecuting = true;
        this.callback(this);
      } finally {
        this.currentlyExecuting = false;
      }
    }
  }
}
Object.extend(String, {
  interpret: function(value) {
    return value == null ? '' : String(value);
  },
  specialChar: {
    '\b': '\\b',
    '\t': '\\t',
    '\n': '\\n',
    '\f': '\\f',
    '\r': '\\r',
    '\\': '\\\\'
  }
});

Object.extend(String.prototype, {
  gsub: function(pattern, replacement) {
    var result = '', source = this, match;
    replacement = arguments.callee.prepareReplacement(replacement);

    while (source.length > 0) {
      if (match = source.match(pattern)) {
        result += source.slice(0, match.index);
        result += String.interpret(replacement(match));
        source  = source.slice(match.index + match[0].length);
      } else {
        result += source, source = '';
      }
    }
    return result;
  },

  sub: function(pattern, replacement, count) {
    replacement = this.gsub.prepareReplacement(replacement);
    count = count === undefined ? 1 : count;

    return this.gsub(pattern, function(match) {
      if (--count < 0) return match[0];
      return replacement(match);
    });
  },

  scan: function(pattern, iterator) {
    this.gsub(pattern, iterator);
    return this;
  },

  truncate: function(length, truncation) {
    length = length || 30;
    truncation = truncation === undefined ? '...' : truncation;
    return this.length > length ?
      this.slice(0, length - truncation.length) + truncation : this;
  },

  strip: function() {
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
  },

  stripTags: function() {
    return this.replace(/<\/?[^>]+>/gi, '');
  },

  stripScripts: function() {
    return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
  },

  extractScripts: function() {
    var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
    var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
    return (this.match(matchAll) || []).map(function(scriptTag) {
      return (scriptTag.match(matchOne) || ['', ''])[1];
    });
  },

  evalScripts: function() {
    return this.extractScripts().map(function(script) { return eval(script) });
  },

  escapeHTML: function() {
    var self = arguments.callee;
    self.text.data = this;
    return self.div.innerHTML;
  },

  unescapeHTML: function() {
    var div = document.createElement('div');
    div.innerHTML = this.stripTags();
    return div.childNodes[0] ? (div.childNodes.length > 1 ?
      $A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue }) :
      div.childNodes[0].nodeValue) : '';
  },

  toQueryParams: function(separator) {
    var match = this.strip().match(/([^?#]*)(#.*)?$/);
    if (!match) return {};

    return match[1].split(separator || '&').inject({}, function(hash, pair) {
      if ((pair = pair.split('='))[0]) {
        var key = decodeURIComponent(pair.shift());
        var value = pair.length > 1 ? pair.join('=') : pair[0];
        if (value != undefined) value = decodeURIComponent(value);

        if (key in hash) {
          if (hash[key].constructor != Array) hash[key] = [hash[key]];
          hash[key].push(value);
        }
        else hash[key] = value;
      }
      return hash;
    });
  },

  toArray: function() {
    return this.split('');
  },

  succ: function() {
    return this.slice(0, this.length - 1) +
      String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
  },

  times: function(count) {
    var result = '';
    for (var i = 0; i < count; i++) result += this;
    return result;
  },

  camelize: function() {
    var parts = this.split('-'), len = parts.length;
    if (len == 1) return parts[0];

    var camelized = this.charAt(0) == '-'
      ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
      : parts[0];

    for (var i = 1; i < len; i++)
      camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);

    return camelized;
  },

  capitalize: function() {
    return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
  },

  underscore: function() {
    return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
  },

  dasherize: function() {
    return this.gsub(/_/,'-');
  },

  inspect: function(useDoubleQuotes) {
    var escapedString = this.gsub(/[\x00-\x1f\\]/, function(match) {
      var character = String.specialChar[match[0]];
      return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16);
    });
    if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
    return "'" + escapedString.replace(/'/g, '\\\'') + "'";
  },

  toJSON: function() {
    return this.inspect(true);
  },

  unfilterJSON: function(filter) {
    return this.sub(filter || Prototype.JSONFilter, '#{1}');
  },

  evalJSON: function(sanitize) {
    var json = this.unfilterJSON();
    try {
      if (!sanitize || (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(json)))
        return eval('(' + json + ')');
    } catch (e) { }
    throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
  },

  include: function(pattern) {
    return this.indexOf(pattern) > -1;
  },

  startsWith: function(pattern) {
    return this.indexOf(pattern) === 0;
  },

  endsWith: function(pattern) {
    var d = this.length - pattern.length;
    return d >= 0 && this.lastIndexOf(pattern) === d;
  },

  empty: function() {
    return this == '';
  },

  blank: function() {
    return /^\s*$/.test(this);
  }
});

if (Prototype.Browser.WebKit || Prototype.Browser.IE) Object.extend(String.prototype, {
  escapeHTML: function() {
    return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
  },
  unescapeHTML: function() {
    return this.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
  }
});

String.prototype.gsub.prepareReplacement = function(replacement) {
  if (typeof replacement == 'function') return replacement;
  var template = new Template(replacement);
  return function(match) { return template.evaluate(match) };
}

String.prototype.parseQuery = String.prototype.toQueryParams;

Object.extend(String.prototype.escapeHTML, {
  div:  document.createElement('div'),
  text: document.createTextNode('')
});

with (String.prototype.escapeHTML) div.appendChild(text);

var Template = Class.create();
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
Template.prototype = {
  initialize: function(template, pattern) {
    this.template = template.toString();
    this.pattern  = pattern || Template.Pattern;
  },

  evaluate: function(object) {
    return this.template.gsub(this.pattern, function(match) {
      var before = match[1];
      if (before == '\\') return match[2];
      return before + String.interpret(object[match[3]]);
    });
  }
}

var $break = {}, $continue = new Error('"throw $continue" is deprecated, use "return" instead');

var Enumerable = {
  each: function(iterator) {
    var index = 0;
    try {
      this._each(function(value) {
        iterator(value, index++);
      });
    } catch (e) {
      if (e != $break) throw e;
    }
    return this;
  },

  eachSlice: function(number, iterator) {
    var index = -number, slices = [], array = this.toArray();
    while ((index += number) < array.length)
      slices.push(array.slice(index, index+number));
    return slices.map(iterator);
  },

  all: function(iterator) {
    var result = true;
    this.each(function(value, index) {
      result = result && !!(iterator || Prototype.K)(value, index);
      if (!result) throw $break;
    });
    return result;
  },

  any: function(iterator) {
    var result = false;
    this.each(function(value, index) {
      if (result = !!(iterator || Prototype.K)(value, index))
        throw $break;
    });
    return result;
  },

  collect: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      results.push((iterator || Prototype.K)(value, index));
    });
    return results;
  },

  detect: function(iterator) {
    var result;
    this.each(function(value, index) {
      if (iterator(value, index)) {
        result = value;
        throw $break;
      }
    });
    return result;
  },

  findAll: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (iterator(value, index))
        results.push(value);
    });
    return results;
  },

  grep: function(pattern, iterator) {
    var results = [];
    this.each(function(value, index) {
      var stringValue = value.toString();
      if (stringValue.match(pattern))
        results.push((iterator || Prototype.K)(value, index));
    })
    return results;
  },

  include: function(object) {
    var found = false;
    this.each(function(value) {
      if (value == object) {
        found = true;
        throw $break;
      }
    });
    return found;
  },

  inGroupsOf: function(number, fillWith) {
    fillWith = fillWith === undefined ? null : fillWith;
    return this.eachSlice(number, function(slice) {
      while(slice.length < number) slice.push(fillWith);
      return slice;
    });
  },

  inject: function(memo, iterator) {
    this.each(function(value, index) {
      memo = iterator(memo, value, index);
    });
    return memo;
  },

  invoke: function(method) {
    var args = $A(arguments).slice(1);
    return this.map(function(value) {
      return value[method].apply(value, args);
    });
  },

  max: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (result == undefined || value >= result)
        result = value;
    });
    return result;
  },

  min: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (result == undefined || value < result)
        result = value;
    });
    return result;
  },

  partition: function(iterator) {
    var trues = [], falses = [];
    this.each(function(value, index) {
      ((iterator || Prototype.K)(value, index) ?
        trues : falses).push(value);
    });
    return [trues, falses];
  },

  pluck: function(property) {
    var results = [];
    this.each(function(value, index) {
      results.push(value[property]);
    });
    return results;
  },

  reject: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (!iterator(value, index))
        results.push(value);
    });
    return results;
  },

  sortBy: function(iterator) {
    return this.map(function(value, index) {
      return {value: value, criteria: iterator(value, index)};
    }).sort(function(left, right) {
      var a = left.criteria, b = right.criteria;
      return a < b ? -1 : a > b ? 1 : 0;
    }).pluck('value');
  },

  toArray: function() {
    return this.map();
  },

  zip: function() {
    var iterator = Prototype.K, args = $A(arguments);
    if (typeof args.last() == 'function')
      iterator = args.pop();

    var collections = [this].concat(args).map($A);
    return this.map(function(value, index) {
      return iterator(collections.pluck(index));
    });
  },

  size: function() {
    return this.toArray().length;
  },

  inspect: function() {
    return '#<Enumerable:' + this.toArray().inspect() + '>';
  }
}

Object.extend(Enumerable, {
  map:     Enumerable.collect,
  find:    Enumerable.detect,
  select:  Enumerable.findAll,
  member:  Enumerable.include,
  entries: Enumerable.toArray
});
var $A = Array.from = function(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) {
    return iterable.toArray();
  } else {
    var results = [];
    for (var i = 0, length = iterable.length; i < length; i++)
      results.push(iterable[i]);
    return results;
  }
}

if (Prototype.Browser.WebKit) {
  $A = Array.from = function(iterable) {
    if (!iterable) return [];
    if (!(typeof iterable == 'function' && iterable == '[object NodeList]') &&
      iterable.toArray) {
      return iterable.toArray();
    } else {
      var results = [];
      for (var i = 0, length = iterable.length; i < length; i++)
        results.push(iterable[i]);
      return results;
    }
  }
}

Object.extend(Array.prototype, Enumerable);

if (!Array.prototype._reverse)
  Array.prototype._reverse = Array.prototype.reverse;

Object.extend(Array.prototype, {
  _each: function(iterator) {
    for (var i = 0, length = this.length; i < length; i++)
      iterator(this[i]);
  },

  clear: function() {
    this.length = 0;
    return this;
  },

  first: function() {
    return this[0];
  },

  last: function() {
    return this[this.length - 1];
  },

  compact: function() {
    return this.select(function(value) {
      return value != null;
    });
  },

  flatten: function() {
    return this.inject([], function(array, value) {
      return array.concat(value && value.constructor == Array ?
        value.flatten() : [value]);
    });
  },

  without: function() {
    var values = $A(arguments);
    return this.select(function(value) {
      return !values.include(value);
    });
  },

  indexOf: function(object) {
    for (var i = 0, length = this.length; i < length; i++)
      if (this[i] == object) return i;
    return -1;
  },

  reverse: function(inline) {
    return (inline !== false ? this : this.toArray())._reverse();
  },

  reduce: function() {
    return this.length > 1 ? this : this[0];
  },

  uniq: function(sorted) {
    return this.inject([], function(array, value, index) {
      if (0 == index || (sorted ? array.last() != value : !array.include(value)))
        array.push(value);
      return array;
    });
  },

  clone: function() {
    return [].concat(this);
  },

  size: function() {
    return this.length;
  },

  inspect: function() {
    return '[' + this.map(Object.inspect).join(', ') + ']';
  },

  toJSON: function() {
    var results = [];
    this.each(function(object) {
      var value = Object.toJSON(object);
      if (value !== undefined) results.push(value);
    });
    return '[' + results.join(', ') + ']';
  }
});

Array.prototype.toArray = Array.prototype.clone;

function $w(string) {
  string = string.strip();
  return string ? string.split(/\s+/) : [];
}

if (Prototype.Browser.Opera){
  Array.prototype.concat = function() {
    var array = [];
    for (var i = 0, length = this.length; i < length; i++) array.push(this[i]);
    for (var i = 0, length = arguments.length; i < length; i++) {
      if (arguments[i].constructor == Array) {
        for (var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
          array.push(arguments[i][j]);
      } else {
        array.push(arguments[i]);
      }
    }
    return array;
  }
}
var Hash = function(object) {
  if (object instanceof Hash) this.merge(object);
  else Object.extend(this, object || {});
};

Object.extend(Hash, {
  toQueryString: function(obj) {
    var parts = [];
    parts.add = arguments.callee.addPair;

    this.prototype._each.call(obj, function(pair) {
      if (!pair.key) return;
      var value = pair.value;

      if (value && typeof value == 'object') {
        if (value.constructor == Array) value.each(function(value) {
          parts.add(pair.key, value);
        });
        return;
      }
      parts.add(pair.key, value);
    });

    return parts.join('&');
  },

  toJSON: function(object) {
    var results = [];
    this.prototype._each.call(object, function(pair) {
      var value = Object.toJSON(pair.value);
      if (value !== undefined) results.push(pair.key.toJSON() + ': ' + value);
    });
    return '{' + results.join(', ') + '}';
  }
});

Hash.toQueryString.addPair = function(key, value, prefix) {
  key = encodeURIComponent(key);
  if (value === undefined) this.push(key);
  else this.push(key + '=' + (value == null ? '' : encodeURIComponent(value)));
}

Object.extend(Hash.prototype, Enumerable);
Object.extend(Hash.prototype, {
  _each: function(iterator) {
    for (var key in this) {
      var value = this[key];
      if (value && value == Hash.prototype[key]) continue;

      var pair = [key, value];
      pair.key = key;
      pair.value = value;
      iterator(pair);
    }
  },

  keys: function() {
    return this.pluck('key');
  },

  values: function() {
    return this.pluck('value');
  },

  merge: function(hash) {
    return $H(hash).inject(this, function(mergedHash, pair) {
      mergedHash[pair.key] = pair.value;
      return mergedHash;
    });
  },

  remove: function() {
    var result;
    for(var i = 0, length = arguments.length; i < length; i++) {
      var value = this[arguments[i]];
      if (value !== undefined){
        if (result === undefined) result = value;
        else {
          if (result.constructor != Array) result = [result];
          result.push(value)
        }
      }
      delete this[arguments[i]];
    }
    return result;
  },

  toQueryString: function() {
    return Hash.toQueryString(this);
  },

  inspect: function() {
    return '#<Hash:{' + this.map(function(pair) {
      return pair.map(Object.inspect).join(': ');
    }).join(', ') + '}>';
  },

  toJSON: function() {
    return Hash.toJSON(this);
  }
});

function $H(object) {
  if (object instanceof Hash) return object;
  return new Hash(object);
};

// Safari iterates over shadowed properties
if (function() {
  var i = 0, Test = function(value) { this.key = value };
  Test.prototype.key = 'foo';
  for (var property in new Test('bar')) i++;
  return i > 1;
}()) Hash.prototype._each = function(iterator) {
  var cache = [];
  for (var key in this) {
    var value = this[key];
    if ((value && value == Hash.prototype[key]) || cache.include(key)) continue;
    cache.push(key);
    var pair = [key, value];
    pair.key = key;
    pair.value = value;
    iterator(pair);
  }
};
ObjectRange = Class.create();
Object.extend(ObjectRange.prototype, Enumerable);
Object.extend(ObjectRange.prototype, {
  initialize: function(start, end, exclusive) {
    this.start = start;
    this.end = end;
    this.exclusive = exclusive;
  },

  _each: function(iterator) {
    var value = this.start;
    while (this.include(value)) {
      iterator(value);
      value = value.succ();
    }
  },

  include: function(value) {
    if (value < this.start)
      return false;
    if (this.exclusive)
      return value < this.end;
    return value <= this.end;
  }
});

var $R = function(start, end, exclusive) {
  return new ObjectRange(start, end, exclusive);
}

var Ajax = {
  getTransport: function() {
    return Try.these(
      function() {return new XMLHttpRequest()},
      function() {return new ActiveXObject('Msxml2.XMLHTTP')},
      function() {return new ActiveXObject('Microsoft.XMLHTTP')}
    ) || false;
  },

  activeRequestCount: 0
}

Ajax.Responders = {
  responders: [],

  _each: function(iterator) {
    this.responders._each(iterator);
  },

  register: function(responder) {
    if (!this.include(responder))
      this.responders.push(responder);
  },

  unregister: function(responder) {
    this.responders = this.responders.without(responder);
  },

  dispatch: function(callback, request, transport, json) {
    this.each(function(responder) {
      if (typeof responder[callback] == 'function') {
        try {
          responder[callback].apply(responder, [request, transport, json]);
        } catch (e) {}
      }
    });
  }
};

Object.extend(Ajax.Responders, Enumerable);

Ajax.Responders.register({
  onCreate: function() {
    Ajax.activeRequestCount++;
  },
  onComplete: function() {
    Ajax.activeRequestCount--;
  }
});

Ajax.Base = function() {};
Ajax.Base.prototype = {
  setOptions: function(options) {
    this.options = {
      method:       'post',
      asynchronous: true,
      contentType:  'application/x-www-form-urlencoded',
      encoding:     'UTF-8',
      parameters:   ''
    }
    Object.extend(this.options, options || {});

    this.options.method = this.options.method.toLowerCase();
    if (typeof this.options.parameters == 'string')
      this.options.parameters = this.options.parameters.toQueryParams();
  }
}

Ajax.Request = Class.create();
Ajax.Request.Events =
  ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];

Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
  _complete: false,

  initialize: function(url, options) {
    this.transport = Ajax.getTransport();
    this.setOptions(options);
    this.request(url);
  },

  request: function(url) {
    this.url = url;
    this.method = this.options.method;
    var params = Object.clone(this.options.parameters);

    if (!['get', 'post'].include(this.method)) {
      // simulate other verbs over post
      params['_method'] = this.method;
      this.method = 'post';
    }

    this.parameters = params;

    if (params = Hash.toQueryString(params)) {
      // when GET, append parameters to URL
      if (this.method == 'get')
        this.url += (this.url.include('?') ? '&' : '?') + params;
      else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent))
        params += '&_=';
    }

    try {
      if (this.options.onCreate) this.options.onCreate(this.transport);
      Ajax.Responders.dispatch('onCreate', this, this.transport);

      this.transport.open(this.method.toUpperCase(), this.url,
        this.options.asynchronous);

      if (this.options.asynchronous)
        setTimeout(function() { this.respondToReadyState(1) }.bind(this), 10);

      this.transport.onreadystatechange = this.onStateChange.bind(this);
      this.setRequestHeaders();

      this.body = this.method == 'post' ? (this.options.postBody || params) : null;
      this.transport.send(this.body);

      /* Force Firefox to handle ready state 4 for synchronous requests */
      if (!this.options.asynchronous && this.transport.overrideMimeType)
        this.onStateChange();

    }
    catch (e) {
      this.dispatchException(e);
    }
  },

  onStateChange: function() {
    var readyState = this.transport.readyState;
    if (readyState > 1 && !((readyState == 4) && this._complete))
      this.respondToReadyState(this.transport.readyState);
  },

  setRequestHeaders: function() {
    var headers = {
      'X-Requested-With': 'XMLHttpRequest',
      'X-Prototype-Version': Prototype.Version,
      'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
    };

    if (this.method == 'post') {
      headers['Content-type'] = this.options.contentType +
        (this.options.encoding ? '; charset=' + this.options.encoding : '');

      /* Force "Connection: close" for older Mozilla browsers to work
       * around a bug where XMLHttpRequest sends an incorrect
       * Content-length header. See Mozilla Bugzilla #246651.
       */
      if (this.transport.overrideMimeType &&
          (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
            headers['Connection'] = 'close';
    }

    // user-defined headers
    if (typeof this.options.requestHeaders == 'object') {
      var extras = this.options.requestHeaders;

      if (typeof extras.push == 'function')
        for (var i = 0, length = extras.length; i < length; i += 2)
          headers[extras[i]] = extras[i+1];
      else
        $H(extras).each(function(pair) { headers[pair.key] = pair.value });
    }

    for (var name in headers)
      this.transport.setRequestHeader(name, headers[name]);
  },

  success: function() {
    return !this.transport.status
        || (this.transport.status >= 200 && this.transport.status < 300);
  },

  respondToReadyState: function(readyState) {
    var state = Ajax.Request.Events[readyState];
    var transport = this.transport, json = this.evalJSON();

    if (state == 'Complete') {
      try {
        this._complete = true;
        (this.options['on' + this.transport.status]
         || this.options['on' + (this.success() ? 'Success' : 'Failure')]
         || Prototype.emptyFunction)(transport, json);
      } catch (e) {
        this.dispatchException(e);
      }

      var contentType = this.getHeader('Content-type');
      if (contentType && contentType.strip().
        match(/^(text|application)\/(x-)?(java|ecma)script(;.*)?$/i))
          this.evalResponse();
    }

    try {
      (this.options['on' + state] || Prototype.emptyFunction)(transport, json);
      Ajax.Responders.dispatch('on' + state, this, transport, json);
    } catch (e) {
      this.dispatchException(e);
    }

    if (state == 'Complete') {
      // avoid memory leak in MSIE: clean up
      this.transport.onreadystatechange = Prototype.emptyFunction;
    }
  },

  getHeader: function(name) {
    try {
      return this.transport.getResponseHeader(name);
    } catch (e) { return null }
  },

  evalJSON: function() {
    try {
      var json = this.getHeader('X-JSON');
      return json ? json.evalJSON() : null;
    } catch (e) { return null }
  },

  evalResponse: function() {
    try {
      return eval((this.transport.responseText || '').unfilterJSON());
    } catch (e) {
      this.dispatchException(e);
    }
  },

  dispatchException: function(exception) {
    (this.options.onException || Prototype.emptyFunction)(this, exception);
    Ajax.Responders.dispatch('onException', this, exception);
  }
});

Ajax.Updater = Class.create();

Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), {
  initialize: function(container, url, options) {
    this.container = {
      success: (container.success || container),
      failure: (container.failure || (container.success ? null : container))
    }

    this.transport = Ajax.getTransport();
    this.setOptions(options);

    var onComplete = this.options.onComplete || Prototype.emptyFunction;
    this.options.onComplete = (function(transport, param) {
      this.updateContent();
      onComplete(transport, param);
    }).bind(this);

    this.request(url);
  },

  updateContent: function() {
    var receiver = this.container[this.success() ? 'success' : 'failure'];
    var response = this.transport.responseText;

    if (!this.options.evalScripts) response = response.stripScripts();

    if (receiver = $(receiver)) {
      if (this.options.insertion)
        new this.options.insertion(receiver, response);
      else
        receiver.update(response);
    }

    if (this.success()) {
      if (this.onComplete)
        setTimeout(this.onComplete.bind(this), 10);
    }
  }
});

Ajax.PeriodicalUpdater = Class.create();
Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), {
  initialize: function(container, url, options) {
    this.setOptions(options);
    this.onComplete = this.options.onComplete;

    this.frequency = (this.options.frequency || 2);
    this.decay = (this.options.decay || 1);

    this.updater = {};
    this.container = container;
    this.url = url;

    this.start();
  },

  start: function() {
    this.options.onComplete = this.updateComplete.bind(this);
    this.onTimerEvent();
  },

  stop: function() {
    this.updater.options.onComplete = undefined;
    clearTimeout(this.timer);
    (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
  },

  updateComplete: function(request) {
    if (this.options.decay) {
      this.decay = (request.responseText == this.lastText ?
        this.decay * this.options.decay : 1);

      this.lastText = request.responseText;
    }
    this.timer = setTimeout(this.onTimerEvent.bind(this),
      this.decay * this.frequency * 1000);
  },

  onTimerEvent: function() {
    this.updater = new Ajax.Updater(this.container, this.url, this.options);
  }
});
function $(element) {
  if (arguments.length > 1) {
    for (var i = 0, elements = [], length = arguments.length; i < length; i++)
      elements.push($(arguments[i]));
    return elements;
  }
  if (typeof element == 'string')
    element = document.getElementById(element);
  return Element.extend(element);
}

if (Prototype.BrowserFeatures.XPath) {
  document._getElementsByXPath = function(expression, parentElement) {
    var results = [];
    var query = document.evaluate(expression, $(parentElement) || document,
      null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    for (var i = 0, length = query.snapshotLength; i < length; i++)
      results.push(query.snapshotItem(i));
    return results;
  };

  document.getElementsByClassName = function(className, parentElement) {
    var q = ".//*[contains(concat(' ', @class, ' '), ' " + className + " ')]";
    return document._getElementsByXPath(q, parentElement);
  }

} else document.getElementsByClassName = function(className, parentElement) {
  var children = ($(parentElement) || document.body).getElementsByTagName('*');
  var elements = [], child;
  for (var i = 0, length = children.length; i < length; i++) {
    child = children[i];
    if (Element.hasClassName(child, className))
      elements.push(Element.extend(child));
  }
  return elements;
};

/*--------------------------------------------------------------------------*/

if (!window.Element) var Element = {};

Element.extend = function(element) {
  var F = Prototype.BrowserFeatures;
  if (!element || !element.tagName || element.nodeType == 3 ||
   element._extended || F.SpecificElementExtensions || element == window)
    return element;

  var methods = {}, tagName = element.tagName, cache = Element.extend.cache,
   T = Element.Methods.ByTag;

  // extend methods for all tags (Safari doesn't need this)
  if (!F.ElementExtensions) {
    Object.extend(methods, Element.Methods),
    Object.extend(methods, Element.Methods.Simulated);
  }

  // extend methods for specific tags
  if (T[tagName]) Object.extend(methods, T[tagName]);

  for (var property in methods) {
    var value = methods[property];
    if (typeof value == 'function' && !(property in element))
      element[property] = cache.findOrStore(value);
  }

  element._extended = Prototype.emptyFunction;
  return element;
};

Element.extend.cache = {
  findOrStore: function(value) {
    return this[value] = this[value] || function() {
      return value.apply(null, [this].concat($A(arguments)));
    }
  }
};

Element.Methods = {
  visible: function(element) {
    return $(element).style.display != 'none';
  },

  toggle: function(element) {
    element = $(element);
    Element[Element.visible(element) ? 'hide' : 'show'](element);
    return element;
  },

  hide: function(element) {
    $(element).style.display = 'none';
    return element;
  },

  show: function(element) {
    $(element).style.display = '';
    return element;
  },

  remove: function(element) {
    element = $(element);
    element.parentNode.removeChild(element);
    return element;
  },

  update: function(element, html) {
    html = typeof html == 'undefined' ? '' : html.toString();
    $(element).innerHTML = html.stripScripts();
    setTimeout(function() {html.evalScripts()}, 10);
    return element;
  },

  replace: function(element, html) {
    element = $(element);
    html = typeof html == 'undefined' ? '' : html.toString();
    if (element.outerHTML) {
      element.outerHTML = html.stripScripts();
    } else {
      var range = element.ownerDocument.createRange();
      range.selectNodeContents(element);
      element.parentNode.replaceChild(
        range.createContextualFragment(html.stripScripts()), element);
    }
    setTimeout(function() {html.evalScripts()}, 10);
    return element;
  },

  inspect: function(element) {
    element = $(element);
    var result = '<' + element.tagName.toLowerCase();
    $H({'id': 'id', 'className': 'class'}).each(function(pair) {
      var property = pair.first(), attribute = pair.last();
      var value = (element[property] || '').toString();
      if (value) result += ' ' + attribute + '=' + value.inspect(true);
    });
    return result + '>';
  },

  recursivelyCollect: function(element, property) {
    element = $(element);
    var elements = [];
    while (element = element[property])
      if (element.nodeType == 1)
        elements.push(Element.extend(element));
    return elements;
  },

  ancestors: function(element) {
    return $(element).recursivelyCollect('parentNode');
  },

  descendants: function(element) {
    return $A($(element).getElementsByTagName('*')).each(Element.extend);
  },

  firstDescendant: function(element) {
    element = $(element).firstChild;
    while (element && element.nodeType != 1) element = element.nextSibling;
    return $(element);
  },

  immediateDescendants: function(element) {
    if (!(element = $(element).firstChild)) return [];
    while (element && element.nodeType != 1) element = element.nextSibling;
    if (element) return [element].concat($(element).nextSiblings());
    return [];
  },

  previousSiblings: function(element) {
    return $(element).recursivelyCollect('previousSibling');
  },

  nextSiblings: function(element) {
    return $(element).recursivelyCollect('nextSibling');
  },

  siblings: function(element) {
    element = $(element);
    return element.previousSiblings().reverse().concat(element.nextSiblings());
  },

  match: function(element, selector) {
    if (typeof selector == 'string')
      selector = new Selector(selector);
    return selector.match($(element));
  },

  up: function(element, expression, index) {
    element = $(element);
    if (arguments.length == 1) return $(element.parentNode);
    var ancestors = element.ancestors();
    return expression ? Selector.findElement(ancestors, expression, index) :
      ancestors[index || 0];
  },

  down: function(element, expression, index) {
    element = $(element);
    if (arguments.length == 1) return element.firstDescendant();
    var descendants = element.descendants();
    return expression ? Selector.findElement(descendants, expression, index) :
      descendants[index || 0];
  },

  previous: function(element, expression, index) {
    element = $(element);
    if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element));
    var previousSiblings = element.previousSiblings();
    return expression ? Selector.findElement(previousSiblings, expression, index) :
      previousSiblings[index || 0];
  },

  next: function(element, expression, index) {
    element = $(element);
    if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element));
    var nextSiblings = element.nextSiblings();
    return expression ? Selector.findElement(nextSiblings, expression, index) :
      nextSiblings[index || 0];
  },

  getElementsBySelector: function() {
    var args = $A(arguments), element = $(args.shift());
    return Selector.findChildElements(element, args);
  },

  getElementsByClassName: function(element, className) {
    return document.getElementsByClassName(className, element);
  },

  readAttribute: function(element, name) {
    element = $(element);
    if (Prototype.Browser.IE) {
      if (!element.attributes) return null;
      var t = Element._attributeTranslations;
      if (t.values[name]) return t.values[name](element, name);
      if (t.names[name])  name = t.names[name];
      var attribute = element.attributes[name];
      return attribute ? attribute.nodeValue : null;
    }
    return element.getAttribute(name);
  },

  getHeight: function(element) {
    return $(element).getDimensions().height;
  },

  getWidth: function(element) {
    return $(element).getDimensions().width;
  },

  classNames: function(element) {
    return new Element.ClassNames(element);
  },

  hasClassName: function(element, className) {
    if (!(element = $(element))) return;
    var elementClassName = element.className;
    if (elementClassName.length == 0) return false;
    if (elementClassName == className ||
        elementClassName.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
      return true;
    return false;
  },

  addClassName: function(element, className) {
    if (!(element = $(element))) return;
    Element.classNames(element).add(className);
    return element;
  },

  removeClassName: function(element, className) {
    if (!(element = $(element))) return;
    Element.classNames(element).remove(className);
    return element;
  },

  toggleClassName: function(element, className) {
    if (!(element = $(element))) return;
    Element.classNames(element)[element.hasClassName(className) ? 'remove' : 'add'](className);
    return element;
  },

  observe: function() {
    Event.observe.apply(Event, arguments);
    return $A(arguments).first();
  },

  stopObserving: function() {
    Event.stopObserving.apply(Event, arguments);
    return $A(arguments).first();
  },

  // removes whitespace-only text node children
  cleanWhitespace: function(element) {
    element = $(element);
    var node = element.firstChild;
    while (node) {
      var nextNode = node.nextSibling;
      if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
        element.removeChild(node);
      node = nextNode;
    }
    return element;
  },

  empty: function(element) {
    return $(element).innerHTML.blank();
  },

  descendantOf: function(element, ancestor) {
    element = $(element), ancestor = $(ancestor);
    while (element = element.parentNode)
      if (element == ancestor) return true;
    return false;
  },

  scrollTo: function(element) {
    element = $(element);
    var pos = Position.cumulativeOffset(element);
    window.scrollTo(pos[0], pos[1]);
    return element;
  },

  getStyle: function(element, style) {
    element = $(element);
    style = style == 'float' ? 'cssFloat' : style.camelize();
    var value = element.style[style];
    if (!value) {
      var css = document.defaultView.getComputedStyle(element, null);
      value = css ? css[style] : null;
    }
    if (style == 'opacity') return value ? parseFloat(value) : 1.0;
    return value == 'auto' ? null : value;
  },

  getOpacity: function(element) {
    return $(element).getStyle('opacity');
  },

  setStyle: function(element, styles, camelized) {
    element = $(element);
    var elementStyle = element.style;

    for (var property in styles)
      if (property == 'opacity') element.setOpacity(styles[property])
      else
        elementStyle[(property == 'float' || property == 'cssFloat') ?
          (elementStyle.styleFloat === undefined ? 'cssFloat' : 'styleFloat') :
          (camelized ? property : property.camelize())] = styles[property];

    return element;
  },

  setOpacity: function(element, value) {
    element = $(element);
    element.style.opacity = (value == 1 || value === '') ? '' :
      (value < 0.00001) ? 0 : value;
    return element;
  },

  getDimensions: function(element) {
    element = $(element);
    var display = $(element).getStyle('display');
    if (display != 'none' && display != null) // Safari bug
      return {width: element.offsetWidth, height: element.offsetHeight};

    // All *Width and *Height properties give 0 on elements with display none,
    // so enable the element temporarily
    var els = element.style;
    var originalVisibility = els.visibility;
    var originalPosition = els.position;
    var originalDisplay = els.display;
    els.visibility = 'hidden';
    els.position = 'absolute';
    els.display = 'block';
    var originalWidth = element.clientWidth;
    var originalHeight = element.clientHeight;
    els.display = originalDisplay;
    els.position = originalPosition;
    els.visibility = originalVisibility;
    return {width: originalWidth, height: originalHeight};
  },

  makePositioned: function(element) {
    element = $(element);
    var pos = Element.getStyle(element, 'position');
    if (pos == 'static' || !pos) {
      element._madePositioned = true;
      element.style.position = 'relative';
      // Opera returns the offset relative to the positioning context, when an
      // element is position relative but top and left have not been defined
      if (window.opera) {
        element.style.top = 0;
        element.style.left = 0;
      }
    }
    return element;
  },

  undoPositioned: function(element) {
    element = $(element);
    if (element._madePositioned) {
      element._madePositioned = undefined;
      element.style.position =
        element.style.top =
        element.style.left =
        element.style.bottom =
        element.style.right = '';
    }
    return element;
  },

  makeClipping: function(element) {
    element = $(element);
    if (element._overflow) return element;
    element._overflow = element.style.overflow || 'auto';
    if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden')
      element.style.overflow = 'hidden';
    return element;
  },

  undoClipping: function(element) {
    element = $(element);
    if (!element._overflow) return element;
    element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
    element._overflow = null;
    return element;
  }
};

Object.extend(Element.Methods, {
  childOf: Element.Methods.descendantOf,
  childElements: Element.Methods.immediateDescendants
});

if (Prototype.Browser.Opera) {
  Element.Methods._getStyle = Element.Methods.getStyle;
  Element.Methods.getStyle = function(element, style) {
    switch(style) {
      case 'left':
      case 'top':
      case 'right':
      case 'bottom':
        if (Element._getStyle(element, 'position') == 'static') return null;
      default: return Element._getStyle(element, style);
    }
  };
}
else if (Prototype.Browser.IE) {
  Element.Methods.getStyle = function(element, style) {
    element = $(element);
    style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize();
    var value = element.style[style];
    if (!value && element.currentStyle) value = element.currentStyle[style];

    if (style == 'opacity') {
      if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
        if (value[1]) return parseFloat(value[1]) / 100;
      return 1.0;
    }

    if (value == 'auto') {
      if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none'))
        return element['offset'+style.capitalize()] + 'px';
      return null;
    }
    return value;
  };

  Element.Methods.setOpacity = function(element, value) {
    element = $(element);
    var filter = element.getStyle('filter'), style = element.style;
    if (value == 1 || value === '') {
      style.filter = filter.replace(/alpha\([^\)]*\)/gi,'');
      return element;
    } else if (value < 0.00001) value = 0;
    style.filter = filter.replace(/alpha\([^\)]*\)/gi, '') +
      'alpha(opacity=' + (value * 100) + ')';
    return element;
  };

  // IE is missing .innerHTML support for TABLE-related elements
  Element.Methods.update = function(element, html) {
    element = $(element);
    html = typeof html == 'undefined' ? '' : html.toString();
    var tagName = element.tagName.toUpperCase();
    if (['THEAD','TBODY','TR','TD'].include(tagName)) {
      var div = document.createElement('div');
      switch (tagName) {
        case 'THEAD':
        case 'TBODY':
          div.innerHTML = '<table><tbody>' +  html.stripScripts() + '</tbody></table>';
          depth = 2;
          break;
        case 'TR':
          div.innerHTML = '<table><tbody><tr>' +  html.stripScripts() + '</tr></tbody></table>';
          depth = 3;
          break;
        case 'TD':
          div.innerHTML = '<table><tbody><tr><td>' +  html.stripScripts() + '</td></tr></tbody></table>';
          depth = 4;
      }
      $A(element.childNodes).each(function(node) { element.removeChild(node) });
      depth.times(function() { div = div.firstChild });
      $A(div.childNodes).each(function(node) { element.appendChild(node) });
    } else {
      element.innerHTML = html.stripScripts();
    }
    setTimeout(function() { html.evalScripts() }, 10);
    return element;
  }
}
else if (Prototype.Browser.Gecko) {
  Element.Methods.setOpacity = function(element, value) {
    element = $(element);
    element.style.opacity = (value == 1) ? 0.999999 :
      (value === '') ? '' : (value < 0.00001) ? 0 : value;
    return element;
  };
}

Element._attributeTranslations = {
  names: {
    colspan:   "colSpan",
    rowspan:   "rowSpan",
    valign:    "vAlign",
    datetime:  "dateTime",
    accesskey: "accessKey",
    tabindex:  "tabIndex",
    enctype:   "encType",
    maxlength: "maxLength",
    readonly:  "readOnly",
    longdesc:  "longDesc"
  },
  values: {
    _getAttr: function(element, attribute) {
      return element.getAttribute(attribute, 2);
    },
    _flag: function(element, attribute) {
      return $(element).hasAttribute(attribute) ? attribute : null;
    },
    style: function(element) {
      return element.style.cssText.toLowerCase();
    },
    title: function(element) {
      var node = element.getAttributeNode('title');
      return node.specified ? node.nodeValue : null;
    }
  }
};

(function() {
  Object.extend(this, {
    href: this._getAttr,
    src:  this._getAttr,
    type: this._getAttr,
    disabled: this._flag,
    checked:  this._flag,
    readonly: this._flag,
    multiple: this._flag
  });
}).call(Element._attributeTranslations.values);

Element.Methods.Simulated = {
  hasAttribute: function(element, attribute) {
    var t = Element._attributeTranslations, node;
    attribute = t.names[attribute] || attribute;
    node = $(element).getAttributeNode(attribute);
    return node && node.specified;
  }
};

Element.Methods.ByTag = {};

Object.extend(Element, Element.Methods);

if (!Prototype.BrowserFeatures.ElementExtensions &&
 document.createElement('div').__proto__) {
  window.HTMLElement = {};
  window.HTMLElement.prototype = document.createElement('div').__proto__;
  Prototype.BrowserFeatures.ElementExtensions = true;
}

Element.hasAttribute = function(element, attribute) {
  if (element.hasAttribute) return element.hasAttribute(attribute);
  return Element.Methods.Simulated.hasAttribute(element, attribute);
};

Element.addMethods = function(methods) {
  var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag;

  if (!methods) {
    Object.extend(Form, Form.Methods);
    Object.extend(Form.Element, Form.Element.Methods);
    Object.extend(Element.Methods.ByTag, {
      "FORM":     Object.clone(Form.Methods),
      "INPUT":    Object.clone(Form.Element.Methods),
      "SELECT":   Object.clone(Form.Element.Methods),
      "TEXTAREA": Object.clone(Form.Element.Methods)
    });
  }

  if (arguments.length == 2) {
    var tagName = methods;
    methods = arguments[1];
  }

  if (!tagName) Object.extend(Element.Methods, methods || {});
  else {
    if (tagName.constructor == Array) tagName.each(extend);
    else extend(tagName);
  }

  function extend(tagName) {
    tagName = tagName.toUpperCase();
    if (!Element.Methods.ByTag[tagName])
      Element.Methods.ByTag[tagName] = {};
    Object.extend(Element.Methods.ByTag[tagName], methods);
  }

  function copy(methods, destination, onlyIfAbsent) {
    onlyIfAbsent = onlyIfAbsent || false;
    var cache = Element.extend.cache;
    for (var property in methods) {
      var value = methods[property];
      if (!onlyIfAbsent || !(property in destination))
        destination[property] = cache.findOrStore(value);
    }
  }

  function findDOMClass(tagName) {
    var klass;
    var trans = {
      "OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph",
      "FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList",
      "DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading",
      "H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote",
      "INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION":
      "TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD":
      "TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR":
      "TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET":
      "FrameSet", "IFRAME": "IFrame"
    };
    if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element';
    if (window[klass]) return window[klass];
    klass = 'HTML' + tagName + 'Element';
    if (window[klass]) return window[klass];
    klass = 'HTML' + tagName.capitalize() + 'Element';
    if (window[klass]) return window[klass];

    window[klass] = {};
    window[klass].prototype = document.createElement(tagName).__proto__;
    return window[klass];
  }

  if (F.ElementExtensions) {
    copy(Element.Methods, HTMLElement.prototype);
    copy(Element.Methods.Simulated, HTMLElement.prototype, true);
  }

  if (F.SpecificElementExtensions) {
    for (var tag in Element.Methods.ByTag) {
      var klass = findDOMClass(tag);
      if (typeof klass == "undefined") continue;
      copy(T[tag], klass.prototype);
    }
  }

  Object.extend(Element, Element.Methods);
  delete Element.ByTag;
};

var Toggle = { display: Element.toggle };

/*--------------------------------------------------------------------------*/

Abstract.Insertion = function(adjacency) {
  this.adjacency = adjacency;
}

Abstract.Insertion.prototype = {
  initialize: function(element, content) {
    this.element = $(element);
    this.content = content.stripScripts();

    if (this.adjacency && this.element.insertAdjacentHTML) {
      try {
        this.element.insertAdjacentHTML(this.adjacency, this.content);
      } catch (e) {
        var tagName = this.element.tagName.toUpperCase();
        if (['TBODY', 'TR'].include(tagName)) {
          this.insertContent(this.contentFromAnonymousTable());
        } else {
          throw e;
        }
      }
    } else {
      this.range = this.element.ownerDocument.createRange();
      if (this.initializeRange) this.initializeRange();
      this.insertContent([this.range.createContextualFragment(this.content)]);
    }

    setTimeout(function() {content.evalScripts()}, 10);
  },

  contentFromAnonymousTable: function() {
    var div = document.createElement('div');
    div.innerHTML = '<table><tbody>' + this.content + '</tbody></table>';
    return $A(div.childNodes[0].childNodes[0].childNodes);
  }
}

var Insertion = new Object();

Insertion.Before = Class.create();
Insertion.Before.prototype = Object.extend(new Abstract.Insertion('beforeBegin'), {
  initializeRange: function() {
    this.range.setStartBefore(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.parentNode.insertBefore(fragment, this.element);
    }).bind(this));
  }
});

Insertion.Top = Class.create();
Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), {
  initializeRange: function() {
    this.range.selectNodeContents(this.element);
    this.range.collapse(true);
  },

  insertContent: function(fragments) {
    fragments.reverse(false).each((function(fragment) {
      this.element.insertBefore(fragment, this.element.firstChild);
    }).bind(this));
  }
});

Insertion.Bottom = Class.create();
Insertion.Bottom.prototype = Object.extend(new Abstract.Insertion('beforeEnd'), {
  initializeRange: function() {
    this.range.selectNodeContents(this.element);
    this.range.collapse(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.appendChild(fragment);
    }).bind(this));
  }
});

Insertion.After = Class.create();
Insertion.After.prototype = Object.extend(new Abstract.Insertion('afterEnd'), {
  initializeRange: function() {
    this.range.setStartAfter(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.parentNode.insertBefore(fragment,
        this.element.nextSibling);
    }).bind(this));
  }
});

/*--------------------------------------------------------------------------*/

Element.ClassNames = Class.create();
Element.ClassNames.prototype = {
  initialize: function(element) {
    this.element = $(element);
  },

  _each: function(iterator) {
    this.element.className.split(/\s+/).select(function(name) {
      return name.length > 0;
    })._each(iterator);
  },

  set: function(className) {
    this.element.className = className;
  },

  add: function(classNameToAdd) {
    if (this.include(classNameToAdd)) return;
    this.set($A(this).concat(classNameToAdd).join(' '));
  },

  remove: function(classNameToRemove) {
    if (!this.include(classNameToRemove)) return;
    this.set($A(this).without(classNameToRemove).join(' '));
  },

  toString: function() {
    return $A(this).join(' ');
  }
};

Object.extend(Element.ClassNames.prototype, Enumerable);
/* Portions of the Selector class are derived from Jack SlocumвЂ™s DomQuery,
 * part of YUI-Ext version 0.40, distributed under the terms of an MIT-style
 * license.  Please see http://www.yui-ext.com/ for more information. */

var Selector = Class.create();

Selector.prototype = {
  initialize: function(expression) {
    this.expression = expression.strip();
    this.compileMatcher();
  },

  compileMatcher: function() {
    // Selectors with namespaced attributes can't use the XPath version
    if (Prototype.BrowserFeatures.XPath && !(/\[[\w-]*?:/).test(this.expression))
      return this.compileXPathMatcher();

    var e = this.expression, ps = Selector.patterns, h = Selector.handlers,
        c = Selector.criteria, le, p, m;

    if (Selector._cache[e]) {
      this.matcher = Selector._cache[e]; return;
    }
    this.matcher = ["this.matcher = function(root) {",
                    "var r = root, h = Selector.handlers, c = false, n;"];

    while (e && le != e && (/\S/).test(e)) {
      le = e;
      for (var i in ps) {
        p = ps[i];
        if (m = e.match(p)) {
          this.matcher.push(typeof c[i] == 'function' ? c[i](m) :
              new Template(c[i]).evaluate(m));
          e = e.replace(m[0], '');
          break;
        }
      }
    }

    this.matcher.push("return h.unique(n);\n}");
    eval(this.matcher.join('\n'));
    Selector._cache[this.expression] = this.matcher;
  },

  compileXPathMatcher: function() {
    var e = this.expression, ps = Selector.patterns,
        x = Selector.xpath, le,  m;

    if (Selector._cache[e]) {
      this.xpath = Selector._cache[e]; return;
    }

    this.matcher = ['.//*'];
    while (e && le != e && (/\S/).test(e)) {
      le = e;
      for (var i in ps) {
        if (m = e.match(ps[i])) {
          this.matcher.push(typeof x[i] == 'function' ? x[i](m) :
            new Template(x[i]).evaluate(m));
          e = e.replace(m[0], '');
          break;
        }
      }
    }

    this.xpath = this.matcher.join('');
    Selector._cache[this.expression] = this.xpath;
  },

  findElements: function(root) {
    root = root || document;
    if (this.xpath) return document._getElementsByXPath(this.xpath, root);
    return this.matcher(root);
  },

  match: function(element) {
    return this.findElements(document).include(element);
  },

  toString: function() {
    return this.expression;
  },

  inspect: function() {
    return "#<Selector:" + this.expression.inspect() + ">";
  }
};

Object.extend(Selector, {
  _cache: {},

  xpath: {
    descendant:   "//*",
    child:        "/*",
    adjacent:     "/following-sibling::*[1]",
    laterSibling: '/following-sibling::*',
    tagName:      function(m) {
      if (m[1] == '*') return '';
      return "[local-name()='" + m[1].toLowerCase() +
             "' or local-name()='" + m[1].toUpperCase() + "']";
    },
    className:    "[contains(concat(' ', @class, ' '), ' #{1} ')]",
    id:           "[@id='#{1}']",
    attrPresence: "[@#{1}]",
    attr: function(m) {
      m[3] = m[5] || m[6];
      return new Template(Selector.xpath.operators[m[2]]).evaluate(m);
    },
    pseudo: function(m) {
      var h = Selector.xpath.pseudos[m[1]];
      if (!h) return '';
      if (typeof h === 'function') return h(m);
      return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m);
    },
    operators: {
      '=':  "[@#{1}='#{3}']",
      '!=': "[@#{1}!='#{3}']",
      '^=': "[starts-with(@#{1}, '#{3}')]",
      '$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']",
      '*=': "[contains(@#{1}, '#{3}')]",
      '~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]",
      '|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]"
    },
    pseudos: {
      'first-child': '[not(preceding-sibling::*)]',
      'last-child':  '[not(following-sibling::*)]',
      'only-child':  '[not(preceding-sibling::* or following-sibling::*)]',
      'empty':       "[count(*) = 0 and (count(text()) = 0 or translate(text(), ' \t\r\n', '') = '')]",
      'checked':     "[@checked]",
      'disabled':    "[@disabled]",
      'enabled':     "[not(@disabled)]",
      'not': function(m) {
        var e = m[6], p = Selector.patterns,
            x = Selector.xpath, le, m, v;

        var exclusion = [];
        while (e && le != e && (/\S/).test(e)) {
          le = e;
          for (var i in p) {
            if (m = e.match(p[i])) {
              v = typeof x[i] == 'function' ? x[i](m) : new Template(x[i]).evaluate(m);
              exclusion.push("(" + v.substring(1, v.length - 1) + ")");
              e = e.replace(m[0], '');
              break;
            }
          }
        }
        return "[not(" + exclusion.join(" and ") + ")]";
      },
      'nth-child':      function(m) {
        return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m);
      },
      'nth-last-child': function(m) {
        return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m);
      },
      'nth-of-type':    function(m) {
        return Selector.xpath.pseudos.nth("position() ", m);
      },
      'nth-last-of-type': function(m) {
        return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m);
      },
      'first-of-type':  function(m) {
        m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m);
      },
      'last-of-type':   function(m) {
        m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m);
      },
      'only-of-type':   function(m) {
        var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m);
      },
      nth: function(fragment, m) {
        var mm, formula = m[6], predicate;
        if (formula == 'even') formula = '2n+0';
        if (formula == 'odd')  formula = '2n+1';
        if (mm = formula.match(/^(\d+)$/)) // digit only
          return '[' + fragment + "= " + mm[1] + ']';
        if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
          if (mm[1] == "-") mm[1] = -1;
          var a = mm[1] ? Number(mm[1]) : 1;
          var b = mm[2] ? Number(mm[2]) : 0;
          predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " +
          "((#{fragment} - #{b}) div #{a} >= 0)]";
          return new Template(predicate).evaluate({
            fragment: fragment, a: a, b: b });
        }
      }
    }
  },

  criteria: {
    tagName:      'n = h.tagName(n, r, "#{1}", c);   c = false;',
    className:    'n = h.className(n, r, "#{1}", c); c = false;',
    id:           'n = h.id(n, r, "#{1}", c);        c = false;',
    attrPresence: 'n = h.attrPresence(n, r, "#{1}"); c = false;',
    attr: function(m) {
      m[3] = (m[5] || m[6]);
      return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}"); c = false;').evaluate(m);
    },
    pseudo:       function(m) {
      if (m[6]) m[6] = m[6].replace(/"/g, '\\"');
      return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m);
    },
    descendant:   'c = "descendant";',
    child:        'c = "child";',
    adjacent:     'c = "adjacent";',
    laterSibling: 'c = "laterSibling";'
  },

  patterns: {
    // combinators must be listed first
    // (and descendant needs to be last combinator)
    laterSibling: /^\s*~\s*/,
    child:        /^\s*>\s*/,
    adjacent:     /^\s*\+\s*/,
    descendant:   /^\s/,

    // selectors follow
    tagName:      /^\s*(\*|[\w\-]+)(\b|$)?/,
    id:           /^#([\w\-\*]+)(\b|$)/,
    className:    /^\.([\w\-\*]+)(\b|$)/,
    pseudo:       /^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|\s|(?=:))/,
    attrPresence: /^\[([\w]+)\]/,
    attr:         /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\]]*?)\4|([^'"][^\]]*?)))?\]/
  },

  handlers: {
    // UTILITY FUNCTIONS
    // joins two collections
    concat: function(a, b) {
      for (var i = 0, node; node = b[i]; i++)
        a.push(node);
      return a;
    },

    // marks an array of nodes for counting
    mark: function(nodes) {
      for (var i = 0, node; node = nodes[i]; i++)
        node._counted = true;
      return nodes;
    },

    unmark: function(nodes) {
      for (var i = 0, node; node = nodes[i]; i++)
        node._counted = undefined;
      return nodes;
    },

    // mark each child node with its position (for nth calls)
    // "ofType" flag indicates whether we're indexing for nth-of-type
    // rather than nth-child
    index: function(parentNode, reverse, ofType) {
      parentNode._counted = true;
      if (reverse) {
        for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) {
          node = nodes[i];
          if (node.nodeType == 1 && (!ofType || node._counted)) node.nodeIndex = j++;
        }
      } else {
        for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++)
          if (node.nodeType == 1 && (!ofType || node._counted)) node.nodeIndex = j++;
      }
    },

    // filters out duplicates and extends all nodes
    unique: function(nodes) {
      if (nodes.length == 0) return nodes;
      var results = [], n;
      for (var i = 0, l = nodes.length; i < l; i++)
        if (!(n = nodes[i])._counted) {
          n._counted = true;
          results.push(Element.extend(n));
        }
      return Selector.handlers.unmark(results);
    },

    // COMBINATOR FUNCTIONS
    descendant: function(nodes) {
      var h = Selector.handlers;
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        h.concat(results, node.getElementsByTagName('*'));
      return results;
    },

    child: function(nodes) {
      var h = Selector.handlers;
      for (var i = 0, results = [], node; node = nodes[i]; i++) {
        for (var j = 0, children = [], child; child = node.childNodes[j]; j++)
          if (child.nodeType == 1 && child.tagName != '!') results.push(child);
      }
      return results;
    },

    adjacent: function(nodes) {
      for (var i = 0, results = [], node; node = nodes[i]; i++) {
        var next = this.nextElementSibling(node);
        if (next) results.push(next);
      }
      return results;
    },

    laterSibling: function(nodes) {
      var h = Selector.handlers;
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        h.concat(results, Element.nextSiblings(node));
      return results;
    },

    nextElementSibling: function(node) {
      while (node = node.nextSibling)
          if (node.nodeType == 1) return node;
      return null;
    },

    previousElementSibling: function(node) {
      while (node = node.previousSibling)
        if (node.nodeType == 1) return node;
      return null;
    },

    // TOKEN FUNCTIONS
    tagName: function(nodes, root, tagName, combinator) {
      tagName = tagName.toUpperCase();
      var results = [], h = Selector.handlers;
      if (nodes) {
        if (combinator) {
          // fastlane for ordinary descendant combinators
          if (combinator == "descendant") {
            for (var i = 0, node; node = nodes[i]; i++)
              h.concat(results, node.getElementsByTagName(tagName));
            return results;
          } else nodes = this[combinator](nodes);
          if (tagName == "*") return nodes;
        }
        for (var i = 0, node; node = nodes[i]; i++)
          if (node.tagName.toUpperCase() == tagName) results.push(node);
        return results;
      } else return root.getElementsByTagName(tagName);
    },

    id: function(nodes, root, id, combinator) {
      var targetNode = $(id), h = Selector.handlers;
      if (!nodes && root == document) return targetNode ? [targetNode] : [];
      if (nodes) {
        if (combinator) {
          if (combinator == 'child') {
            for (var i = 0, node; node = nodes[i]; i++)
              if (targetNode.parentNode == node) return [targetNode];
          } else if (combinator == 'descendant') {
            for (var i = 0, node; node = nodes[i]; i++)
              if (Element.descendantOf(targetNode, node)) return [targetNode];
          } else if (combinator == 'adjacent') {
            for (var i = 0, node; node = nodes[i]; i++)
              if (Selector.handlers.previousElementSibling(targetNode) == node)
                return [targetNode];
          } else nodes = h[combinator](nodes);
        }
        for (var i = 0, node; node = nodes[i]; i++)
          if (node == targetNode) return [targetNode];
        return [];
      }
      return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : [];
    },

    className: function(nodes, root, className, combinator) {
      if (nodes && combinator) nodes = this[combinator](nodes);
      return Selector.handlers.byClassName(nodes, root, className);
    },

    byClassName: function(nodes, root, className) {
      if (!nodes) nodes = Selector.handlers.descendant([root]);
      var needle = ' ' + className + ' ';
      for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) {
        nodeClassName = node.className;
        if (nodeClassName.length == 0) continue;
        if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle))
          results.push(node);
      }
      return results;
    },

    attrPresence: function(nodes, root, attr) {
      var results = [];
      for (var i = 0, node; node = nodes[i]; i++)
        if (Element.hasAttribute(node, attr)) results.push(node);
      return results;
    },

    attr: function(nodes, root, attr, value, operator) {
      if (!nodes) nodes = root.getElementsByTagName("*");
      var handler = Selector.operators[operator], results = [];
      for (var i = 0, node; node = nodes[i]; i++) {
        var nodeValue = Element.readAttribute(node, attr);
        if (nodeValue === null) continue;
        if (handler(nodeValue, value)) results.push(node);
      }
      return results;
    },

    pseudo: function(nodes, name, value, root, combinator) {
      if (nodes && combinator) nodes = this[combinator](nodes);
      if (!nodes) nodes = root.getElementsByTagName("*");
      return Selector.pseudos[name](nodes, value, root);
    }
  },

  pseudos: {
    'first-child': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++) {
        if (Selector.handlers.previousElementSibling(node)) continue;
          results.push(node);
      }
      return results;
    },
    'last-child': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++) {
        if (Selector.handlers.nextElementSibling(node)) continue;
          results.push(node);
      }
      return results;
    },
    'only-child': function(nodes, value, root) {
      var h = Selector.handlers;
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        if (!h.previousElementSibling(node) && !h.nextElementSibling(node))
          results.push(node);
      return results;
    },
    'nth-child':        function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, formula, root);
    },
    'nth-last-child':   function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, formula, root, true);
    },
    'nth-of-type':      function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, formula, root, false, true);
    },
    'nth-last-of-type': function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, formula, root, true, true);
    },
    'first-of-type':    function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, "1", root, false, true);
    },
    'last-of-type':     function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, "1", root, true, true);
    },
    'only-of-type':     function(nodes, formula, root) {
      var p = Selector.pseudos;
      return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root);
    },

    // handles the an+b logic
    getIndices: function(a, b, total) {
      if (a == 0) return b > 0 ? [b] : [];
      return $R(1, total).inject([], function(memo, i) {
        if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i);
        return memo;
      });
    },

    // handles nth(-last)-child, nth(-last)-of-type, and (first|last)-of-type
    nth: function(nodes, formula, root, reverse, ofType) {
      if (nodes.length == 0) return [];
      if (formula == 'even') formula = '2n+0';
      if (formula == 'odd')  formula = '2n+1';
      var h = Selector.handlers, results = [], indexed = [], m;
      h.mark(nodes);
      for (var i = 0, node; node = nodes[i]; i++) {
        if (!node.parentNode._counted) {
          h.index(node.parentNode, reverse, ofType);
          indexed.push(node.parentNode);
        }
      }
      if (formula.match(/^\d+$/)) { // just a number
        formula = Number(formula);
        for (var i = 0, node; node = nodes[i]; i++)
          if (node.nodeIndex == formula) results.push(node);
      } else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
        if (m[1] == "-") m[1] = -1;
        var a = m[1] ? Number(m[1]) : 1;
        var b = m[2] ? Number(m[2]) : 0;
        var indices = Selector.pseudos.getIndices(a, b, nodes.length);
        for (var i = 0, node, l = indices.length; node = nodes[i]; i++) {
          for (var j = 0; j < l; j++)
            if (node.nodeIndex == indices[j]) results.push(node);
        }
      }
      h.unmark(nodes);
      h.unmark(indexed);
      return results;
    },

    'empty': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++) {
        // IE treats comments as element nodes
        if (node.tagName == '!' || (node.firstChild && !node.innerHTML.match(/^\s*$/))) continue;
        results.push(node);
      }
      return results;
    },

    'not': function(nodes, selector, root) {
      var h = Selector.handlers, selectorType, m;
      var exclusions = new Selector(selector).findElements(root);
      h.mark(exclusions);
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        if (!node._counted) results.push(node);
      h.unmark(exclusions);
      return results;
    },

    'enabled': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        if (!node.disabled) results.push(node);
      return results;
    },

    'disabled': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        if (node.disabled) results.push(node);
      return results;
    },

    'checked': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        if (node.checked) results.push(node);
      return results;
    }
  },

  operators: {
    '=':  function(nv, v) { return nv == v; },
    '!=': function(nv, v) { return nv != v; },
    '^=': function(nv, v) { return nv.startsWith(v); },
    '$=': function(nv, v) { return nv.endsWith(v); },
    '*=': function(nv, v) { return nv.include(v); },
    '~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); },
    '|=': function(nv, v) { return ('-' + nv.toUpperCase() + '-').include('-' + v.toUpperCase() + '-'); }
  },

  matchElements: function(elements, expression) {
    var matches = new Selector(expression).findElements(), h = Selector.handlers;
    h.mark(matches);
    for (var i = 0, results = [], element; element = elements[i]; i++)
      if (element._counted) results.push(element);
    h.unmark(matches);
    return results;
  },

  findElement: function(elements, expression, index) {
    if (typeof expression == 'number') {
      index = expression; expression = false;
    }
    return Selector.matchElements(elements, expression || '*')[index || 0];
  },

  findChildElements: function(element, expressions) {
    var exprs = expressions.join(','), expressions = [];
    exprs.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) {
      expressions.push(m[1].strip());
    });
    var results = [], h = Selector.handlers;
    for (var i = 0, l = expressions.length, selector; i < l; i++) {
      selector = new Selector(expressions[i].strip());
      h.concat(results, selector.findElements(element));
    }
    return (l > 1) ? h.unique(results) : results;
  }
});

function $$() {
  return Selector.findChildElements(document, $A(arguments));
}
var Form = {
  reset: function(form) {
    $(form).reset();
    return form;
  },

  serializeElements: function(elements, getHash) {
    var data = elements.inject({}, function(result, element) {
      if (!element.disabled && element.name) {
        var key = element.name, value = $(element).getValue();
        if (value != null) {
             if (key in result) {
            if (result[key].constructor != Array) result[key] = [result[key]];
            result[key].push(value);
          }
          else result[key] = value;
        }
      }
      return result;
    });

    return getHash ? data : Hash.toQueryString(data);
  }
};

Form.Methods = {
  serialize: function(form, getHash) {
    return Form.serializeElements(Form.getElements(form), getHash);
  },

  getElements: function(form) {
    return $A($(form).getElementsByTagName('*')).inject([],
      function(elements, child) {
        if (Form.Element.Serializers[child.tagName.toLowerCase()])
          elements.push(Element.extend(child));
        return elements;
      }
    );
  },

  getInputs: function(form, typeName, name) {
    form = $(form);
    var inputs = form.getElementsByTagName('input');

    if (!typeName && !name) return $A(inputs).map(Element.extend);

    for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
      var input = inputs[i];
      if ((typeName && input.type != typeName) || (name && input.name != name))
        continue;
      matchingInputs.push(Element.extend(input));
    }

    return matchingInputs;
  },

  disable: function(form) {
    form = $(form);
    Form.getElements(form).invoke('disable');
    return form;
  },

  enable: function(form) {
    form = $(form);
    Form.getElements(form).invoke('enable');
    return form;
  },

  findFirstElement: function(form) {
    return $(form).getElements().find(function(element) {
      return element.type != 'hidden' && !element.disabled &&
        ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
    });
  },

  focusFirstElement: function(form) {
    form = $(form);
    form.findFirstElement().activate();
    return form;
  },

  request: function(form, options) {
    form = $(form), options = Object.clone(options || {});

    var params = options.parameters;
    options.parameters = form.serialize(true);

    if (params) {
      if (typeof params == 'string') params = params.toQueryParams();
      Object.extend(options.parameters, params);
    }

    if (form.hasAttribute('method') && !options.method)
      options.method = form.method;

    return new Ajax.Request(form.readAttribute('action'), options);
  }
}

/*--------------------------------------------------------------------------*/

Form.Element = {
  focus: function(element) {
    $(element).focus();
    return element;
  },

  select: function(element) {
    $(element).select();
    return element;
  }
}

Form.Element.Methods = {
  serialize: function(element) {
    element = $(element);
    if (!element.disabled && element.name) {
      var value = element.getValue();
      if (value != undefined) {
        var pair = {};
        pair[element.name] = value;
        return Hash.toQueryString(pair);
      }
    }
    return '';
  },

  getValue: function(element) {
    element = $(element);
    var method = element.tagName.toLowerCase();
    return Form.Element.Serializers[method](element);
  },

  clear: function(element) {
    $(element).value = '';
    return element;
  },

  present: function(element) {
    return $(element).value != '';
  },

  activate: function(element) {
    element = $(element);
    try {
      element.focus();
      if (element.select && (element.tagName.toLowerCase() != 'input' ||
        !['button', 'reset', 'submit'].include(element.type)))
        element.select();
    } catch (e) {}
    return element;
  },

  disable: function(element) {
    element = $(element);
    element.blur();
    element.disabled = true;
    return element;
  },

  enable: function(element) {
    element = $(element);
    element.disabled = false;
    return element;
  }
}

/*--------------------------------------------------------------------------*/

var Field = Form.Element;
var $F = Form.Element.Methods.getValue;

/*--------------------------------------------------------------------------*/

Form.Element.Serializers = {
  input: function(element) {
    switch (element.type.toLowerCase()) {
      case 'checkbox':
      case 'radio':
        return Form.Element.Serializers.inputSelector(element);
      default:
        return Form.Element.Serializers.textarea(element);
    }
  },

  inputSelector: function(element) {
    return element.checked ? element.value : null;
  },

  textarea: function(element) {
    return element.value;
  },

  select: function(element) {
    return this[element.type == 'select-one' ?
      'selectOne' : 'selectMany'](element);
  },

  selectOne: function(element) {
    var index = element.selectedIndex;
    return index >= 0 ? this.optionValue(element.options[index]) : null;
  },

  selectMany: function(element) {
    var values, length = element.length;
    if (!length) return null;

    for (var i = 0, values = []; i < length; i++) {
      var opt = element.options[i];
      if (opt.selected) values.push(this.optionValue(opt));
    }
    return values;
  },

  optionValue: function(opt) {
    // extend element because hasAttribute may not be native
    return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
  }
}

/*--------------------------------------------------------------------------*/

Abstract.TimedObserver = function() {}
Abstract.TimedObserver.prototype = {
  initialize: function(element, frequency, callback) {
    this.frequency = frequency;
    this.element   = $(element);
    this.callback  = callback;

    this.lastValue = this.getValue();
    this.registerCallback();
  },

  registerCallback: function() {
    setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  onTimerEvent: function() {
    var value = this.getValue();
    var changed = ('string' == typeof this.lastValue && 'string' == typeof value
      ? this.lastValue != value : String(this.lastValue) != String(value));
    if (changed) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  }
}

Form.Element.Observer = Class.create();
Form.Element.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.Observer = Class.create();
Form.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
  getValue: function() {
    return Form.serialize(this.element);
  }
});

/*--------------------------------------------------------------------------*/

Abstract.EventObserver = function() {}
Abstract.EventObserver.prototype = {
  initialize: function(element, callback) {
    this.element  = $(element);
    this.callback = callback;

    this.lastValue = this.getValue();
    if (this.element.tagName.toLowerCase() == 'form')
      this.registerFormCallbacks();
    else
      this.registerCallback(this.element);
  },

  onElementEvent: function() {
    var value = this.getValue();
    if (this.lastValue != value) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  },

  registerFormCallbacks: function() {
    Form.getElements(this.element).each(this.registerCallback.bind(this));
  },

  registerCallback: function(element) {
    if (element.type) {
      switch (element.type.toLowerCase()) {
        case 'checkbox':
        case 'radio':
          Event.observe(element, 'click', this.onElementEvent.bind(this));
          break;
        default:
          Event.observe(element, 'change', this.onElementEvent.bind(this));
          break;
      }
    }
  }
}

Form.Element.EventObserver = Class.create();
Form.Element.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.EventObserver = Class.create();
Form.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
  getValue: function() {
    return Form.serialize(this.element);
  }
});
if (!window.Event) {
  var Event = new Object();
}

Object.extend(Event, {
  KEY_BACKSPACE: 8,
  KEY_TAB:       9,
  KEY_RETURN:   13,
  KEY_ESC:      27,
  KEY_LEFT:     37,
  KEY_UP:       38,
  KEY_RIGHT:    39,
  KEY_DOWN:     40,
  KEY_DELETE:   46,
  KEY_HOME:     36,
  KEY_END:      35,
  KEY_PAGEUP:   33,
  KEY_PAGEDOWN: 34,

  element: function(event) {
    return $(event.target || event.srcElement);
  },

  isLeftClick: function(event) {
    return (((event.which) && (event.which == 1)) ||
            ((event.button) && (event.button == 1)));
  },

  pointerX: function(event) {
    return event.pageX || (event.clientX +
      (document.documentElement.scrollLeft || document.body.scrollLeft));
  },

  pointerY: function(event) {
    return event.pageY || (event.clientY +
      (document.documentElement.scrollTop || document.body.scrollTop));
  },

  stop: function(event) {
    if (event.preventDefault) {
      event.preventDefault();
      event.stopPropagation();
    } else {
      event.returnValue = false;
      event.cancelBubble = true;
    }
  },

  // find the first node with the given tagName, starting from the
  // node the event was triggered on; traverses the DOM upwards
  findElement: function(event, tagName) {
    var element = Event.element(event);
    while (element.parentNode && (!element.tagName ||
        (element.tagName.toUpperCase() != tagName.toUpperCase())))
      element = element.parentNode;
    return element;
  },

  observers: false,

  _observeAndCache: function(element, name, observer, useCapture) {
    if (!this.observers) this.observers = [];
    if (element.addEventListener) {
      this.observers.push([element, name, observer, useCapture]);
      element.addEventListener(name, observer, useCapture);
    } else if (element.attachEvent) {
      this.observers.push([element, name, observer, useCapture]);
      element.attachEvent('on' + name, observer);
    }
  },

  unloadCache: function() {
    if (!Event.observers) return;
    for (var i = 0, length = Event.observers.length; i < length; i++) {
      Event.stopObserving.apply(this, Event.observers[i]);
      Event.observers[i][0] = null;
    }
    Event.observers = false;
  },

  observe: function(element, name, observer, useCapture) {
    element = $(element);
    useCapture = useCapture || false;

    if (name == 'keypress' &&
      (Prototype.Browser.WebKit || element.attachEvent))
      name = 'keydown';

    Event._observeAndCache(element, name, observer, useCapture);
  },

  stopObserving: function(element, name, observer, useCapture) {
    element = $(element);
    useCapture = useCapture || false;

    if (name == 'keypress' &&
        (Prototype.Browser.WebKit || element.attachEvent))
      name = 'keydown';

    if (element.removeEventListener) {
      element.removeEventListener(name, observer, useCapture);
    } else if (element.detachEvent) {
      try {
        element.detachEvent('on' + name, observer);
      } catch (e) {}
    }
  }
});

/* prevent memory leaks in IE */
if (Prototype.Browser.IE)
  Event.observe(window, 'unload', Event.unloadCache, false);
var Position = {
  // set to true if needed, warning: firefox performance problems
  // NOT neeeded for page scrolling, only if draggable contained in
  // scrollable elements
  includeScrollOffsets: false,

  // must be called before calling withinIncludingScrolloffset, every time the
  // page is scrolled
  prepare: function() {
    this.deltaX =  window.pageXOffset
                || document.documentElement.scrollLeft
                || document.body.scrollLeft
                || 0;
    this.deltaY =  window.pageYOffset
                || document.documentElement.scrollTop
                || document.body.scrollTop
                || 0;
  },

  realOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.scrollTop  || 0;
      valueL += element.scrollLeft || 0;
      element = element.parentNode;
    } while (element);
    return [valueL, valueT];
  },

  cumulativeOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
    } while (element);
    return [valueL, valueT];
  },

  positionedOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
      if (element) {
        if(element.tagName=='BODY') break;
        var p = Element.getStyle(element, 'position');
        if (p == 'relative' || p == 'absolute') break;
      }
    } while (element);
    return [valueL, valueT];
  },

  offsetParent: function(element) {
    if (element.offsetParent) return element.offsetParent;
    if (element == document.body) return element;

    while ((element = element.parentNode) && element != document.body)
      if (Element.getStyle(element, 'position') != 'static')
        return element;

    return document.body;
  },

  // caches x/y coordinate pair to use with overlap
  within: function(element, x, y) {
    if (this.includeScrollOffsets)
      return this.withinIncludingScrolloffsets(element, x, y);
    this.xcomp = x;
    this.ycomp = y;
    this.offset = this.cumulativeOffset(element);

    return (y >= this.offset[1] &&
            y <  this.offset[1] + element.offsetHeight &&
            x >= this.offset[0] &&
            x <  this.offset[0] + element.offsetWidth);
  },

  withinIncludingScrolloffsets: function(element, x, y) {
    var offsetcache = this.realOffset(element);

    this.xcomp = x + offsetcache[0] - this.deltaX;
    this.ycomp = y + offsetcache[1] - this.deltaY;
    this.offset = this.cumulativeOffset(element);

    return (this.ycomp >= this.offset[1] &&
            this.ycomp <  this.offset[1] + element.offsetHeight &&
            this.xcomp >= this.offset[0] &&
            this.xcomp <  this.offset[0] + element.offsetWidth);
  },

  // within must be called directly before
  overlap: function(mode, element) {
    if (!mode) return 0;
    if (mode == 'vertical')
      return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
        element.offsetHeight;
    if (mode == 'horizontal')
      return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
        element.offsetWidth;
  },

  page: function(forElement) {
    var valueT = 0, valueL = 0;

    var element = forElement;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;

      // Safari fix
      if (element.offsetParent == document.body)
        if (Element.getStyle(element,'position')=='absolute') break;

    } while (element = element.offsetParent);

    element = forElement;
    do {
      if (!window.opera || element.tagName=='BODY') {
        valueT -= element.scrollTop  || 0;
        valueL -= element.scrollLeft || 0;
      }
    } while (element = element.parentNode);

    return [valueL, valueT];
  },

  clone: function(source, target) {
    var options = Object.extend({
      setLeft:    true,
      setTop:     true,
      setWidth:   true,
      setHeight:  true,
      offsetTop:  0,
      offsetLeft: 0
    }, arguments[2] || {})

    // find page position of source
    source = $(source);
    var p = Position.page(source);

    // find coordinate system to use
    target = $(target);
    var delta = [0, 0];
    var parent = null;
    // delta [0,0] will do fine with position: fixed elements,
    // position:absolute needs offsetParent deltas
    if (Element.getStyle(target,'position') == 'absolute') {
      parent = Position.offsetParent(target);
      delta = Position.page(parent);
    }

    // correct by body offsets (fixes Safari)
    if (parent == document.body) {
      delta[0] -= document.body.offsetLeft;
      delta[1] -= document.body.offsetTop;
    }

    // set position
    if(options.setLeft)   target.style.left  = (p[0] - delta[0] + options.offsetLeft) + 'px';
    if(options.setTop)    target.style.top   = (p[1] - delta[1] + options.offsetTop) + 'px';
    if(options.setWidth)  target.style.width = source.offsetWidth + 'px';
    if(options.setHeight) target.style.height = source.offsetHeight + 'px';
  },

  absolutize: function(element) {
    element = $(element);
    if (element.style.position == 'absolute') return;
    Position.prepare();

    var offsets = Position.positionedOffset(element);
    var top     = offsets[1];
    var left    = offsets[0];
    var width   = element.clientWidth;
    var height  = element.clientHeight;

    element._originalLeft   = left - parseFloat(element.style.left  || 0);
    element._originalTop    = top  - parseFloat(element.style.top || 0);
    element._originalWidth  = element.style.width;
    element._originalHeight = element.style.height;

    element.style.position = 'absolute';
    element.style.top    = top + 'px';
    element.style.left   = left + 'px';
    element.style.width  = width + 'px';
    element.style.height = height + 'px';
  },

  relativize: function(element) {
    element = $(element);
    if (element.style.position == 'relative') return;
    Position.prepare();

    element.style.position = 'relative';
    var top  = parseFloat(element.style.top  || 0) - (element._originalTop || 0);
    var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);

    element.style.top    = top + 'px';
    element.style.left   = left + 'px';
    element.style.height = element._originalHeight;
    element.style.width  = element._originalWidth;
  }
}

// Safari returns margins on body which is incorrect if the child is absolutely
// positioned.  For performance reasons, redefine Position.cumulativeOffset for
// KHTML/WebKit only.
if (Prototype.Browser.WebKit) {
  Position.cumulativeOffset = function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      if (element.offsetParent == document.body)
        if (Element.getStyle(element, 'position') == 'absolute') break;

      element = element.offsetParent;
    } while (element);

    return [valueL, valueT];
  }
}

Element.addMethods();

var Scriptaculous = {
  Version: '1.7.1_beta3',
  require: function(libraryName) {
    // inserting via DOM fails in Safari 2.0, so brute force approach
    document.write('<script type="text/javascript" src="'+libraryName+'"></script>');
  },
  REQUIRED_PROTOTYPE: '1.5.1',
  load: function() {
    function convertVersionString(versionString){
      var r = versionString.split('.');
      return parseInt(r[0])*100000 + parseInt(r[1])*1000 + parseInt(r[2]);
    }
 
    if((typeof Prototype=='undefined') || 
       (typeof Element == 'undefined') || 
       (typeof Element.Methods=='undefined') ||
       (convertVersionString(Prototype.Version) < 
        convertVersionString(Scriptaculous.REQUIRED_PROTOTYPE)))
       throw("script.aculo.us requires the Prototype JavaScript framework >= " +
        Scriptaculous.REQUIRED_PROTOTYPE);
    
    $A(document.getElementsByTagName("script")).findAll( function(s) {
      return (s.src && s.src.match(/scriptaculous\.js(\?.*)?$/))
    }).each( function(s) {
      var path = s.src.replace(/scriptaculous\.js(\?.*)?$/,'');
      var includes = s.src.match(/\?.*load=([a-z,]*)/);
      (includes ? includes[1] : 'builder,effects,dragdrop,controls,slider,sound').split(',').each(
       function(include) { Scriptaculous.require(path+include+'.js') });
    });
  }
}

Scriptaculous.load();

/*
ModalBox - The pop-up window thingie with AJAX, based on prototype and script.aculo.us.

Copyright Andrey Okonetchnikov (andrej.okonetschnikow@gmail.com), 2006-2007
All rights reserved.
 
VERSION 1.5.5
Last Modified: 09/06/2007
*/

if (!window.Modalbox)
    var Modalbox = new Object();

Modalbox.Methods = {
    overrideAlert: false, // Override standard browser alert message with ModalBox
    focusableElements: new Array,
    options: {
        title: "ModalBox Window", // Title of the ModalBox window
        overlayClose: true, // Close modal box by clicking on overlay
        width: 500, // Default width in px
        height: 90, // Default height in px
        overlayOpacity: .75, // Default overlay opacity
        overlayDuration: .25, // Default overlay fade in/out duration in seconds
        slideDownDuration: .5, // Default Modalbox appear slide down effect in seconds
        slideUpDuration: .15, // Default Modalbox hiding slide up effect in seconds
        resizeDuration: .2, // Default resize duration seconds
        inactiveFade: true, // Fades MB window on inactive state
        transitions: !-[1,] ? true : false, // Toggles transition effects. Transitions are enabled by default
        loadingString: "Please wait. Loading...", // Default loading string message
        closeString: "Close window", // Default title attribute for close window link
        params: {},
        method: 'get' // Default Ajax request method
    },
    _options: new Object,
    
    setOptions: function(options) {
        Object.extend(this.options, options || {});
    },
    
    _init: function(options) {
        // Setting up original options with default options
        Object.extend(this._options, this.options);
        this.setOptions(options);
        
        //Create the overlay
        this.MBoverlay = document.createElement('div');
        this.MBoverlay.id = 'MB_overlay';
        this.MBoverlay.style.opacity = '0';
        
        //Create the window
        this.MBloading = document.createElement('div');
        this.MBloading.id = 'MB_loading';
        this.MBloading.innerHTML = this.options.loadingString;
        
        this.MBcontent = document.createElement('div');
        this.MBcontent.id = 'MB_content';
        this.MBcontent.appendChild(this.MBloading);
        
        this.MBclose = document.createElement('a');
        this.MBclose.href = '#';
        this.MBclose.title = 'Close window';
        this.MBclose.id = 'MB_close';
        this.MBclose.innerHTML = '<span>×</span>';
        
        this.MBcaption = document.createElement('div');
        this.MBcaption.id = 'MB_caption';
        
        this.MBheader = document.createElement('div');
        this.MBheader.id = 'MB_header';
        this.MBheader.appendChild(this.MBcaption);
        this.MBheader.appendChild(this.MBclose);
        
        this.MBframe = document.createElement('div');
        this.MBframe.id = 'MB_frame';
        this.MBframe.appendChild(this.MBheader);
        this.MBframe.appendChild(this.MBcontent);
        
        this.MBwindow = document.createElement('div');
        this.MBwindow.id = 'MB_window';
        this.MBwindow.style.display = 'none';
        this.MBwindow.appendChild(this.MBframe);
        
        
        // Inserting into DOM
        document.body.insertBefore(this.MBwindow, document.body.childNodes[0]);
        document.body.insertBefore(this.MBoverlay, document.body.childNodes[0]);
        
        // Initial scrolling position of the window. To be used for remove scrolling effect during ModalBox appearing
        this.initScrollX = window.pageXOffset || document.body.scrollLeft || document.documentElement.scrollLeft;
        this.initScrollY = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
        
        //Adding event observers
        this.hide = this.hide.bindAsEventListener(this);
        this.close = this._hide.bindAsEventListener(this);
        this.kbdHandler = this.kbdHandler.bindAsEventListener(this);
        this._initObservers();

        this.initialized = true; // Mark as initialized
        this.active = true; // Mark as active
        this.currFocused = 0;
    },
    
    show: function(content, options) {
        if(!this.initialized) this._init(options); // Check for is already initialized
        
        this.content = content;
        this.setOptions(options);
        
        Element.update(this.MBcaption, this.options.title); // Updating title of the MB
        
        if(this.MBwindow.style.display == "none") { // First modal box appearing
            this._appear();
            this.event("onShow"); // Passing onShow callback
        }
        else { // If MB already on the screen, update it
            this._update();
            this.event("onUpdate"); // Passing onUpdate callback
        } 
    },
    
    hide: function(options) { // External hide method to use from external HTML and JS
        if(this.initialized) {
            if(options) Object.extend(this.options, options); // Passing callbacks
            if(this.options.transitions)
                Effect.SlideUp(this.MBwindow, { duration: this.options.slideUpDuration, afterFinish: this._deinit.bind(this) } );
            else {
                Element.hide(this.MBwindow);
                this._deinit();
            }
        } else throw("Modalbox isn't initialized");
    },
    
    alert: function(message){
        var html = '<div class="MB_alert"><p>' + message + '</p><input type="button" onclick="Modalbox.hide()" value="OK" /></div>';
        Modalbox.show(html, {title: 'Alert: ' + document.title, width: 300});
    },
        
    _hide: function(event) { // Internal hide method to use inside MB class
        if(event) Event.stop(event);
        this.hide();
    },
    
    _appear: function() { // First appearing of MB
        if (navigator.appVersion.match(/\bMSIE\b/))
            this._toggleSelects();
        this._setOverlay();
        this._setWidth();
        this._setPosition();
        if(this.options.transitions) {
            Element.setStyle(this.MBoverlay, {opacity: 0});
            new Effect.Fade(this.MBoverlay, {
                    from: 0, 
                    to: this.options.overlayOpacity, 
                    duration: this.options.overlayDuration, 
                    afterFinish: function() {
                        new Effect.SlideDown(this.MBwindow, {
                            duration: this.options.slideDownDuration, 
                            afterFinish: function(){ 
                                this._setPosition(); 
                                this.loadContent();
                            }.bind(this)
                        });
                    }.bind(this)
            });
        } else {
            Element.setStyle(this.MBoverlay, {opacity: this.options.overlayOpacity});
            Element.show(this.MBwindow);
            this._setPosition(); 
            this.loadContent();
        }
        this._setWidthAndPosition = this._setWidthAndPosition.bindAsEventListener(this);
        Event.observe(window, "resize", this._setWidthAndPosition);
    },
    
    resize: function(byWidth, byHeight, options) { // Change size of MB without loading content
        var wHeight = Element.getHeight(this.MBwindow);
        var wWidth = Element.getWidth(this.MBwindow);
        var hHeight = Element.getHeight(this.MBheader);
        var cHeight = Element.getHeight(this.MBcontent);
        var newHeight = ((wHeight - hHeight + byHeight) < cHeight) ? (cHeight + hHeight - wHeight) : byHeight;
        this.setOptions(options); // Passing callbacks
        if(this.options.transitions) {
            new Effect.ScaleBy(this.MBwindow, byWidth, newHeight, {
                    duration: this.options.resizeDuration, 
                      afterFinish: function() { 
                        this.event("_afterResize"); // Passing internal callback
                        this.event("afterResize"); // Passing callback
                    }.bind(this)
                });
        } else {
            this.MBwindow.setStyle({width: wWidth + byWidth + "px", height: wHeight + newHeight + "px"});
            setTimeout(function() {
                this.event("_afterResize"); // Passing internal callback
                this.event("afterResize"); // Passing callback
            }.bind(this), 1);
            
        }
        
    },
    
    _update: function() { // Updating MB in case of wizards
        Element.update(this.MBcontent, "");
        this.MBcontent.appendChild(this.MBloading);
        Element.update(this.MBloading, this.options.loadingString);
        this.currentDims = [this.MBwindow.offsetWidth, this.MBwindow.offsetHeight];
        Modalbox.resize((this.options.width - this.currentDims[0]), (this.options.height - this.currentDims[1]), {_afterResize: this._loadAfterResize.bind(this) });
    },
    
    loadContent: function () {
        if(this.event("beforeLoad") != false) { // If callback passed false, skip loading of the content
            if(typeof this.content == 'string') {
                
                var htmlRegExp = new RegExp(/<\/?[^>]+>/gi);
                if(htmlRegExp.test(this.content)) { // Plain HTML given as a parameter
                    this._insertContent(this.content);
                    this._putContent();
                } else 
                    new Ajax.Request( this.content, { method: this.options.method.toLowerCase(), parameters: this.options.params, 
                        onComplete: function(transport) {
                            var response = new String(transport.responseText);
                            this._insertContent(transport.responseText.stripScripts());
                            response.extractScripts().map(function(script) { 
                                return eval(script.replace("<!--", "").replace("// -->", ""));
                            }.bind(window));
                            this._putContent();
                        }.bind(this)
                    });
                    
            } else if (typeof this.content == 'object') {// HTML Object is given
                this._insertContent(this.content);
                this._putContent();
            } else {
                Modalbox.hide();
                throw('Please specify correct URL or HTML element (plain HTML or object)');
            }
        }
    },
    
    _insertContent: function(content){
        Element.extend(this.MBcontent);
        this.MBcontent.update("");
       
        if(typeof content == 'string')
        {
            this.MBcontent.hide().update(content);
             this.MBcontent.down().show();
        }
        else if (typeof this.content == 'object') { // HTML Object is given
            var _htmlObj = content.cloneNode(true); // If node already a part of DOM we'll clone it
            // If clonable element has ID attribute defined, modifying it to prevent duplicates
            if(this.content.id) this.content.id = "MB_" + this.content.id;
            /* Add prefix for IDs on all elements inside the DOM node */
            this.content.getElementsBySelector('*[id]').each(function(el){ el.id = "MB_" + el.id });
            this.MBcontent.hide().appendChild(_htmlObj);
            this.MBcontent.down().show(); // Toggle visibility for hidden nodes
        }
    },
    
    _putContent: function(){
        
        init_facebook();
        this.MBframe.setStyle({height: '300px'});
        this.MBcontent.show();
        // Prepare and resize modal box for content
        if(this.options.height == this._options.height)
            Modalbox.resize(0, this.MBcontent.getHeight() - Element.getHeight(this.MBwindow) + Element.getHeight(this.MBheader), {
                afterResize: function(){
                    this.MBcontent.show();
                    this.focusableElements = this._findFocusableElements();
                    this._setFocus(); // Setting focus on first 'focusable' element in content (input, select, textarea, link or button)
                    this.event("afterLoad"); // Passing callback
                }.bind(this)
            });
        else { // Height is defined. Creating a scrollable window
            this._setWidth();
            this.MBcontent.setStyle({overflow: 'auto', height: Element.getHeight(this.MBwindow) - Element.getHeight(this.MBheader) - 13 + 'px'});
            this.MBcontent.show();
            this.focusableElements = this._findFocusableElements();
            this._setFocus(); // Setting focus on first 'focusable' element in content (input, select, textarea, link or button)
            this.event("afterLoad"); // Passing callback
        }
       
    },
    
    activate: function(options){
        this.setOptions(options);
        this.active = true;
        Event.observe(this.MBclose, "click", this.close);
        if(this.options.overlayClose) Event.observe(this.MBoverlay, "click", this.hide);
        Element.show(this.MBclose);
        if(this.options.transitions && this.options.inactiveFade) new Effect.Appear(this.MBwindow, {duration: this.options.slideUpDuration});
    },
    
    deactivate: function(options) {
        this.setOptions(options);
        this.active = false;
        Event.stopObserving(this.MBclose, "click", this.close);
        if(this.options.overlayClose) Event.stopObserving(this.MBoverlay, "click", this.hide);
        Element.hide(this.MBclose);
        if(this.options.transitions && this.options.inactiveFade) new Effect.Fade(this.MBwindow, {duration: this.options.slideUpDuration, to: .75});
    },
    
    _initObservers: function(){
        Event.observe(this.MBclose, "click", this.close);
        if(this.options.overlayClose) Event.observe(this.MBoverlay, "click", this.hide);
        Event.observe(document, "keypress", Modalbox.kbdHandler );
    },
    
    _removeObservers: function(){
        Event.stopObserving(this.MBclose, "click", this.close);
        if(this.options.overlayClose) Event.stopObserving(this.MBoverlay, "click", this.hide);
        Event.stopObserving(document, "keypress", Modalbox.kbdHandler );
    },
    
    _loadAfterResize: function() {
        this._setWidth();
        this._setPosition();
        this.loadContent();
    },
    
    _setFocus: function() { // Setting focus to be looped inside current MB
    return true;
        if(this.focusableElements.length > 0) {
            var i = 0;
            var firstEl = this.focusableElements.find(function findFirst(el){
                i++;
                return el.tabIndex == 1;
            }) || this.focusableElements.first();
            this.currFocused = (i == this.focusableElements.length - 1) ? (i-1) : 0;
            firstEl.focus(); // Focus on first focusable element except close button
        } else
            $("MB_close").focus(); // If no focusable elements exist focus on close button
    },
    
    _findFocusableElements: function(){ // Collect form elements or links from MB content
        var els = this.MBcontent.getElementsBySelector('input:not([type~=hidden]), select, textarea, button, a[href]');
        els.invoke('addClassName', 'MB_focusable');
        return this.MBcontent.getElementsByClassName('MB_focusable');
    },
    
    kbdHandler: function(e) {
        var node = Event.element(e);
        switch(e.keyCode) {
            case Event.KEY_TAB:
                Event.stop(e);
                if(!e.shiftKey) { //Focusing in direct order
                    if(this.currFocused == this.focusableElements.length - 1) {
                        this.focusableElements.first().focus();
                        this.currFocused = 0;
                    } else {
                        this.currFocused++;
                        this.focusableElements[this.currFocused].focus();
                    }
                } else { // Shift key is pressed. Focusing in reverse order
                    if(this.currFocused == 0) {
                        this.focusableElements.last().focus();
                        this.currFocused = this.focusableElements.length - 1;
                    } else {
                        this.currFocused--;
                        this.focusableElements[this.currFocused].focus();
                    }
                }
                break;            
            case Event.KEY_ESC:
                if(this.active) this._hide(e);
                break;
            case 32:
                this._preventScroll(e);
                break;
            case 0: // For Gecko browsers compatibility
                if(e.which == 32) this._preventScroll(e);
                break;
            case Event.KEY_UP:
            case Event.KEY_DOWN:
            case Event.KEY_PAGEDOWN:
            case Event.KEY_PAGEUP:
            case Event.KEY_HOME:
            case Event.KEY_END:
                // Safari operates in slightly different way. This realization is still buggy in Safari.
                if(/Safari|KHTML/.test(navigator.userAgent) && !["textarea", "select"].include(node.tagName.toLowerCase()))
                    Event.stop(e);
                else if( (node.tagName.toLowerCase() == "input" && ["submit", "button"].include(node.type)) || (node.tagName.toLowerCase() == "a") )
                    Event.stop(e);
                break;
        }
    },
    
    _preventScroll: function(event) { // Disabling scrolling by "space" key
        if(!["input", "textarea", "select", "button"].include(Event.element(event).tagName.toLowerCase())) 
            Event.stop(event);
    },
    
    _deinit: function()
    {    
        this._removeObservers();
        Event.stopObserving(window, "resize", this._setWidthAndPosition );
        if(this.options.transitions) {
            Effect.toggle(this.MBoverlay, 'appear', {duration: this.options.overlayDuration, afterFinish: this._removeElements.bind(this) });
        } else {
            this.MBoverlay.hide();
            this._removeElements();
        }
        Element.setStyle(this.MBcontent, {overflow: '', height: ''});
    },
    
    _removeElements: function () {
        if (navigator.appVersion.match(/\bMSIE\b/)) {
            this._prepareIE("", ""); // If set to auto MSIE will show horizontal scrolling
            window.scrollTo(this.initScrollX, this.initScrollY);
        }
        Element.remove(this.MBoverlay);
        Element.remove(this.MBwindow);
        
        /* Replacing prefixes 'MB_' in IDs for the original content */
        if(typeof this.content == 'object' && this.content.id && this.content.id.match(/MB_/)) {
            this.content.getElementsBySelector('*[id]').each(function(el){ el.id = el.id.replace(/MB_/, ""); });
            this.content.id = this.content.id.replace(/MB_/, "");
        }
        /* Initialized will be set to false */
        this.initialized = false;
        
        if (navigator.appVersion.match(/\bMSIE\b/))
            this._toggleSelects(); // Toggle back 'select' elements in IE
        this.event("afterHide"); // Passing afterHide callback
        this.setOptions(this._options); //Settings options object into intial state
    },
    
    _setOverlay: function () {
        if (navigator.appVersion.match(/\bMSIE\b/)) {
            this._prepareIE("100%", "hidden");
            if (!navigator.appVersion.match(/\b7.0\b/)) window.scrollTo(0,0); // Disable scrolling on top for IE7
        }
    },
    
    _setWidth: function () { //Set size
        Element.setStyle(this.MBwindow, {width: this.options.width + "px", height: this.options.height + "px"});
    },
    
    _setPosition: function () {
        Element.setStyle(this.MBwindow, {left: Math.round((Element.getWidth(document.body) - Element.getWidth(this.MBwindow)) / 2 ) + "px"});
    },
    
    _setWidthAndPosition: function () {
        Element.setStyle(this.MBwindow, {width: this.options.width + "px"});
        this._setPosition();
    },
    
    _getScrollTop: function () { //From: http://www.quirksmode.org/js/doctypes.html
        var theTop;
        if (document.documentElement && document.documentElement.scrollTop)
            theTop = document.documentElement.scrollTop;
        else if (document.body)
            theTop = document.body.scrollTop;
        return theTop;
    },
    // For IE browsers -- IE requires height to 100% and overflow hidden (taken from lightbox)
    _prepareIE: function(height, overflow){
        var body = document.getElementsByTagName('body')[0];
        body.style.height = height;
        body.style.overflow = overflow;
  
        var html = document.getElementsByTagName('html')[0];
        html.style.height = height;
        html.style.overflow = overflow; 
    },
    // For IE browsers -- hiding all SELECT elements
    _toggleSelects: function() {
        var selects = $$("select");
        if(this.initialized) {
            selects.invoke('setStyle', {'visibility': 'hidden'});
        } else {
            selects.invoke('setStyle', {'visibility': ''});
        }
            
    },
    event: function(eventName) {
        if(this.options[eventName]) {
            var returnValue = this.options[eventName](); // Executing callback
            this.options[eventName] = null; // Removing callback after execution
            if(returnValue != undefined) 
                return returnValue;
            else 
                return true;
        }
        return true;
    }
}

/*!
// iPhone-style Checkboxes jQuery plugin
// Copyright Thomas Reynolds, licensed GPL & MIT
*/
;(function($, iphoneStyle) {

// Constructor
$[iphoneStyle] = function(elem, options) {
  this.$elem = $(elem);
  
  // Import options into instance variables
  var obj = this;
  $.each(options, function(key, value) {
    obj[key] = value;
  });
  
  // Initialize the control
  this.wrapCheckboxWithDivs();
  this.attachEvents();
  this.disableTextSelection();
  
  if (this.resizeHandle)    { this.optionallyResize('handle'); }
  if (this.resizeContainer) { this.optionallyResize('container'); }
  
  this.initialPosition();
};

$.extend($[iphoneStyle].prototype, {
  // Wrap the existing input[type=checkbox] with divs for styling and grab DOM references to the created nodes
  wrapCheckboxWithDivs: function() {
    this.$elem.wrap('<div class="' + this.containerClass + '" />');
    this.container = this.$elem.parent();
    
    this.offLabel  = $('<label class="'+ this.labelOffClass +'">' +
                         '<span>'+ this.uncheckedLabel +'</span>' +
                       '</label>').appendTo(this.container);
    this.offSpan   = this.offLabel.children('span');
    
    this.onLabel   = $('<label class="'+ this.labelOnClass +'">' +
                         '<span>'+ this.checkedLabel +'</span>' +
                       '</label>').appendTo(this.container);
    this.onSpan    = this.onLabel.children('span');
    
    this.handle    = $('<div class="' + this.handleClass + '">' +
                         '<div class="' + this.handleRightClass + '">' +
                           '<div class="' + this.handleCenterClass + '" />' +
                         '</div>' +
                       '</div>').appendTo(this.container);
  },
  
  // Disable IE text selection, other browsers are handled in CSS
  disableTextSelection: function() {
    if (!$.browser.msie) { return; }

    // Elements containing text should be unselectable
    $.each([this.handle, this.offLabel, this.onLabel, this.container], function(el) {
      $(el).attr("unselectable", "on");
    });
  },
  
  // Automatically resize the handle or container
  optionallyResize: function(mode) {
    var onLabelWidth  = this.onLabel.width(),
        offLabelWidth = this.offLabel.width();
        
    if (mode == 'container') {
      var newWidth = (onLabelWidth > offLabelWidth) ? onLabelWidth : offLabelWidth;
      newWidth += this.handle.width() + 15; 
    } else { 
      var newWidth = (onLabelWidth < offLabelWidth) ? onLabelWidth : offLabelWidth;
    }
    if(newWidth > 40 && newWidth < 80) newWidth = 89;
    this[mode].css({ width: newWidth });
  },
  
  attachEvents: function() {
    var obj = this;
    
    // A mousedown anywhere in the control will start tracking for dragging
    this.container
      .bind('mousedown touchstart', function(event) {          
        event.preventDefault();
        
        if (obj.$elem.is(':disabled')) { return; }
          
        var x = event.pageX || event.originalEvent.changedTouches[0].pageX;
        $[iphoneStyle].currentlyClicking = obj.handle;
        $[iphoneStyle].dragStartPosition = x;
        $[iphoneStyle].handleLeftOffset  = parseInt(obj.handle.css('left'), 10) || 0;
      })
    
      // Utilize event bubbling to handle drag on any element beneath the container
      .bind('iPhoneDrag', function(event, x) {
        event.preventDefault();
        
        if (obj.$elem.is(':disabled')) { return; }
        
        var p = (x + $[iphoneStyle].handleLeftOffset - $[iphoneStyle].dragStartPosition) / obj.rightSide;
        if (p < 0) { p = 0; }
        if (p > 1) { p = 1; }
        obj.handle.css({ left: p * obj.rightSide });
        obj.onLabel.css({ width: p * obj.rightSide + 4 });
        obj.offSpan.css({ marginRight: -p * obj.rightSide });
        obj.onSpan.css({ marginLeft: -(1 - p) * obj.rightSide });
      })
    
        // Utilize event bubbling to handle drag end on any element beneath the container
      .bind('iPhoneDragEnd', function(event, x) {
        if (obj.$elem.is(':disabled')) { return; }
        
        if ($[iphoneStyle].dragging) {
          var p = (x - $[iphoneStyle].dragStartPosition) / obj.rightSide;
          obj.$elem.attr('checked', (p >= 0.5));
        } else {
          obj.$elem.attr('checked', !obj.$elem.attr('checked'));
        }

        $[iphoneStyle].currentlyClicking = null;
        $[iphoneStyle].dragging = null;
        obj.$elem.change();
      });
  
    // Animate when we get a change event
    this.$elem.change(function() {

      if(document.getElementById('place_bid_title'))  
      {
        document.getElementById('place_bid_title').innerHTML = document.getElementById('on_off').checked ? 'Enter budget:' : 'Place bid:';
        document.getElementById('place_bid_title[TEMP]').innerHTML = document.getElementById('on_off').checked ? 'Enter budget:' : 'Place bid:';
      }
      jQuery.ajax({
          type: "GET",
          url: _BASE_URL+"ajax_autobid.php",
          data: 'id='+jQuery('#product_id').val()+'&status='+document.getElementById('on_off').checked,
          success: function(msg){
         }
      });
      var text = jQuery('#place_bid_confirm').html();
      text = str_replace('checked="checked"','',text);
      if(document.getElementById('on_off').checked)
          text = str_replace('id="on_off[TEMP]"','id="on_off[TEMP]" checked="checked"',text);
      jQuery('#place_bid_confirm').html(text);
            
      if (obj.$elem.is(':disabled')) {
        obj.container.addClass(obj.disabledClass);
        return false;
      } else {
        obj.container.removeClass(obj.disabledClass);
      }
      
      var new_left = obj.$elem.attr('checked') ? obj.rightSide : 0;

      obj.handle.animate({         left: new_left },                 obj.duration);
      obj.onLabel.animate({       width: new_left + 4 },             obj.duration);
      obj.offSpan.animate({ marginRight: -new_left },                obj.duration);
      obj.onSpan.animate({   marginLeft: new_left - obj.rightSide }, obj.duration);
    });
  },
  
  // Setup the control's inital position
  initialPosition: function() {
    this.offLabel.css({ width: this.container.width() - 5 });

    var offset = ($.browser.msie && $.browser.version < 7) ? 3 : 6;
    this.rightSide = this.container.width() - this.handle.width() - offset;

    if (this.$elem.is(':checked')) {
      this.handle.css({ left: this.rightSide });
      this.onLabel.css({ width: this.rightSide + 4 });
      this.offSpan.css({ marginRight: -this.rightSide });
    } else {
      this.onLabel.css({ width: 0 });
      this.onSpan.css({ marginLeft: -this.rightSide });
    }
    
    if (this.$elem.is(':disabled')) {
      this.container.addClass(this.disabledClass);
    }
  }
});

// jQuery-specific code
$.fn[iphoneStyle] = function(options) {
  var checkboxes = this.filter(':checkbox');
  
  // Fail early if we don't have any checkboxes passed in
  if (!checkboxes.length) { return this; }
  
  // Merge options passed in with global defaults
  var opt = $.extend({}, $[iphoneStyle].defaults, options);
  
  checkboxes.each(function() {
    $(this).data(iphoneStyle, new $[iphoneStyle](this, opt));
  });

  if (!$[iphoneStyle].initComplete) {
    // As the mouse moves on the page, animate if we are in a drag state
    $(document)
      .bind('mousemove touchmove', function(event) {
        if (!$[iphoneStyle].currentlyClicking) { return; }
        event.preventDefault();
        
        var x = event.pageX || event.originalEvent.changedTouches[0].pageX;
        if (!$[iphoneStyle].dragging &&
            (Math.abs($[iphoneStyle].dragStartPosition - x) > opt.dragThreshold)) { 
          $[iphoneStyle].dragging = true; 
        }
    
        $(event.target).trigger('iPhoneDrag', [x]);
      })

      // When the mouse comes up, leave drag state
      .bind('mouseup touchend', function(event) {        
        if (!$[iphoneStyle].currentlyClicking) { return; }
        event.preventDefault();
    
        var x = event.pageX || event.originalEvent.changedTouches[0].pageX;
        $($[iphoneStyle].currentlyClicking).trigger('iPhoneDragEnd', [x]);
      });
      
    $[iphoneStyle].initComplete = true;
  }
  
  return this;
}; // End of $.fn[iphoneStyle]

$[iphoneStyle].defaults = {
  duration:          200,                       // Time spent during slide animation
  checkedLabel:      'ON',                      // Text content of "on" state
  uncheckedLabel:    'OFF',                     // Text content of "off" state
  resizeHandle:      true,                      // Automatically resize the handle to cover either label
  resizeContainer:   true,                      // Automatically resize the widget to contain the labels
  disabledClass:     'iPhoneCheckDisabled',
  containerClass:    'iPhoneCheckContainer',
  labelOnClass:      'iPhoneCheckLabelOn',
  labelOffClass:     'iPhoneCheckLabelOff',
  handleClass:       'iPhoneCheckHandle',
  handleCenterClass: 'iPhoneCheckHandleCenter',
  handleRightClass:  'iPhoneCheckHandleRight',
  dragThreshold:     5                          // Pixels that must be dragged for a click to be ignored
};

})(jQuery, 'iphoneStyle');

function autobid_popup_show(id)
{
    var info = jQuery('.popup'+id);
    if (eval('hideDelayTimer'+id)) clearTimeout(eval('hideDelayTimer'+id));
    if (eval('beingShown'+id) || eval('shown'+id)) {
        // don't trigger the animation again
        return;
    } else {
        // reset position of info box
        eval('beingShown'+id+' = true;');

        var left = -53;
        if(document.getElementById('link_cont0'))
            var top = -60;
        else if(id == '') 
            var top = -120; 
        else if(id == '1') 
        {
            var top = -80; 
            left = -84;
        }
        else if(id == '3' && document.getElementById('buzz_header')) 
        {
            var top = -70; 
            left = -120;
        }
        else if(id == '4') 
        {
            var top = -70; 
            left = -120;
        }
        else 
            var top = -60;
            
        
            
        if(document.getElementById('cont0')) 
        {
            top = top - jQuery('#dpop'+id).height() + 80 ;
            left += 40;
        }
        info.css({
            top: top,
            left: left,
            display: 'block'
        }).animate({
            top: '-=' + distance + 'px',
            opacity: 1
        }, time, 'swing', function() {
            eval('beingShown'+id+' = false;');
            eval('shown'+id+' = true;');
        });
    }

    return false;
}

function autobid_popup_hide(id)
{
    var info = jQuery('.popup'+id);
    if (eval('hideDelayTimer'+id)) clearTimeout(eval('hideDelayTimer'+id));
    eval("hideDelayTimer"+id+" = setTimeout(function () {hideDelayTimer"+id+" = null;info.animate({top: '-=' + distance + 'px',opacity: 0}, time, 'swing', function () { shown"+id+" = false;info.css('display', 'none');});}, hideDelay);");

    return false;
}

var distance = 10;
var time = 250;
var hideDelay = 500;
var hideDelayTimer = null;
var hideDelayTimer1 = null;
var hideDelayTimer2 = null;
var hideDelayTimer3 = null;
var hideDelayTimer4 = null;
var hideDelayTimer5 = null;
var hideDelayTimer6 = null;
var beingShown = false;
var beingShown1 = false;
var beingShown2 = false;
var beingShown3 = false;
var beingShown4 = false;
var beingShown5 = false;
var beingShown6 = false;
var shown = false;
var shown1 = false;
var shown2 = false;
var shown3 = false;
var shown4 = false;
var shown5 = false;
var shown6 = false;
function bubbleInfoInit(id)
{
    if(id==undefined) var id = '';
    jQuery('.bubbleInfo'+id).each(function () {
        distance = 10;
        time = 250;
        hideDelay = 500;
        hideDelayTimer = null;
        beingShown = false;
        shown = false;
        jQuery('.popup', this).css('opacity', 0);
        jQuery(this).find('div').mouseover(function () {return autobid_popup_show(id);}).mouseout(function () {return autobid_popup_hide(id);});
    });
};


Object.extend(Modalbox, Modalbox.Methods);

if(Modalbox.overrideAlert) window.alert = Modalbox.alert;
/*
Effect.ScaleBy = Class.create();
Object.extend(Object.extend(Effect.ScaleBy.prototype, Effect.Base.prototype), {
  initialize: function(element, byWidth, byHeight, options) {
    this.element = $(element)
    var options = Object.extend({
      scaleFromTop: true,
      scaleMode: 'box',        // 'box' or 'contents' or {} with provided values
      scaleByWidth: byWidth,
      scaleByHeight: byHeight
    }, arguments[3] || {});
    this.start(options);
  },
  setup: function() {
    this.elementPositioning = this.element.getStyle('position');
      
    this.originalTop  = this.element.offsetTop;
    this.originalLeft = this.element.offsetLeft;
    
    this.dims = null;
    if(this.options.scaleMode=='box')
      this.dims = [this.element.offsetHeight, this.element.offsetWidth];
     if(/^content/.test(this.options.scaleMode))
      this.dims = [this.element.scrollHeight, this.element.scrollWidth];
    if(!this.dims)
      this.dims = [this.options.scaleMode.originalHeight,
                   this.options.scaleMode.originalWidth];
      
    this.deltaY = this.options.scaleByHeight;
    this.deltaX = this.options.scaleByWidth;
  },
  update: function(position) {
    var currentHeight = this.dims[0] + (this.deltaY * position);
    var currentWidth = this.dims[1] + (this.deltaX * position);
    
    currentHeight = (currentHeight > 0) ? currentHeight : 0;
    currentWidth = (currentWidth > 0) ? currentWidth : 0;
    
    this.setDimensions(currentHeight, currentWidth);
  },

  setDimensions: function(height, width) {
    var d = {};
    d.width = width + 'px';
    d.height = height + 'px';
    
    var topd  = Math.round((height - this.dims[0])/2);
    var leftd = Math.round((width  - this.dims[1])/2);
    if(this.elementPositioning == 'absolute' || this.elementPositioning == 'fixed') {
        if(!this.options.scaleFromTop) d.top = this.originalTop-topd + 'px';
        d.left = this.originalLeft-leftd + 'px';
    } else {
        if(!this.options.scaleFromTop) d.top = -topd + 'px';
        d.left = -leftd + 'px';
    }
    this.element.setStyle(d);
  }
});
*/
function highlight_show(obj,notclear)
{
    if(obj.defaultValue==obj.value && notclear == undefined)
        obj.value = '';
    jQuery(obj).addClass('error');
}

function highlight_hide(obj,notclear)
{
    if(''==obj.value && notclear == undefined)
        obj.value = obj.defaultValue;
    jQuery(obj).removeClass('error');
}

function init_facebook()
{    
    FB_RequireFeatures(["XFBML"], function() {
          FB.init(FACEBOOK_API_KEY,'/xd_receiver.html', {});      
    });    
}

function expand_buzz(obj)
{
 if(obj.innerHTML == '▼ Expand')
 {
     obj.innerHTML = '▲ Collapse';
     jQuery(obj).parents('.net_comment_message').find('li').each(function(id, li){
            jQuery(li).show();
     });
 }
 else
 {
     obj.innerHTML = '▼ Expand';
     jQuery(obj).parents('.net_comment_message').find('li').each(function(id, li){
         if(jQuery(li).hasClass('li0') || jQuery(li).hasClass('li1') || jQuery(li).hasClass('li2'))
            jQuery(li).show();
         else
            jQuery(li).hide();
     });
 }
}
     
function followme(link, id)
{
    jQuery.ajax({
      type:"GET",
      url:_BASE_URL+"ajax_follow.php",
      data: 'id='+id,
      success:function(msg){ 
        if(msg > 0)
        {
            jQuery(link).html('Following'); 
            jQuery('#follow_counter').html(jQuery('#follow_counter').html()/1 + 1); 
        }
        else
        {
            jQuery(link).html('Followers');  
            jQuery('#follow_counter').html(jQuery('#follow_counter').html()/1 - 1); 
            if(jQuery('#follow_counter').html()<0) jQuery('#follow_counter').html('0');
        }           
      }
    });
}

function OnRequestPermission(){

    setTimeout('check_facebook_perms();', 1000);
    var myPermissions = "email,user_birthday"; // permissions your app needs
    FB.Connect.showPermissionDialog(myPermissions , function(perms) {
      
    });
}
function check_facebook_perms()
{
    jQuery.ajax({
      type:"GET",
      url:_BASE_URL+"ajax_check_facebook_perms.php",
      data: '',
      success:function(msg){ 
       window.location.href='/?fb';
          if(msg=='') 
            setTimeout('check_facebook_perms();', 1000);
          else
            window.location.href='/?fb';
      }
    });
    
}

var map = null;
var geocoder = null;
var setpoint_flag = 0;
var new_address = '';
var new_coord = '';

function select_location()
{
    setpoint_flag = 1;
    jQuery('#not_you').html('<span style="font-size:11px;">Set point and</span> <a href="" style="font-size:11px;" onclick="save_location(); return false;">save</a>');
}

function save_location()
{
    setpoint_flag = 0;
    jQuery('#not_you').html('<a href="" style="font-size:12px;" onclick="select_location(); return false;">Not you?</a>');
    jQuery.ajax({
      type:"GET",
      url:_BASE_URL+"ajax_save_address.php",
      data: 'new_address='+new_address+'&new_coord='+new_coord,
      success:function(msg){             
      }
    });
}

function initialize() {
  if (GBrowserIsCompatible()) {
    G_PHYSICAL_MAP.getMaximumResolution = function () { return 9 };
    G_NORMAL_MAP.getMaximumResolution = function () { return 9 };
    G_SATELLITE_MAP.getMaximumResolution = function () { return 9 };
    G_HYBRID_MAP.getMaximumResolution = function () { return 9 };

    map = new GMap2(document.getElementById("map_canvas"));
    map.setCenter(new GLatLng(37.4419, -122.1419), 1);
    map.enableScrollWheelZoom(); 
    geocoder = new GClientGeocoder();
    GEvent.addListener(map, "click", getAddress);
  }
}

function getAddress(overlay, latlng) {
  if (latlng != null && setpoint_flag>0) {
    address = latlng;
    geocoder.getLocations(latlng, set_point);
  }
}

function set_point(response)
{
    map.clearOverlays();
    if (!response || response.Status.code != 200) {
        //alert("Status Code:" + response.Status.code);
    } else {
        place = response.Placemark[0];
        point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
        marker = new GMarker(point);
        map.addOverlay(marker);
        new_address = place.address;
        new_coord = place.Point.coordinates[1] + "," + place.Point.coordinates[0];
        marker.openInfoWindowHtml(place.address);
    }

}

function showAddress(coord, address) {
  if (geocoder) {
    geocoder.getLatLng(
      coord,
      function(point) {
        if (!point) {
          //alert(address + " not found");
        } else {
          map.setCenter(point, 13);
          var marker = new GMarker(point);
          lastMarker = marker;
          map.addOverlay(marker);
          marker.openInfoWindowHtml(address);
        }
      }
    );
  }
}

jQuery.autocomplete = function(input, options) {
    // Create a link to self
    var me = this;

    // Create jQuery object for input element
    var $input = $(input).attr("autocomplete", "off");

    // Apply inputClass if necessary
    if (options.inputClass) {
        $input.addClass(options.inputClass);
    }

    // Create results
    var results = document.createElement("div");

    // Create jQuery object for results
    // var $results = $(results);
    var $results = $(results).hide().addClass(options.resultsClass).css("position", "absolute");
    if( options.width > 0 ) {
        $results.css("width", options.width);
    }

    // Add to body element
    $("body").append(results);

    input.autocompleter = me;

    var timeout = null;
    var prev = "";
    var active = -1;
    var cache = {};
    var keyb = false;
    var hasFocus = false;
    var lastKeyPressCode = null;
    var mouseDownOnSelect = false;
    var hidingResults = false;

    // flush cache
    function flushCache(){
        cache = {};
        cache.data = {};
        cache.length = 0;
    };

    // flush cache
    flushCache();

    // if there is a data array supplied
    if( options.data != null ){
        var sFirstChar = "", stMatchSets = {}, row = [];

        // no url was specified, we need to adjust the cache length to make sure it fits the local data store
        if( typeof options.url != "string" ) {
            options.cacheLength = 1;
        }

        // loop through the array and create a lookup structure
        for( var i=0; i < options.data.length; i++ ){
            // if row is a string, make an array otherwise just reference the array
            row = ((typeof options.data[i] == "string") ? [options.data[i]] : options.data[i]);

            // if the length is zero, don't add to list
            if( row[0].length > 0 ){
                // get the first character
                sFirstChar = row[0].substring(0, 1).toLowerCase();
                // if no lookup array for this character exists, look it up now
                if( !stMatchSets[sFirstChar] ) stMatchSets[sFirstChar] = [];
                // if the match is a string
                stMatchSets[sFirstChar].push(row);
            }
        }

        // add the data items to the cache
        for( var k in stMatchSets ) {
            // increase the cache size
            options.cacheLength++;
            // add to the cache
            //addToCache(k, stMatchSets[k]);
        }
    }

    $input
    .keyup(function(e) {
        // track last key pressed
        lastKeyPressCode = e.keyCode;
        switch(e.keyCode) {
            case 38: // up
                e.preventDefault();
                moveSelect(-1);
                break;
            case 40: // down
                e.preventDefault();
                moveSelect(1);
                break;
            case 9:  // tab
            case 13: // return
                if( selectCurrent() ){
                    // make sure to blur off the current field
                    $input.get(0).blur();
                    e.preventDefault();
                }
                break;
            default:
                active = -1;
                if (timeout) clearTimeout(timeout);
                timeout = setTimeout(function(){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 = true;
    })
    .blur(function() {
        // track whether the field has focus
        hasFocus = false;
        if (!mouseDownOnSelect) {
            hideResults();
        }
    });

    hideResultsNow();

    function onChange() {
        // ignore if the following keys are pressed: [del] [shift] [capslock]
        if( lastKeyPressCode == 46 || (lastKeyPressCode > 8 && lastKeyPressCode < 32) ) return $results.hide();
        var v = $input.val();
        if (v == prev) return;
        prev = v;
        if (v.length >= options.minChars) {
            $input.addClass(options.loadingClass);
            requestData(v);
        } else {
            $input.removeClass(options.loadingClass);
            $results.hide();
        }
    };

     function moveSelect(step) {

        var lis = $("li", results);
        if (!lis) return;

        active += step;

        if (active < 0) {
            active = 0;
        } else if (active >= lis.size()) {
            active = lis.size() - 1;
        }

        lis.removeClass("ac_over");

        $(lis[active]).addClass("ac_over");

        // Weird behaviour in IE
        // if (lis[active] && lis[active].scrollIntoView) {
        //     lis[active].scrollIntoView(false);
        // }

    };

    function selectCurrent() {
        var li = $("li.ac_over", results)[0];
        if (!li) {
            var $li = $("li", results);
            if (options.selectOnly) {
                if ($li.length == 1) li = $li[0];
            } else if (options.selectFirst) {
                li = $li[0];
            }
        }
        if (li) {
            selectItem(li);
            return true;
        } else {
            return false;
        }
    };

    function selectItem(li) {
        if (!li) {
            li = document.createElement("li");
            li.extra = [];
            li.selectValue = "";
        }
        var v = $.trim(li.selectValue ? li.selectValue : li.innerHTML);
        input.lastSelected = v;
        prev = v;
        $results.html("");
        $input.val(v);
        hideResultsNow();
        if (options.onItemSelect) {
            setTimeout(function() { options.onItemSelect(li) }, 1);
        }
        
    };

    // selects a portion of the input string
    function createSelection(start, end){
        // get a reference to the input element
        var field = $input.get(0);
        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();
    };

    // fills in the input box w/the first match (assumed to be the best match)
    function autoFill(sValue){
        // if the last user key pressed was backspace, don't autofill
        if( lastKeyPressCode != 8 ){
            // fill in the value (keep the case the user has typed)
            $input.val($input.val() + sValue.substring(prev.length));
            // select the portion of the value not typed by the user (so the next character will erase)
            createSelection(prev.length, sValue.length);
        }
    };

    function showResults() {
        // get the position of the input field right now (in case the DOM is shifted)
        var pos = findPos(input);
        // either use the specified width, or autocalculate based on form element
        var iWidth = (options.width > 0) ? options.width : $input.width();
        // reposition
        $results.css({
            width: parseInt(iWidth) + "px",
            top: (pos.y + input.offsetHeight) + "px",
            left: pos.x + "px"
        }).show();
    };

    function hideResults() {
        if (timeout) clearTimeout(timeout);
        timeout = setTimeout(hideResultsNow, 200);
    };

    function hideResultsNow() {
        
        if (hidingResults) {
            return;
        }
        hidingResults = true;
    
        if (timeout) {
            clearTimeout(timeout);
        }
        
        var v = $input.removeClass(options.loadingClass).val();
        
        if ($results.is(":visible")) {
            $results.hide();
        }
        
        if (options.mustMatch) {
            if (!input.lastSelected || input.lastSelected != v) {
                selectItem(null);
            }
        }

        hidingResults = false;
    };

    function receiveData(q, data) {
        if (data) {
            $input.removeClass(options.loadingClass);
            results.innerHTML = "";

            // if the field no longer has focus or if there are no matches, do not display the drop down
            if( !hasFocus || data.length == 0 ) return hideResultsNow();

            if ($.browser.msie) {
                // we put a styled iframe behind the calendar so HTML SELECT elements don't show through
                $results.append(document.createElement('iframe'));
            }
            results.appendChild(dataToDom(data));
            // autofill in the complete box w/the first match as long as the user hasn't entered in more data
            if( options.autoFill && ($input.val().toLowerCase() == q.toLowerCase()) ) autoFill(data[0][0]);
            showResults();
        } else {
            hideResultsNow();
        }
    };

    function parseData(data) {
        if (!data) return null;
        var parsed = [];
        var rows = data.split(options.lineSeparator);
        for (var i=0; i < rows.length; i++) {
            var row = $.trim(rows[i]);
            if (row) {
                parsed[parsed.length] = row.split(options.cellSeparator);
            }
        }
        return parsed;
    };

    function dataToDom(data) {
        var ul = document.createElement("ul");
        var num = data.length;

        // limited results to a max number
        if( (options.maxItemsToShow > 0) && (options.maxItemsToShow < num) ) num = options.maxItemsToShow;

        for (var i=0; i < num; i++) {
            var row = data[i];
            if (!row) continue;
            var li = document.createElement("li");
            if (options.formatItem) {
                li.innerHTML = options.formatItem(row, i, num);
                li.selectValue = row[0];
            } else {
                li.innerHTML = row[0];
                li.selectValue = row[0];
            }
            var extra = null;
            if (row.length > 1) {
                extra = [];
                for (var j=1; j < row.length; j++) {
                    extra[extra.length] = row[j];
                }
            }
            li.extra = extra;
            ul.appendChild(li);
            
            $(li).hover(
                function() { $("li", ul).removeClass("ac_over"); $(this).addClass("ac_over"); active = $("li", ul).indexOf($(this).get(0)); },
                function() { $(this).removeClass("ac_over"); }
            ).click(function(e) { 
                e.preventDefault();
                e.stopPropagation();
                selectItem(this)
            });
            
        }
        $(ul).mousedown(function() {
            mouseDownOnSelect = true;
        }).mouseup(function() {
            mouseDownOnSelect = false;
        });
        return ul;
    };

    function requestData(q) {
        if (!options.matchCase) q = q.toLowerCase();
        var data = options.cacheLength ? loadFromCache(q) : null;
        // recieve the cached data
        if (data) {
            receiveData(q, data);
        // if an AJAX url has been supplied, try loading the data now
        } else if( (typeof options.url == "string") && (options.url.length > 0) ){
            $.get(makeUrl(q), function(data) {
                data = parseData(data);
                //addToCache(q, data);
                receiveData(q, data);
            });
        // if there's been no data found, remove the loading class
        } else {
            $input.removeClass(options.loadingClass);
        }
    };

    function makeUrl(q) {
        var sep = options.url.indexOf('?') == -1 ? '?' : '&'; 
        var url = options.url + sep + "q=" + encodeURI(q);
        for (var i in options.extraParams) {
            url += "&" + i + "=" + encodeURI(options.extraParams[i]);
        }
        return url;
    };

    function loadFromCache(q) {
        if (!q) return null;
        if (cache.data[q]) return cache.data[q];
        if (options.matchSubset) {
            for (var i = q.length - 1; i >= options.minChars; i--) {
                var qs = q.substr(0, i);
                var c = cache.data[qs];
                if (c) {
                    var csub = [];
                    for (var j = 0; j < c.length; j++) {
                        var x = c[j];
                        var x0 = x[0];
                        if (matchSubset(x0, q)) {
                            csub[csub.length] = x;
                        }
                    }
                    return csub;
                }
            }
        }
        return null;
    };

    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;
    };

    this.flushCache = function() {
        flushCache();
    };

    this.setExtraParams = function(p) {
        options.extraParams = p;
    };

    this.findValue = function(){
        var q = $input.val();

        if (!options.matchCase) q = q.toLowerCase();
        var data = options.cacheLength ? loadFromCache(q) : null;
        if (data) {
            findValueCallback(q, data);
        } else if( (typeof options.url == "string") && (options.url.length > 0) ){
            $.get(makeUrl(q), function(data) {
                data = parseData(data)
                addToCache(q, data);
                findValueCallback(q, data);
            });
        } else {
            // no matches
            findValueCallback(q, null);
        }
    }

    function findValueCallback(q, data){
        if (data) $input.removeClass(options.loadingClass);

        var num = (data) ? data.length : 0;
        var li = null;

        for (var i=0; i < num; i++) {
            var row = data[i];

            if( row[0].toLowerCase() == q.toLowerCase() ){
                li = document.createElement("li");
                if (options.formatItem) {
                    li.innerHTML = options.formatItem(row, i, num);
                    li.selectValue = row[0];
                } else {
                    li.innerHTML = row[0];
                    li.selectValue = row[0];
                }
                var extra = null;
                if( row.length > 1 ){
                    extra = [];
                    for (var j=1; j < row.length; j++) {
                        extra[extra.length] = row[j];
                    }
                }
                li.extra = extra;
            }
        }

        if( options.onFindValue ) setTimeout(function() { options.onFindValue(li) }, 1);
    }

    function addToCache(q, data) {
        //if (!data || !q || !options.cacheLength) return;
        //if (!cache.length || cache.length > options.cacheLength) {
        //    flushCache();
        //    cache.length++;
        //} else if (!cache[q]) {
        //    cache.length++;
        //}
        //cache.data[q] = data;
    };

    function findPos(obj) {
        var curleft = obj.offsetLeft || 0;
        var curtop = obj.offsetTop || 0;
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        }
        return {x:curleft,y:curtop};
    }
}

jQuery.fn.autocomplete = function(url, options, data) {
    // Make sure options exists
    options = options || {};
    // Set url as option
    options.url = url;
    // set some bulk local data
    options.data = ((typeof data == "object") && (data.constructor == Array)) ? data : null;

    // Set default values for required options
    options = $.extend({
        inputClass: "ac_input",
        resultsClass: "ac_results",
        lineSeparator: "\n",
        cellSeparator: "|",
        minChars: 1,
        delay: 400,
        matchCase: 0,
        matchSubset: 1,
        matchContains: 0,
        cacheLength: 1,
        mustMatch: 0,
        extraParams: {},
        loadingClass: "ac_loading",
        selectFirst: false,
        selectOnly: false,
        maxItemsToShow: -1,
        autoFill: false,
        width: 0
    }, options);
    options.width = parseInt(options.width, 10);

    this.each(function() {
        var input = this;
        new jQuery.autocomplete(input, options);
    });

    // Don't break the chain
    return this;
}

jQuery.fn.autocompleteArray = function(data, options) {
    return this.autocomplete(null, options, data);
}

jQuery.fn.indexOf = function(e){
    for( var i=0; i<this.length; i++ ){
        if( this[i] == e ) return i;
    }
    return -1;
};


/*
 * FaceList 1.1 - Facebook Style List Box
 *
 * Copyright (c) 2008 Ian Tearle (iantearle.com)
 * Original take by Xavier Domenech 
 * Original autocomplete  by Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, JГ¶rn Zaefferer
 *
 * $Date: 2008-07-07 11:02:02 -0000 (Wed, 06 Feb 2008) 
 *
 *    ChangeLog:
 *  11/11/08    Changes from Theo Chakkapark (linkedin.com/in/theochakkapark): 
 *                - Now properly matches against all returned elements
 *                 - Does not allow duplicate results
 *                - Does not need to show ID along with the result
 *    08/07/08     - Added .replace(/ /g,'_') to string replaces to allow for multiple spaces in the string.
 *                - Added data[0] to select first array from split string
 *    09/07/08    - Altered data[1] in remove_tag_data() function so it passes data[1] from the onClick function
 */
(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 ? 10 : 150
        }, options);
        // if highlight is set to false, replace it with a do-nothing function
        options.highlight = options.highlight || function(value) { return value; };
        
        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: 8,
        TAB: 9,
        RETURN: 13,
        ESC: 27,
        COMMA: 188,
        PAGEUP: 33,
        PAGEDOWN: 34
    };
    // Create $ object for input element
    var $input = $(input).attr("autocomplete", "off");
    
    $input.click(function (){$('.default').remove();$('#'+options.result_cont).append('<div class="default">'+options.intro_text+'</div>');$('#'+options.result_cont).css('display','');})
    $('body').click(function (){ $('#'+options.result_cont+' ul').remove();});
    $('.'+options.classname).click(function (){ $input.focus();});
    var timeout;
    var previousValue = "";
    var cache = $.Autocompleter.Cache(options);
    var hasFocus = 0;
    var lastKeyPressCode;
    var config = {
        mouseDownOnSelect: true
    };
    var select = $.Autocompleter.Select(options, input, selectCurrent, config);
    
    $input.before('<input type="hidden" name="'+options.result_field+'" id="'+options.result_field+'" value="">');

    
    $input.keydown(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 KEY.TAB:
            case KEY.RETURN:
                if( selectCurrent() ){
                    $input.blur();
                    event.preventDefault();
                }
                break;
            case KEY.DEL:
                arr_user = $('#'+options.result_field).val().split(",");
                data_tag = new String(arr_user[arr_user.length - 2]);
                if($input.val() == "" && $('.'+options.classname+' #bit-'+data_tag) && $('.'+options.classname+' #bit-'+data_tag).attr('class') == "token token_selected")
                {
                    Remove_tag_data(arr_user[arr_user.length - 2]);
                }
                else if($input.val() == "" && $('.'+options.classname+' #bit-'+arr_user[arr_user.length - 2]) && $('.'+options.classname+' #bit-'+arr_user[arr_user.length - 2]).attr('class') != "token token_selected")
                {
                    $('.'+options.classname+' #bit-'+data_tag).addClass('token_selected');
                }
                else if($input.val().length == 1)
                {
                    $('#'+options.result_cont+' ul').remove();
                    $('#'+options.result_cont+' div').remove();
                    $('#'+options.result_cont+'').append('<div class="default">'+options.intro_text+'</div>');
                }
                else
                {
                    onChange(1, true);
                }
                    
            break;    
            case KEY.ESC:
                select.hide();
                $('#'+options.result_cont+' ul').remove();
                $input.val('');
                break;
                
            default:
                clearTimeout(timeout);
                timeout = setTimeout(onChange, options.delay);
                break;
        }
    }).keypress(function() {
        // having fun with opera - remove this binding and Opera submits the form when we select an entry via return
    }).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;
    }).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]);
        }
    }).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();
    });
    function Remove_tag_data(data)
    {
        if(document.getElementById('error_city')) jQuery('#city').show(); 
        options.data += ','+data;
        options.data = new String(data).split(",").sort().toString();
        $(options.classname+' #bit-'+new String(data).replace(/ /g,'_')).remove();
        $('#'+options.result_field).val(new String($('#'+options.result_field).val().replace(data,"")));
        repairValueList();
        if(document.getElementById('main_listing')) apply_search_filter();
        return false;
    }
    function MakeBox(data)
    {
        elemLI = $('<li id="bit-'+new String(data[1]).replace(/ /g,'_')+'" class="token"><span><span><span><span>'+data[0]+'</span></span></span></span></li>').click(function () {$('.token').removeClass('token_selected'); $(this).addClass("token_selected");},function () {$(this).removeClass("token_selected");});

        elemA = $('<span class="x" onclick="autocomplete_Remove_tag_data(\''+options.classname+'\', \''+data[1]+'\')"> .x</span>');
        $(elemLI).append(elemA);
        $('#'+options.result_cont+' ul').remove();
        $('.'+options.classname+' .token-input').before(elemLI);
        $input.val('');
        $input.focus();
        $('#'+options.user_list).focus();
        if(document.getElementById('main_listing')) apply_search_filter();
    }
    function selectCurrent() {
        if(document.getElementById('error_city')) jQuery('#city').hide(); 
        var selected = select.selected();
        if( !selected )
            return false;
        
        if($('#'+options.result_cont+' ul').get() != "" && $('#'+options.result_cont+' ul#no_result').get() == "")
        {    
            RemoveData(selected.data);
            MakeBox(selected.data);
            return true;
        }
        else
            return false;
    }
    function RemoveData(data)
    {
        list_users = new String(options.data).replace(/ /g,'_');
        options.data = list_users.replace(data[1],"");
        $('#'+options.result_field).val( $('#'+options.result_field).val()+","+data[1]);
        repairValueList();
    };
    
    function repairValueList(){
        //Begin cleanup
        var result = $('#'+options.result_field).val();
        result = result.split(",");
        //Loop through the array and rebuild the string
        var i = 0;
        var str = "";
        for(i=0; i < result.length; i++){
            if(result[i] == ""){
                continue;
            }
            str = str + result[i];
            str = str + ",";                
        }
        
        $('#'+options.result_field).val(str);        
    };
    
    function onChange(crap, skipPrevCheck) {
        crap == 1?valor = $input.val().substring(0,($input.val().length-1)):valor = $input.val();
        request(valor.toLowerCase(), receiveData, noData);
    };
    
    function noData() {
        $('.default').remove();
        $('#'+options.result_cont+' ul').remove()
        $('#'+options.result_cont+'').append('<ul id="no_result"><li>'+options.no_result+'</li></ul>')
    };

    function receiveData(q, data) {
        if (q != "" && data && data.length && hasFocus ) {
            select.display(data, q);
            select.show();
        } else {
            $('#'+options.result_cont+' ul').remove();
        }
    };

    function request(term, success, failure) {
        term = term.toLowerCase();
        //var data = cache.load(term);
        //ORGINAL
        /*// recieve the cached data
        if (data && data.length) {
            success(term, data);
        } else {
            failure(term);
        }*/
        //ORIGINAL END
        $('#'+options.result_cont+'').html('<div class="default">Searching...</div>');
        if(typeof options.url == 'string')
        {
            var sep = options.url.indexOf('?') == -1 ? '?' : '&'; 
            var url = options.url + sep + "q=" + encodeURI(term);
            if(document.getElementById('error_city'))  url += "&country=" + jQuery('#country').val();
            if(document.getElementById('filter_payment'))  url += "&no_continents=1";
            
            $.get(
                url,
                function(data)
                {
                    data = parse(data);
                    //cache.add(term, data);
                    receiveData(term, data);
                    if(data.length == 0){
                            $('#'+options.result_cont+'').html('<div class="default">No Results Found</div>');
                    }
                }
                );        
        }
        else
        {
            //var data = cache.load(term);
            // recieve the cached data
            //if (data && data.length) {
            //    success(term, data);
            //} else {
            //    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("|",2);
                parsed[parsed.length] = {
                    data: row,
                    value: row[0],
                    result: options.formatResult && options.formatResult(row, row[0]) || row[0]
                };
            }
        }
        return parsed;
    };
};

$.Autocompleter.defaults = {
    minChars: 1,
    delay: 400,
    cacheLength: 1,
    max: 100,
    selectFirst: true,
    width: 0,
    highlight: function(value, term) {
        return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<em>$1</em>");
    },
       intro_text: 'Type in the box',
    result_field: 'to_users',
    no_result: 'No user result'
};

$.Autocompleter.Cache = function(options) {

    var data = {};
    var length = 0;
    
    function matchSubset(s, sub) {
        var i = s.toLowerCase().indexOf(sub);
        if (i == -1) return false;
        return i == 0 || true;
    };
    
    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 = new String(rawValue);
            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
             */
                // 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;
            
            return null;
        }
    };
};


(function(d){function R(a,c){return 32-(new Date(a,c,32)).getDate()}function S(a,c){a=""+a;for(c=c||2;a.length<c;)a="0"+a;return a}function T(a,c,j){var q=a.getDate(),h=a.getDay(),r=a.getMonth();a=a.getFullYear();var f={d:q,dd:S(q),ddd:B[j].shortDays[h],dddd:B[j].days[h],m:r+1,mm:S(r+1),mmm:B[j].shortMonths[r],mmmm:B[j].months[r],yy:String(a).slice(2),yyyy:a};c=c.replace(X,function(s){return s in f?f[s]:s.slice(1,s.length-1)});return Y.html(c).html()}function v(a){return parseInt(a,10)}function U(a,
c){return a.getFullYear()===c.getFullYear()&&a.getMonth()==c.getMonth()&&a.getDate()==c.getDate()}function C(a){if(a){if(a.constructor==Date)return a;if(typeof a=="string"){var c=a.split("-");if(c.length==3)return new Date(v(c[0]),v(c[1])-1,v(c[2]));if(!/^-?\d+$/.test(a))return;a=v(a)}c=new Date;c.setDate(c.getDate()+a);return c}}function Z(a,c){function j(b,e,g){n=b;D=b.getFullYear();E=b.getMonth();G=b.getDate();g=g||d.Event("api");g.type="change";H.trigger(g,[b]);if(!g.isDefaultPrevented()){a.val(T(b,
e.format,e.lang));a.data("date",b);h.hide(g)}}function q(b){b.type="onShow";H.trigger(b);d(document).bind("keydown.d",function(e){if(e.ctrlKey)return true;var g=e.keyCode;if(g==8){a.val("");return h.hide(e)}if(g==27)return h.hide(e);if(d(V).index(g)>=0){if(!w){h.show(e);return e.preventDefault()}var i=d("#"+f.weeks+" a"),t=d("."+f.focus),o=i.index(t);t.removeClass(f.focus);if(g==74||g==40)o+=7;else if(g==75||g==38)o-=7;else if(g==76||g==39)o+=1;else if(g==72||g==37)o-=1;if(o>41){h.addMonth();t=d("#"+
f.weeks+" a:eq("+(o-42)+")")}else if(o<0){h.addMonth(-1);t=d("#"+f.weeks+" a:eq("+(o+42)+")")}else t=i.eq(o);t.addClass(f.focus);return e.preventDefault()}if(g==34)return h.addMonth();if(g==33)return h.addMonth(-1);if(g==36)return h.today();if(g==13)d(e.target).is("select")||d("."+f.focus).click();return d([16,17,18,9]).index(g)>=0});d(document).bind("click.d",function(e){var g=e.target;if(!d(g).parents("#"+f.root).length&&g!=a[0]&&(!L||g!=L[0]))h.hide(e)})}var h=this,r=new Date,f=c.css,s=B[c.lang],
k=d("#"+f.root),M=k.find("#"+f.title),L,I,J,D,E,G,n=a.attr("data-value")||c.value||a.val(),m=a.attr("min")||c.min,p=a.attr("max")||c.max,w;if(m===0)m="0";n=C(n)||r;m=C(m||c.yearRange[0]*365);p=C(p||c.yearRange[1]*365);if(!s)throw"Dateinput: invalid language: "+c.lang;if(a.attr("type")=="date"){var N=d("<input/>");d.each("class,disabled,id,maxlength,name,readonly,required,size,style,tabindex,title,value".split(","),function(b,e){N.attr(e,a.attr(e))});a.replaceWith(N);a=N}a.addClass(f.input);var H=
a.add(h);if(!k.length){k=d("<div><div><a/><div/><a/></div><div><div/><div/></div></div>").hide().css({position:"absolute"}).attr("id",f.root);k.children().eq(0).attr("id",f.head).end().eq(1).attr("id",f.body).children().eq(0).attr("id",f.days).end().eq(1).attr("id",f.weeks).end().end().end().find("a").eq(0).attr("id",f.prev).end().eq(1).attr("id",f.next);M=k.find("#"+f.head).find("div").attr("id",f.title);if(c.selectors){var z=d("<select/>").attr("id",f.month),A=d("<select/>").attr("id",f.year);M.html(z.add(A))}for(var $=
k.find("#"+f.days),O=0;O<7;O++)$.append(d("<span/>").text(s.shortDays[(O+c.firstDay)%7]));d("body").append(k)}if(c.trigger)L=d("<a/>").attr("href","#").addClass(f.trigger).click(function(b){h.show();return b.preventDefault()}).insertAfter(a);var K=k.find("#"+f.weeks);A=k.find("#"+f.year);z=k.find("#"+f.month);d.extend(h,{show:function(b){if(!(a.attr("readonly")||a.attr("disabled")||w)){b=b||d.Event();b.type="onBeforeShow";H.trigger(b);if(!b.isDefaultPrevented()){d.each(W,function(){this.hide()});
w=true;z.unbind("change").change(function(){h.setValue(A.val(),d(this).val())});A.unbind("change").change(function(){h.setValue(d(this).val(),z.val())});I=k.find("#"+f.prev).unbind("click").click(function(){I.hasClass(f.disabled)||h.addMonth(-1);return false});J=k.find("#"+f.next).unbind("click").click(function(){J.hasClass(f.disabled)||h.addMonth();return false});h.setValue(n);var e=a.offset();if(/iPad/i.test(navigator.userAgent))e.top-=d(window).scrollTop();k.css({top:e.top+a.outerHeight({margins:true})+
c.offset[0],left:e.left+c.offset[1]});if(c.speed)k.show(c.speed,function(){q(b)});else{k.show();q(b)}return h}}},setValue:function(b,e,g){var i=v(e)>=-1?new Date(v(b),v(e),v(g||1)):b||n;if(i<m)i=m;else if(i>p)i=p;b=i.getFullYear();e=i.getMonth();g=i.getDate();if(e==-1){e=11;b--}else if(e==12){e=0;b++}if(!w){j(i,c);return h}E=e;D=b;g=new Date(b,e,1-c.firstDay);g=g.getDay();var t=R(b,e),o=R(b,e-1),P;if(c.selectors){z.empty();d.each(s.months,function(x,F){m<new Date(b,x+1,-1)&&p>new Date(b,x,0)&&z.append(d("<option/>").html(F).attr("value",
x))});A.empty();i=r.getFullYear();for(var l=i+c.yearRange[0];l<i+c.yearRange[1];l++)m<=new Date(l+1,-1,1)&&p>new Date(l,0,0)&&A.append(d("<option/>").text(l));z.val(e);A.val(b)}else M.html(s.months[e]+" "+b);K.empty();I.add(J).removeClass(f.disabled);l=!g?-7:0;for(var u,y;l<(!g?35:42);l++){u=d("<a/>");if(l%7===0){P=d("<div/>").addClass(f.week);K.append(P)}if(l<g){u.addClass(f.off);y=o-g+l+1;i=new Date(b,e-1,y)}else if(l>=g+t){u.addClass(f.off);y=l-t-g+1;i=new Date(b,e+1,y)}else{y=l-g+1;i=new Date(b,
e,y);if(U(n,i))u.attr("id",f.current).addClass(f.focus);else U(r,i)&&u.attr("id",f.today)}m&&i<m&&u.add(I).addClass(f.disabled);p&&i>p&&u.add(J).addClass(f.disabled);u.attr("href","#"+y).text(y).data("date",i);P.append(u)}K.find("a").click(function(x){var F=d(this);if(!F.hasClass(f.disabled)){d("#"+f.current).removeAttr("id");F.attr("id",f.current);j(F.data("date"),c,x)}return false});f.sunday&&K.find(f.week).each(function(){var x=c.firstDay?7-c.firstDay:0;d(this).children().slice(x,x+1).addClass(f.sunday)});
return h},setMin:function(b,e){m=C(b);e&&n<m&&h.setValue(m);return h},setMax:function(b,e){p=C(b);e&&n>p&&h.setValue(p);return h},today:function(){return h.setValue(r)},addDay:function(b){return this.setValue(D,E,G+(b||1))},addMonth:function(b){return this.setValue(D,E+(b||1),G)},addYear:function(b){return this.setValue(D+(b||1),E,G)},hide:function(b){if(w){b=d.Event();b.type="onHide";H.trigger(b);d(document).unbind("click.d").unbind("keydown.d");if(b.isDefaultPrevented())return;k.hide();w=false}return h},
getConf:function(){return c},getInput:function(){return a},getCalendar:function(){return k},getValue:function(b){return b?T(n,b,c.lang):n},isOpen:function(){return w}});d.each(["onBeforeShow","onShow","change","onHide"],function(b,e){d.isFunction(c[e])&&d(h).bind(e,c[e]);h[e]=function(g){g&&d(h).bind(e,g);return h}});a.bind("focus click",h.show).keydown(function(b){var e=b.keyCode;if(!w&&d(V).index(e)>=0){h.show(b);return b.preventDefault()}return b.shiftKey||b.ctrlKey||b.altKey||e==9?true:b.preventDefault()});
C(a.val())&&j(n,c)}d.tools=d.tools||{version:"1.2.5"};var W=[],Q,V=[75,76,38,39,74,72,40,37],B={};Q=d.tools.dateinput={conf:{format:"mm/dd/yy",selectors:false,yearRange:[-5,5],lang:"en",offset:[0,0],speed:0,firstDay:0,min:undefined,max:undefined,trigger:false,css:{prefix:"cal",input:"date",root:0,head:0,title:0,prev:0,next:0,month:0,year:0,days:0,body:0,weeks:0,today:0,current:0,week:0,off:0,sunday:0,focus:0,disabled:0,trigger:0}},localize:function(a,c){d.each(c,function(j,q){c[j]=q.split(",")});
B[a]=c}};Q.localize("en",{months:"January,February,March,April,May,June,July,August,September,October,November,December",shortMonths:"Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec",days:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday",shortDays:"Sun,Mon,Tue,Wed,Thu,Fri,Sat"});var X=/d{1,4}|m{1,4}|yy(?:yy)?|"[^"]*"|'[^']*'/g,Y=d("<a/>");d.expr[":"].date=function(a){var c=a.getAttribute("type");return c&&c=="date"||!!d(a).data("dateinput")};d.fn.dateinput=function(a){if(this.data("dateinput"))return this;
a=d.extend(true,{},Q.conf,a);d.each(a.css,function(j,q){if(!q&&j!="prefix")a.css[j]=(a.css.prefix||"")+(q||j)});var c;this.each(function(){var j=new Z(d(this),a);W.push(j);j=j.getInput().data("dateinput",j);c=c?c.add(j):j});return c?c:this}})(jQuery);
(function(e){function F(d,a){a=Math.pow(10,a);return Math.round(d*a)/a}function q(d,a){if(a=parseInt(d.css(a),10))return a;return(d=d[0].currentStyle)&&d.width&&parseInt(d.width,10)}function C(d){return(d=d.data("events"))&&d.onSlide}function G(d,a){function h(c,b,f,j){if(f===undefined)f=b/k*z;else if(j)f-=a.min;if(s)f=Math.round(f/s)*s;if(b===undefined||s)b=f*k/z;if(isNaN(f))return g;b=Math.max(0,Math.min(b,k));f=b/k*z;if(j||!n)f+=a.min;if(n)if(j)b=k-b;else f=a.max-f;f=F(f,t);var r=c.type=="click";
if(D&&l!==undefined&&!r){c.type="onSlide";A.trigger(c,[f,b]);if(c.isDefaultPrevented())return g}j=r?a.speed:0;r=r?function(){c.type="change";A.trigger(c,[f])}:null;if(n){m.animate({top:b},j,r);a.progress&&B.animate({height:k-b+m.width()/2},j)}else{m.animate({left:b},j,r);a.progress&&B.animate({width:b+m.width()/2},j)}l=f;H=b;d.val(f);return g}function o(){if(n=a.vertical||q(i,"height")>q(i,"width")){k=q(i,"height")-q(m,"height");u=i.offset().top+k}else{k=q(i,"width")-q(m,"width");u=i.offset().left}}
function v(){o();g.setValue(a.value!==undefined?a.value:a.min)}var g=this,p=a.css,i=e("<div><div/><a href='#'/></div>").data("rangeinput",g),n,l,u,k,H;d.before(i);var m=i.addClass(p.slider).find("a").addClass(p.handle),B=i.find("div").addClass(p.progress);e.each("min,max,step,value".split(","),function(c,b){c=d.attr(b);if(parseFloat(c))a[b]=parseFloat(c,10)});var z=a.max-a.min,s=a.step=="any"?0:a.step,t=a.precision;if(t===undefined)try{t=s.toString().split(".")[1].length}catch(I){t=0}if(d.attr("type")==
"range"){var w=e("<input/>");e.each("class,disabled,id,maxlength,name,readonly,required,size,style,tabindex,title,value".split(","),function(c,b){w.attr(b,d.attr(b))});w.val(a.value);d.replaceWith(w);d=w}d.addClass(p.input);var A=e(g).add(d),D=true;e.extend(g,{getValue:function(){return l},setValue:function(c,b){o();return h(b||e.Event("api"),undefined,c,true)},getConf:function(){return a},getProgress:function(){return B},getHandle:function(){return m},getInput:function(){return d},step:function(c,
b){b=b||e.Event();var f=a.step=="any"?1:a.step;g.setValue(l+f*(c||1),b)},stepUp:function(c){return g.step(c||1)},stepDown:function(c){return g.step(-c||-1)}});e.each("onSlide,change".split(","),function(c,b){e.isFunction(a[b])&&e(g).bind(b,a[b]);g[b]=function(f){f&&e(g).bind(b,f);return g}});m.drag({drag:false}).bind("dragStart",function(){o();D=C(e(g))||C(d)}).bind("drag",function(c,b,f){if(d.is(":disabled"))return false;h(c,n?b:f)}).bind("dragEnd",function(c){if(!c.isDefaultPrevented()){c.type=
"change";A.trigger(c,[l])}}).click(function(c){return c.preventDefault()});i.click(function(c){if(d.is(":disabled")||c.target==m[0])return c.preventDefault();o();var b=m.width()/2;h(c,n?k-u-b+c.pageY:c.pageX-u-b)});a.keyboard&&d.keydown(function(c){if(!d.attr("readonly")){var b=c.keyCode,f=e([75,76,38,33,39]).index(b)!=-1,j=e([74,72,40,34,37]).index(b)!=-1;if((f||j)&&!(c.shiftKey||c.altKey||c.ctrlKey)){if(f)g.step(b==33?10:1,c);else if(j)g.step(b==34?-10:-1,c);return c.preventDefault()}}});d.blur(function(c){var b=
e(this).val();b!==l&&g.setValue(b,c)});e.extend(d[0],{stepUp:g.stepUp,stepDown:g.stepDown});v();k||e(window).load(v)}e.tools=e.tools||{version:"1.2.5"};var E;E=e.tools.rangeinput={conf:{min:0,max:100,step:"any",steps:0,value:0,precision:undefined,vertical:0,keyboard:true,progress:false,speed:100,css:{input:"range",slider:"slider",progress:"progress",handle:"handle"}}};var x,y;e.fn.drag=function(d){document.ondragstart=function(){return false};d=e.extend({x:true,y:true,drag:true},d);x=x||e(document).bind("mousedown mouseup",
function(a){var h=e(a.target);if(a.type=="mousedown"&&h.data("drag")){var o=h.position(),v=a.pageX-o.left,g=a.pageY-o.top,p=true;x.bind("mousemove.drag",function(i){var n=i.pageX-v;i=i.pageY-g;var l={};if(d.x)l.left=n;if(d.y)l.top=i;if(p){h.trigger("dragStart");p=false}d.drag&&h.css(l);h.trigger("drag",[i,n]);y=h});a.preventDefault()}else try{y&&y.trigger("dragEnd")}finally{x.unbind("mousemove.drag");y=null}});return this.data("drag",true)};e.expr[":"].range=function(d){var a=d.getAttribute("type");
return a&&a=="range"||!!e(d).filter("input").data("rangeinput")};e.fn.rangeinput=function(d){if(this.data("rangeinput"))return this;d=e.extend(true,{},E.conf,d);var a;this.each(function(){var h=new G(e(this),e.extend(true,{},d));h=h.getInput().data("rangeinput",h);a=a?a.add(h):h});return a?a:this}})(jQuery);
(function(e){function t(a,b,c){var k=a.offset().top,f=a.offset().left,l=c.position.split(/,?\s+/),p=l[0];l=l[1];k-=b.outerHeight()-c.offset[0];f+=a.outerWidth()+c.offset[1];if(/iPad/i.test(navigator.userAgent))k-=e(window).scrollTop();c=b.outerHeight()+a.outerHeight();if(p=="center")k+=c/2;if(p=="bottom")k+=c;a=a.outerWidth();if(l=="center")f-=(a+b.outerWidth())/2;if(l=="left")f-=a;return{top:k,left:f}}function y(a){function b(){return this.getAttribute("type")==a}b.key="[type="+a+"]";return b}function u(a,
b,c){function k(g,d,i){if(!(!c.grouped&&g.length)){var j;if(i===false||e.isArray(i)){j=h.messages[d.key||d]||h.messages["*"];j=j[c.lang]||h.messages["*"].en;(d=j.match(/\$\d/g))&&e.isArray(i)&&e.each(d,function(m){j=j.replace(this,i[m])})}else j=i[c.lang]||i;g.push(j)}}var f=this,l=b.add(f);a=a.not(":button, :image, :reset, :submit");e.extend(f,{getConf:function(){return c},getForm:function(){return b},getInputs:function(){return a},reflow:function(){a.each(function(){var g=e(this),d=g.data("msg.el");
if(d){g=t(g,d,c);d.css({top:g.top,left:g.left})}});return f},invalidate:function(g,d){if(!d){var i=[];e.each(g,function(j,m){j=a.filter("[name='"+j+"']");if(j.length){j.trigger("OI",[m]);i.push({input:j,messages:[m]})}});g=i;d=e.Event()}d.type="onFail";l.trigger(d,[g]);d.isDefaultPrevented()||q[c.effect][0].call(f,g,d);return f},reset:function(g){g=g||a;g.removeClass(c.errorClass).each(function(){var d=e(this).data("msg.el");if(d){d.remove();e(this).data("msg.el",null)}}).unbind(c.errorInputEvent||
"");return f},destroy:function(){b.unbind(c.formEvent+".V").unbind("reset.V");a.unbind(c.inputEvent+".V").unbind("change.V");return f.reset()},checkValidity:function(g,d){g=g||a;g=g.not(":disabled");if(!g.length)return true;d=d||e.Event();d.type="onBeforeValidate";l.trigger(d,[g]);if(d.isDefaultPrevented())return d.result;var i=[];g.not(":radio:not(:checked)").each(function(){var m=[],n=e(this).data("messages",m),v=r&&n.is(":date")?"onHide.v":c.errorInputEvent+".v";n.unbind(v);e.each(w,function(){var o=
this,s=o[0];if(n.filter(s).length){o=o[1].call(f,n,n.val());if(o!==true){d.type="onBeforeFail";l.trigger(d,[n,s]);if(d.isDefaultPrevented())return false;var x=n.attr(c.messageAttr);if(x){m=[x];return false}else k(m,s,o)}}});if(m.length){i.push({input:n,messages:m});n.trigger("OI",[m]);c.errorInputEvent&&n.bind(v,function(o){f.checkValidity(n,o)})}if(c.singleError&&i.length)return false});var j=q[c.effect];if(!j)throw'Validator: cannot find effect "'+c.effect+'"';if(i.length){f.invalidate(i,d);return false}else{j[1].call(f,
g,d);d.type="onSuccess";l.trigger(d,[g]);g.unbind(c.errorInputEvent+".v")}return true}});e.each("onBeforeValidate,onBeforeFail,onFail,onSuccess".split(","),function(g,d){e.isFunction(c[d])&&e(f).bind(d,c[d]);f[d]=function(i){i&&e(f).bind(d,i);return f}});c.formEvent&&b.bind(c.formEvent+".V",function(g){if(!f.checkValidity(null,g))return g.preventDefault()});b.bind("reset.V",function(){f.reset()});a[0]&&a[0].validity&&a.each(function(){this.oninvalid=function(){return false}});if(b[0])b[0].checkValidity=
f.checkValidity;c.inputEvent&&a.bind(c.inputEvent+".V",function(g){f.checkValidity(e(this),g)});a.filter(":checkbox, select").filter("[required]").bind("change.V",function(g){var d=e(this);if(this.checked||d.is("select")&&e(this).val())q[c.effect][1].call(f,d,g)});var p=a.filter(":radio").change(function(g){f.checkValidity(p,g)});e(window).resize(function(){f.reflow()})}e.tools=e.tools||{version:"1.2.5"};var z=/\[type=([a-z]+)\]/,A=/^-?[0-9]*(\.[0-9]+)?$/,r=e.tools.dateinput,B=/^([a-z0-9_\.\-\+]+)@([\da-z\.\-]+)\.([a-z\.]{2,6})$/i,
C=/^(https?:\/\/)?[\da-z\.\-]+\.[a-z\.]{2,6}[#&+_\?\/\w \.\-=]*$/i,h;h=e.tools.validator={conf:{grouped:false,effect:"default",errorClass:"invalid",inputEvent:null,errorInputEvent:"keyup",formEvent:"submit",lang:"en",message:"<div/>",messageAttr:"data-message",messageClass:"error",offset:[0,0],position:"center right",singleError:false,speed:"normal"},messages:{"*":{en:"Please correct this value"}},localize:function(a,b){e.each(b,function(c,k){h.messages[c]=h.messages[c]||{};h.messages[c][a]=k})},
localizeFn:function(a,b){h.messages[a]=h.messages[a]||{};e.extend(h.messages[a],b)},fn:function(a,b,c){if(e.isFunction(b))c=b;else{if(typeof b=="string")b={en:b};this.messages[a.key||a]=b}if(b=z.exec(a))a=y(b[1]);w.push([a,c])},addEffect:function(a,b,c){q[a]=[b,c]}};var w=[],q={"default":[function(a){var b=this.getConf();e.each(a,function(c,k){c=k.input;c.addClass(b.errorClass);var f=c.data("msg.el");if(!f){f=e(b.message).addClass(b.messageClass).appendTo(document.body);c.data("msg.el",f)}f.css({visibility:"hidden"}).find("p").remove();
e.each(k.messages,function(l,p){e("<p/>").html(p).appendTo(f)});f.outerWidth()==f.parent().width()&&f.add(f.find("p")).css({display:"inline"});k=t(c,f,b);f.css({visibility:"visible",position:"absolute",top:k.top,left:k.left}).fadeIn(b.speed)})},function(a){var b=this.getConf();a.removeClass(b.errorClass).each(function(){var c=e(this).data("msg.el");c&&c.css({visibility:"hidden"})})}]};e.each("email,url,number".split(","),function(a,b){e.expr[":"][b]=function(c){return c.getAttribute("type")===b}});
e.fn.oninvalid=function(a){return this[a?"bind":"trigger"]("OI",a)};h.fn(":email","Please enter a valid email address",function(a,b){return!b||B.test(b)});h.fn(":url","Please enter a valid URL",function(a,b){return!b||C.test(b)});h.fn(":number","Please enter a numeric value.",function(a,b){return A.test(b)});h.fn("[max]","Please enter a value smaller than $1",function(a,b){if(b===""||r&&a.is(":date"))return true;a=a.attr("max");return parseFloat(b)<=parseFloat(a)?true:[a]});h.fn("[min]","Please enter a value larger than $1",
function(a,b){if(b===""||r&&a.is(":date"))return true;a=a.attr("min");return parseFloat(b)>=parseFloat(a)?true:[a]});h.fn("[required]","Please complete this mandatory field.",function(a,b){if(a.is(":checkbox"))return a.is(":checked");return!!b});h.fn("[pattern]",function(a){var b=new RegExp("^"+a.attr("pattern")+"$");return b.test(a.val())});e.fn.validator=function(a){var b=this.data("validator");if(b){b.destroy();this.removeData("validator")}a=e.extend(true,{},h.conf,a);if(this.is("form"))return this.each(function(){var c=
e(this);b=new u(c.find(":input"),c,a);c.data("validator",b)});else{b=new u(this,this.eq(0).closest("form"),a);return this.data("validator",b)}}})(jQuery);


var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}();

if(jQuery){(function(a){a.extend(a.fn,{uploadify:function(b){a(this).each(function(){settings=a.extend({id:a(this).attr("id"),uploader:"uploadify.swf",script:"uploadify.php",expressInstall:null,folder:"",height:30,width:110,cancelImg:"cancel.png",wmode:"opaque",scriptAccess:"sameDomain",fileDataName:"Filedata",method:"POST",queueSizeLimit:999,simUploadLimit:1,queueID:false,displayData:"percentage",onInit:function(){},onSelect:function(){},onQueueFull:function(){},onCheck:function(){},onCancel:function(){},onError:function(){},onProgress:function(){},onComplete:function(){},onAllComplete:function(){}},b);var e=location.pathname;e=e.split("/");e.pop();e=e.join("/")+"/";var f={};f.uploadifyID=settings.id;f.pagepath=e;if(settings.buttonImg){f.buttonImg=escape(settings.buttonImg)}if(settings.buttonText){f.buttonText=escape(settings.buttonText)}if(settings.rollover){f.rollover=true}f.script=settings.script;f.folder=escape(settings.folder);if(settings.scriptData){var g="";for(var d in settings.scriptData){g+="&"+d+"="+settings.scriptData[d]}f.scriptData=escape(g.substr(1))}f.width=settings.width;f.height=settings.height;f.wmode=settings.wmode;f.method=settings.method;f.queueSizeLimit=settings.queueSizeLimit;f.simUploadLimit=settings.simUploadLimit;if(settings.hideButton){f.hideButton=true}if(settings.fileDesc){f.fileDesc=settings.fileDesc}if(settings.fileExt){f.fileExt=settings.fileExt}if(settings.multi){f.multi=true}if(settings.auto){f.auto=true}if(settings.sizeLimit){f.sizeLimit=settings.sizeLimit}if(settings.checkScript){f.checkScript=settings.checkScript}if(settings.fileDataName){f.fileDataName=settings.fileDataName}if(settings.queueID){f.queueID=settings.queueID}if(settings.onInit()!==false){a(this).css("display","none");a(this).after('<div id="'+a(this).attr("id")+'Uploader"></div>');swfobject.embedSWF(settings.uploader,settings.id+"Uploader",settings.width,settings.height,"9.0.24",settings.expressInstall,f,{quality:"high",wmode:settings.wmode,allowScriptAccess:settings.scriptAccess});if(settings.queueID==false){a("#"+a(this).attr("id")+"Uploader").after('<div id="'+a(this).attr("id")+'Queue" class="uploadifyQueue"></div>')}}if(typeof(settings.onOpen)=="function"){a(this).bind("uploadifyOpen",settings.onOpen)}a(this).bind("uploadifySelect",{action:settings.onSelect,queueID:settings.queueID},function(j,h,i){if(j.data.action(j,h,i)!==false){var k=Math.round(i.size/1024*100)*0.01;var l="KB";if(k>1000){k=Math.round(k*0.001*100)*0.01;l="MB"}var m=k.toString().split(".");if(m.length>1){k=m[0]+"."+m[1].substr(0,2)}else{k=m[0]}if(i.name.length>20){fileName=i.name.substr(0,20)+"..."}else{fileName=i.name}queue="#"+a(this).attr("id")+"Queue";if(j.data.queueID){queue="#"+j.data.queueID}a(queue).append('<div id="'+a(this).attr("id")+h+'" class="uploadifyQueueItem"><div class="cancel"><a href="javascript:jQuery(\'#'+a(this).attr("id")+"').uploadifyCancel('"+h+'\')"><img src="'+settings.cancelImg+'" border="0" /></a></div><span class="fileName">'+fileName+" ("+k+l+')</span><span class="percentage"></span><div class="uploadifyProgress"><div id="'+a(this).attr("id")+h+'ProgressBar" class="uploadifyProgressBar"><!--Progress Bar--></div></div></div>')}});if(typeof(settings.onSelectOnce)=="function"){a(this).bind("uploadifySelectOnce",settings.onSelectOnce)}a(this).bind("uploadifyQueueFull",{action:settings.onQueueFull},function(h,i){if(h.data.action(h,i)!==false){alert("The queue is full.  The max size is "+i+".")}});a(this).bind("uploadifyCheckExist",{action:settings.onCheck},function(m,l,k,j,o){var i=new Object();i=k;i.folder=e+j;if(o){for(var h in k){var n=h}}a.post(l,i,function(r){for(var p in r){if(m.data.action(m,l,k,j,o)!==false){var q=confirm("Do you want to replace the file "+r[p]+"?");if(!q){document.getElementById(a(m.target).attr("id")+"Uploader").cancelFileUpload(p,true,true)}}}if(o){document.getElementById(a(m.target).attr("id")+"Uploader").startFileUpload(n,true)}else{document.getElementById(a(m.target).attr("id")+"Uploader").startFileUpload(null,true)}},"json")});a(this).bind("uploadifyCancel",{action:settings.onCancel},function(l,h,k,m,j){if(l.data.action(l,h,k,m,j)!==false){var i=(j==true)?0:250;a("#"+a(this).attr("id")+h).fadeOut(i,function(){a(this).remove()})}});if(typeof(settings.onClearQueue)=="function"){a(this).bind("uploadifyClearQueue",settings.onClearQueue)}var c=[];a(this).bind("uploadifyError",{action:settings.onError},function(l,h,k,j){if(l.data.action(l,h,k,j)!==false){var i=new Array(h,k,j);c.push(i);a("#"+a(this).attr("id")+h+" .percentage").text(" - "+j.type+" Error");a("#"+a(this).attr("id")+h).addClass("uploadifyError")}});a(this).bind("uploadifyProgress",{action:settings.onProgress,toDisplay:settings.displayData},function(j,h,i,k){if(j.data.action(j,h,i,k)!==false){a("#"+a(this).attr("id")+h+"ProgressBar").css("width",k.percentage+"%");if(j.data.toDisplay=="percentage"){displayData=" - "+k.percentage+"%"}if(j.data.toDisplay=="speed"){displayData=" - "+k.speed+"KB/s"}if(j.data.toDisplay==null){displayData=" "}a("#"+a(this).attr("id")+h+" .percentage").text(displayData)}});a(this).bind("uploadifyComplete",{action:settings.onComplete},function(k,h,j,i,l){if(k.data.action(k,h,j,unescape(i),l)!==false){a("#"+a(this).attr("id")+h+" .percentage").text(" - Completed");a("#"+a(this).attr("id")+h).fadeOut(250,function(){a(this).remove()})}});if(typeof(settings.onAllComplete)=="function"){a(this).bind("uploadifyAllComplete",{action:settings.onAllComplete},function(h,i){if(h.data.action(h,i)!==false){c=[]}})}})},uploadifySettings:function(f,j,c){var g=false;a(this).each(function(){if(f=="scriptData"&&j!=null){if(c){var i=j}else{var i=a.extend(settings.scriptData,j)}var l="";for(var k in i){l+="&"+k+"="+escape(i[k])}j=l.substr(1)}g=document.getElementById(a(this).attr("id")+"Uploader").updateSettings(f,j)});if(j==null){if(f=="scriptData"){var b=unescape(g).split("&");var e=new Object();for(var d=0;d<b.length;d++){var h=b[d].split("=");e[h[0]]=h[1]}g=e}return g}},uploadifyUpload:function(b){a(this).each(function(){document.getElementById(a(this).attr("id")+"Uploader").startFileUpload(b,false)})},uploadifyCancel:function(b){a(this).each(function(){document.getElementById(a(this).attr("id")+"Uploader").cancelFileUpload(b,true,false)})},uploadifyClearQueue:function(){a(this).each(function(){document.getElementById(a(this).attr("id")+"Uploader").clearFileUploadQueue(false)})}})})(jQuery)};

eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(5($){$.K.V=5(d){3 e={8:\'U\',v:\'M\',4:\'J\',A:\'E\',B:\'\',j:T};3 d=$.R(e,d);Q f.L(5(){2=$(f);3 s=$("n",2).I;3 w=2.k();3 h=2.D();3 b=s-1;3 t=0;3 c=(d.B==\'S\');$("i",2).z(\'k\',s*w);6(!c)$("n",2).z(\'P\',\'O\');$(2).N(\'<9 u="\'+d.8+\'"><a r=\\"m:q(0);\\">\'+d.v+\'</a></9> <9 u="\'+d.4+\'"><a r=\\"m:q(0);\\">\'+d.A+\'</a></9>\');$("a","#"+d.8).o();$("a","#"+d.4).o();$("a","#"+d.4).y(5(){7("l");6(t>=b)$(f).x();$("a","#"+d.8).g()});$("a","#"+d.8).y(5(){7("H");6(t<=0)$(f).x();$("a","#"+d.4).g()});5 7(a){6(a=="l"){t=(t>=b)?b:t+1}C{t=(t<=0)?0:t-1};6(!c){p=(t*w*-1);$("i",2).7({G:p},d.j)}C{p=(t*h*-1);$("i",2).7({F:p},d.j)}};6(s>1)$("a","#"+d.4).g()})}})(W);',59,59,'||obj|var|nextId|function|if|animate|prevId|span||||||this|fadeIn||ul|speed|width|next|javascript|li|hide||void|href|||id|prevText||fadeOut|click|css|nextText|orientation|else|height|Next|marginTop|marginLeft|prev|length|nextBtn|fn|each|Previous|after|left|float|return|extend|vertical|800|prevBtn|easySlider|jQuery'.split('|'),0,{}))

$.Autocompleter.Select = function (options, input, select, config) {
    var CLASSES = {
        ACTIVE: "auto-focus"
    };
    
    var listItems,
        active = -1,
        data,
        term = "",
        element,
        list;
    
    // Create results
    function init() {
        element = $('#'+options.result_cont+'');
        list = $('<ul>').appendTo(element).mouseover( function(event) {
            if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
                active = $("li", list).removeClass().index(target(event));
                $(target(event)).addClass(CLASSES.ACTIVE);            
            }
        }).click(function(event) {
            $(target(event)).addClass(CLASSES.ACTIVE);
            select();
            input.focus();
            return false;
        }).mousedown(function() {
            config.mouseDownOnSelect = true;
        }).mouseup(function() {
            config.mouseDownOnSelect = false;
        });
        
        
        if( options.width > 0 )
            element.css("width", options.width);
            
    } 
    
    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();
        movePosition(step);
        var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
        
    };
    
    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();
        $('.default').remove();
        var max = limitNumberOfItems(data.length);
        lista = new String(options.data);
        
        var current = new String($('#'+options.result_field).val()); //Do not allow duplicates by first getting the current list of numbers
        var results = false;
        
        var duplicates = $('#'+options.result_field).val();
        duplicates = duplicates.split(",");
        
        for (var i=0; i < max; i++) {
            //Check for duplicates - if the ID matches in any part of the data hidden field, then reject the result
            var found = false;
            var j=0;
            //for(j=0; j < duplicates.length; j++){
             //   if(duplicates[j] == data[i].data[1]){
              //      found = true;
              //      j = duplicates.length;    
              //  }
            //}

            if(found == true){
                continue;    
            }
            
            if (!data[i]){
                continue;
            }
            var formatted = new String(data[i].data[0]);
            if ( formatted === false ){
                continue;
            }
            var li = $("<li>").html( options.highlight(formatted, term) ).appendTo(list)[0];
            lista = new String(options.data);
            $.data(li, "ac_data", data[i]);
            results = true;
        
        }
        
        if(results == false){
            $('#'+options.result_cont+'').html('<div class="default">No Results Found</div>');
        }
        
        listItems = list.find("li");
        if ( options.selectFirst ) {
            listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
            active = 0;
        }
    }
    
    return {
        display: function(d, q) {
            $('#'+options.result_cont+' ul').remove();
            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();
            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();
            
        },
        selected: function() {
            return listItems && $.data(listItems.filter("." + CLASSES.ACTIVE)[0], "ac_data");
        },
        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);

function show_error_promt(text, width, delay)
{
    if(delay==undefined) delay = 3000;
    jQuery('#confirm_message').addClass('popup_error');
    jQuery('#confirm_message').css('height', width==undefined ? '25px' : width+'px' );   
    jQuery('#confirm_message').html(text);   
    jQuery('#confirm_message').show('fast');      
    setTimeout("jQuery('#confirm_message').hide('slow');   ",delay);
}

function show_promt(text, width, delay)
{
    if(delay==undefined) delay = 3000;
    jQuery('#confirm_message').removeClass('popup_error');
    jQuery('#confirm_message').css('height', width==undefined ? '25px' : width+'px' );   
    jQuery('#confirm_message').html(text);   
    jQuery('#confirm_message').show('fast');   
    setTimeout("jQuery('#confirm_message').hide('slow');   ",delay);
}

function prepare_countr()
{
    var countries = '';
    jQuery(".facelist .token").each(function(ind,obj){ countries += ','+obj.id; });
    jQuery('#country_filter').val(countries);
}

function show_hide_map(obj)
{
    if(jQuery('#not_you').css('display')=='none') 
    {
        jQuery('.block_location').show();
        obj.innerHTML='Hide map';
        jQuery.ajax({
          type: "GET",
          url: _BASE_URL+"ajax_show_hide_map.php",
          data: 'act=1',
          success: function(msg){
         }
       });
    } 
    else 
    {
        jQuery('.block_location').hide(1);
        obj.innerHTML='Show map';
        jQuery.ajax({
          type: "GET",
          url: _BASE_URL+"ajax_show_hide_map.php",
          data: 'act=0',
          success: function(msg){
         }
       });
    }
}

function add_poll_act()
{
    jQuery('.add_poll_but').removeClass('active');
    jQuery('.delete_poll_but').addClass('active');
    jQuery('.add_poll_block').addClass('active');
}

function delete_poll_act()
{    
    jQuery('#word_container').parent().html('<div id="word_container">'+jQuery('#word_container').html()+'</div>');
    
    jQuery('.add_poll_form_1').val('');
    jQuery('.add_poll_form_2').val('');
    jQuery('.add_poll_but').addClass('active');
    jQuery('.delete_poll_but').removeClass('active');
    jQuery('.add_poll_block').removeClass('active');
}

function empty_poll()
{
    jQuery('.radio_poll').each(function(ind,obj){obj.checked=false;  });
}

//v1.7
// Flash Player Version Detection
// Detect Client Browser type
// Copyright 2005-2007 Adobe Systems Incorporated.  All rights reserved.
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion()
{
    var version;
    var axo;
    var e;

    // NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

    try {
        // version will be set for 7.X or greater players
        axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
        version = axo.GetVariable("$version");
    } catch (e) {
    }

    if (!version)
    {
        try {
            // version will be set for 6.X players only
            axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
            
            // installed player is some revision of 6.0
            // GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
            // so we have to be careful. 
            
            // default to the first public version
            version = "WIN 6,0,21,0";

            // throws if AllowScripAccess does not exist (introduced in 6.0r47)        
            axo.AllowScriptAccess = "always";

            // safe to call for 6.0r47 or greater
            version = axo.GetVariable("$version");

        } catch (e) {
        }
    }

    if (!version)
    {
        try {
            // version will be set for 4.X or 5.X player
            axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
            version = axo.GetVariable("$version");
        } catch (e) {
        }
    }

    if (!version)
    {
        try {
            // version will be set for 3.X player
            axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
            version = "WIN 3,0,18,0";
        } catch (e) {
        }
    }

    if (!version)
    {
        try {
            // version will be set for 2.X player
            axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
            version = "WIN 2,0,0,11";
        } catch (e) {
            version = -1;
        }
    }
    
    return version;
}

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
    // NS/Opera version >= 3 check for Flash plugin in plugin array
    var flashVer = -1;
    
    if (navigator.plugins != null && navigator.plugins.length > 0) {
        if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
            var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
            var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
            var descArray = flashDescription.split(" ");
            var tempArrayMajor = descArray[2].split(".");            
            var versionMajor = tempArrayMajor[0];
            var versionMinor = tempArrayMajor[1];
            var versionRevision = descArray[3];
            if (versionRevision == "") {
                versionRevision = descArray[4];
            }
            if (versionRevision[0] == "d") {
                versionRevision = versionRevision.substring(1);
            } else if (versionRevision[0] == "r") {
                versionRevision = versionRevision.substring(1);
                if (versionRevision.indexOf("d") > 0) {
                    versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
                }
            }
            var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
        }
    }
    // MSN/WebTV 2.6 supports Flash 4
    else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
    // WebTV 2.5 supports Flash 3
    else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
    // older WebTV supports Flash 2
    else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
    else if ( isIE && isWin && !isOpera ) {
        flashVer = ControlVersion();
    }    
    return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
    versionStr = GetSwfVer();
    if (versionStr == -1 ) {
        return false;
    } else if (versionStr != 0) {
        if(isIE && isWin && !isOpera) {
            // Given "WIN 2,0,0,11"
            tempArray         = versionStr.split(" ");     // ["WIN", "2,0,0,11"]
            tempString        = tempArray[1];            // "2,0,0,11"
            versionArray      = tempString.split(",");    // ['2', '0', '0', '11']
        } else {
            versionArray      = versionStr.split(".");
        }
        var versionMajor      = versionArray[0];
        var versionMinor      = versionArray[1];
        var versionRevision   = versionArray[2];

            // is the major.revision >= requested major.revision AND the minor version >= requested minor
        if (versionMajor > parseFloat(reqMajorVer)) {
            return true;
        } else if (versionMajor == parseFloat(reqMajorVer)) {
            if (versionMinor > parseFloat(reqMinorVer))
                return true;
            else if (versionMinor == parseFloat(reqMinorVer)) {
                if (versionRevision >= parseFloat(reqRevision))
                    return true;
            }
        }
        return false;
    }
}

function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?'); 
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs) 
{ 
  var str = '';
  if (isIE && isWin && !isOpera)
  {
    str += '<object ';
    for (var i in objAttrs)
    {
      str += i + '="' + objAttrs[i] + '" ';
    }
    str += '>';
    for (var i in params)
    {
      str += '<param name="' + i + '" value="' + params[i] + '" /> ';
    }
    str += '</object>';
  }
  else
  {
    str += '<embed ';
    for (var i in embedAttrs)
    {
      str += i + '="' + embedAttrs[i] + '" ';
    }
    str += '> </embed>';
  }

  document.write(str);
}

function AC_FL_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    

    switch (currArg){    
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":    
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblclick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
      case "id":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}

var gallery_page = 1;
function profile_gallery(page)
{
    if(page>0 && ((page<4 && document.getElementById('gallery3')) || (page<3 && !document.getElementById('gallery3')))) 
        gallery_page = page;
    if(gallery_page==1)
    {
        jQuery('#prof_gal_page1').addClass('active');
        jQuery('#prof_gal_page2').removeClass('active');
        jQuery('#prof_gal_page3').removeClass('active');
        jQuery('#gallery1').show();
        jQuery('#gallery2').hide();
        jQuery('#gallery3').hide();
    }
    if(gallery_page==2)
    {
        jQuery('#prof_gal_page1').removeClass('active');
        jQuery('#prof_gal_page3').removeClass('active');
        jQuery('#prof_gal_page2').addClass('active');
        jQuery('#gallery1').hide();
        jQuery('#gallery3').hide();
        jQuery('#gallery2').show();
    }
    if(gallery_page==3)
    {
        jQuery('#prof_gal_page1').removeClass('active');
        jQuery('#prof_gal_page2').removeClass('active');
        jQuery('#prof_gal_page3').addClass('active');
        jQuery('#gallery1').hide();
        jQuery('#gallery2').hide();
        jQuery('#gallery3').show();
    }
}

// Simple Set Clipboard System
// Author: Joseph Huckaby

var ZeroClipboard = {
    
    version: "1.0.7",
    clients: {}, // registered upload clients on page, indexed by id
    moviePath: 'http://www.buzzmart.com/ZeroClipboard.swf', // URL to movie
    nextId: 1, // ID of next movie
    
    $: function(thingy) {
        // simple DOM lookup utility function
        if (typeof(thingy) == 'string') thingy = document.getElementById(thingy);
        if (!thingy.addClass) {
            // extend element with a few useful methods
            thingy.hide = function() { this.style.display = 'none'; };
            thingy.show = function() { this.style.display = ''; };
            thingy.addClass = function(name) { this.removeClass(name); this.className += ' ' + name; };
            thingy.removeClass = function(name) {
                var classes = this.className.split(/\s+/);
                var idx = -1;
                for (var k = 0; k < classes.length; k++) {
                    if (classes[k] == name) { idx = k; k = classes.length; }
                }
                if (idx > -1) {
                    classes.splice( idx, 1 );
                    this.className = classes.join(' ');
                }
                return this;
            };
            thingy.hasClass = function(name) {
                return !!this.className.match( new RegExp("\\s*" + name + "\\s*") );
            };
        }
        return thingy;
    },
    
    setMoviePath: function(path) {
        // set path to ZeroClipboard.swf
        this.moviePath = path;
    },
    
    dispatch: function(id, eventName, args) {
        // receive event from flash movie, send to client        
        var client = this.clients[id];
        if (client) {
            client.receiveEvent(eventName, args);
        }
    },
    
    register: function(id, client) {
        // register new client to receive events
        this.clients[id] = client;
    },
    
    getDOMObjectPosition: function(obj, stopObj) {
        // get absolute coordinates for dom element
        var info = {
            left: 0, 
            top: 0, 
            width: obj.width ? obj.width : obj.offsetWidth, 
            height: obj.height ? obj.height : obj.offsetHeight
        };

        while (obj && (obj != stopObj)) {
            info.left += obj.offsetLeft;
            info.top += obj.offsetTop;
            obj = obj.offsetParent;
        }

        return info;
    },
    
    Client: function(elem) {
        // constructor for new simple upload client
        this.handlers = {};
        
        // unique ID
        this.id = ZeroClipboard.nextId++;
        this.movieId = 'ZeroClipboardMovie_' + this.id;
        
        // register client with singleton to receive flash events
        ZeroClipboard.register(this.id, this);
        
        // create movie
        if (elem) this.glue(elem);
    }
};

ZeroClipboard.Client.prototype = {
    
    id: 0, // unique ID for us
    ready: false, // whether movie is ready to receive events or not
    movie: null, // reference to movie object
    clipText: '', // text to copy to clipboard
    handCursorEnabled: true, // whether to show hand cursor, or default pointer cursor
    cssEffects: true, // enable CSS mouse effects on dom container
    handlers: null, // user event handlers
    
    glue: function(elem, appendElem, stylesToAdd) {
        // glue to DOM element
        // elem can be ID or actual DOM element object
        this.domElement = ZeroClipboard.$(elem);
        
        // float just above object, or zIndex 99 if dom element isn't set
        var zIndex = 99;
        if (this.domElement.style.zIndex) {
            zIndex = parseInt(this.domElement.style.zIndex, 10) + 1;
        }
        
        if (typeof(appendElem) == 'string') {
            appendElem = ZeroClipboard.$(appendElem);
        }
        else if (typeof(appendElem) == 'undefined') {
            appendElem = document.getElementsByTagName('body')[0];
        }
        
        // find X/Y position of domElement
        var box = ZeroClipboard.getDOMObjectPosition(this.domElement, appendElem);
        
        // create floating DIV above element
        this.div = document.createElement('div');
        var style = this.div.style;
        style.position = 'absolute';
        style.left = '' + box.left + 'px';
        style.top = '' + box.top + 'px';
        style.width = '' + box.width + 'px';
        style.height = '' + box.height + 'px';
        style.zIndex = zIndex;
        
        if (typeof(stylesToAdd) == 'object') {
            for (addedStyle in stylesToAdd) {
                style[addedStyle] = stylesToAdd[addedStyle];
            }
        }
        
        // style.backgroundColor = '#f00'; // debug
        
        appendElem.appendChild(this.div);
        
        this.div.innerHTML = this.getHTML( box.width, box.height );
    },
    
    getHTML: function(width, height) {
        // return HTML for movie
        var html = '';
        var flashvars = 'id=' + this.id + 
            '&width=' + width + 
            '&height=' + height;
            
        if (navigator.userAgent.match(/MSIE/)) {
            // IE gets an OBJECT tag
            var protocol = location.href.match(/^https/i) ? 'https://' : 'http://';
            html += '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="'+protocol+'download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="'+width+'" height="'+height+'" id="'+this.movieId+'" align="middle"><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" /><param name="movie" value="'+ZeroClipboard.moviePath+'" /><param name="loop" value="false" /><param name="menu" value="false" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><param name="flashvars" value="'+flashvars+'"/><param name="wmode" value="transparent"/></object>';
        }
        else {
            // all other browsers get an EMBED tag
            html += '<embed id="'+this.movieId+'" src="'+ZeroClipboard.moviePath+'" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="'+width+'" height="'+height+'" name="'+this.movieId+'" align="middle" allowScriptAccess="always" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="'+flashvars+'" wmode="transparent" />';
        }
        return html;
    },
    
    hide: function() {
        // temporarily hide floater offscreen
        if (this.div) {
            this.div.style.left = '-2000px';
        }
    },
    
    show: function() {
        // show ourselves after a call to hide()
        this.reposition();
    },
    
    destroy: function() {
        // destroy control and floater
        if (this.domElement && this.div) {
            this.hide();
            this.div.innerHTML = '';
            
            var body = document.getElementsByTagName('body')[0];
            try { body.removeChild( this.div ); } catch(e) {;}
            
            this.domElement = null;
            this.div = null;
        }
    },
    
    reposition: function(elem) {
        // reposition our floating div, optionally to new container
        // warning: container CANNOT change size, only position
        if (elem) {
            this.domElement = ZeroClipboard.$(elem);
            if (!this.domElement) this.hide();
        }
        
        if (this.domElement && this.div) {
            var box = ZeroClipboard.getDOMObjectPosition(this.domElement);
            var style = this.div.style;
            style.left = '' + box.left + 'px';
            style.top = '' + box.top + 'px';
        }
    },
    
    setText: function(newText) {
        // set text to be copied to clipboard
        this.clipText = newText;
        if (this.ready) this.movie.setText(newText);
    },
    
    addEventListener: function(eventName, func) {
        // add user event listener for event
        // event types: load, queueStart, fileStart, fileComplete, queueComplete, progress, error, cancel
        eventName = eventName.toString().toLowerCase().replace(/^on/, '');
        if (!this.handlers[eventName]) this.handlers[eventName] = [];
        this.handlers[eventName].push(func);
    },
    
    setHandCursor: function(enabled) {
        // enable hand cursor (true), or default arrow cursor (false)
        this.handCursorEnabled = enabled;
        if (this.ready) this.movie.setHandCursor(enabled);
    },
    
    setCSSEffects: function(enabled) {
        // enable or disable CSS effects on DOM container
        this.cssEffects = !!enabled;
    },
    
    receiveEvent: function(eventName, args) {
        // receive event from flash
        eventName = eventName.toString().toLowerCase().replace(/^on/, '');
                
        // special behavior for certain events
        switch (eventName) {
            case 'load':
                // movie claims it is ready, but in IE this isn't always the case...
                // bug fix: Cannot extend EMBED DOM elements in Firefox, must use traditional function
                this.movie = document.getElementById(this.movieId);
                if (!this.movie) {
                    var self = this;
                    setTimeout( function() { self.receiveEvent('load', null); }, 1 );
                    return;
                }
                
                // firefox on pc needs a "kick" in order to set these in certain cases
                if (!this.ready && navigator.userAgent.match(/Firefox/) && navigator.userAgent.match(/Windows/)) {
                    var self = this;
                    setTimeout( function() { self.receiveEvent('load', null); }, 100 );
                    this.ready = true;
                    return;
                }
                
                this.ready = true;
                this.movie.setText( this.clipText );
                this.movie.setHandCursor( this.handCursorEnabled );
                break;
            
            case 'mouseover':
                if (this.domElement && this.cssEffects) {
                    this.domElement.addClass('hover');
                    if (this.recoverActive) this.domElement.addClass('active');
                }
                break;
            
            case 'mouseout':
                if (this.domElement && this.cssEffects) {
                    this.recoverActive = false;
                    if (this.domElement.hasClass('active')) {
                        this.domElement.removeClass('active');
                        this.recoverActive = true;
                    }
                    this.domElement.removeClass('hover');
                }
                break;
            
            case 'mousedown':
                if (this.domElement && this.cssEffects) {
                    this.domElement.addClass('active');
                }
                break;
            
            case 'mouseup':
                if (this.domElement && this.cssEffects) {
                    this.domElement.removeClass('active');
                    this.recoverActive = false;
                }
                break;
        } // switch eventName
        
        if (this.handlers[eventName]) {
            for (var idx = 0, len = this.handlers[eventName].length; idx < len; idx++) {
                var func = this.handlers[eventName][idx];
            
                if (typeof(func) == 'function') {
                    // actual function reference
                    func(this, args);
                }
                else if ((typeof(func) == 'object') && (func.length == 2)) {
                    // PHP style object + method, i.e. [myObject, 'myMethod']
                    func[0][ func[1] ](this, args);
                }
                else if (typeof(func) == 'string') {
                    // name of function
                    window[func](this, args);
                }
            } // foreach event handler defined
        } // user defined handler for event
    }
    
};


function change_pref_net_checkboxes(status)
{
    jQuery('#net_checkboxes input').each(function(ind,obj){obj.checked=status;  });
}

var next_index_buzz=9;
function add_index_buzz()
{ 
    if(next_index_buzz==0)return false;
    jQuery.ajax({type:"GET",url:"/ajax_get_home_buzz.php",data:'next_index_buzz='+next_index_buzz,dataType:"html",success:function(msg)
    {
        if(msg!=''&&next_index_buzz>0)
        {
            jQuery('#new_buzz_container').html('<div id="new_buzz'+next_index_buzz+'" style="display:none">'+msg+'</div>'+jQuery('#new_buzz_container').html());
            if('\v'!='v') jQuery('#new_buzz'+next_index_buzz).css({opacity:0, background:'#fff'});
            jQuery('#new_buzz'+next_index_buzz).show('low');
            if('\v'!='v') jQuery('#new_buzz'+next_index_buzz).animate({opacity:1},1000,function(){});
            setTimeout("remove_last_home_buzzes()",1000);
            next_index_buzz++;
            if(next_index_buzz>max_home_buzz)next_index_buzz=1;
            last_buzz_timer = setTimeout('add_index_buzz()',6000);
        }
    }});
}

function remove_last_home_buzzes()
{
    if(!document.getElementById('net_home_buzz')) return false;
    var container_bottom = jQuery('.net_home_buzz').position().top + jQuery('.net_home_buzz').height();
    jQuery('.net_comment').each(function (id, obj){
        var bottom_pos = jQuery(obj).position().top + jQuery(obj).height();
        if(bottom_pos-container_bottom>0) 
        {
            jQuery(obj).animate({opacity:0},300,function(){});
            setTimeout(function(){jQuery(obj).remove()},300);
        }
    });
}

var listind_id_for_buzz = 0;
function find_buzz_listing()
{
     jQuery('#listing_found').html('Wait...');
    validate_reg(document.getElementById('buzz_listing_id'),'0-9');
    jQuery.ajax({type:"GET",url:"/ajax_get_buzz_listing.php",data:'id='+jQuery('#buzz_listing_id').val(),dataType:"html",success:function(msg)
    {
        if(msg=='')
        {
            jQuery('#listing_found').html('None');
            listind_id_for_buzz = 0;
            jQuery('#listing_attach_but').hide();
        }
        else
        {
            jQuery('#listing_found').html(msg);
            listind_id_for_buzz = jQuery('#buzz_listing_id').val();
            jQuery('#listing_attach_but').show();
        }
    }});
}

function submit_buzz_listing(reply)
{
    var text = jQuery('#listing_found').html();
    if(listind_id_for_buzz>0 && text!='' && text!='None')
    {
        disablePopup();
        //jQuery('#buzz_text').val(jQuery('#buzz_text').val() + '[id-'+listind_id_for_buzz+']'+text+'[/id]');
        var editor = eval('CKEDITOR.instances.' + (reply==''?'buzz_text':'reply_text'+reply));
        editor.setData(str_replace("</p>","",str_replace("<p>","",editor.getData())) + '<a href="/product/'+listind_id_for_buzz+'">'+text+'</a> &nbsp;&nbsp;');
        set_editor_counter((reply==''?'buzz_text':'reply_text'+reply));
    }
}

function show_buzz()
{
    //jQuery('#buzz_text').val('');
    if(typeof CKEDITOR != 'undefined') CKEDITOR.instances.buzz_text.setData('');
    jQuery('#buzz_text_length').html(200);
    jQuery('#buzz_type').val('1');
    jQuery('#buzz_header').html('Share the buzz');
    jQuery('#buzz_listing').hide();
    jQuery('#promote_it').hide();
    jQuery('#buzz_link_cont').addClass('active');
    jQuery('#request_link_cont').removeClass('active');
    jQuery('#promote_link_cont').removeClass('active');
    jQuery('#new_buzzs').html('');
    jQuery('#price_range').hide();
    profile_show_content('type=1','buzz_list', 'network_cont');
    update_buzz_corners();
}

function show_request()
{
    //jQuery('#buzz_text').val('');
    if(typeof CKEDITOR != 'undefined') CKEDITOR.instances.buzz_text.setData('<span style="color:#aaa;">I\'m looking for</span>&nbsp;');
    jQuery('#buzz_text_length').html(200);
    jQuery('#buzz_type').val('2');
    jQuery('#buzz_header').html('');
    jQuery('#buzz_listing').hide();
    jQuery('#promote_it').hide();
    jQuery('#buzz_link_cont').removeClass('active');
    jQuery('#request_link_cont').addClass('active');
    jQuery('#promote_link_cont').removeClass('active');
    jQuery('#new_buzzs').html('');
    jQuery('#price_range').show();
    profile_show_content('type=2','buzz_list', 'network_cont');
    update_buzz_corners();
}

function show_promote()
{
    //jQuery('#buzz_text').val('');
    if(typeof CKEDITOR != 'undefined') CKEDITOR.instances.buzz_text.setData('<span style="color:#aaa;">Check out my listing</span>&nbsp;');
    jQuery('#buzz_text_length').html(200);
    jQuery('#buzz_type').val('3');
    jQuery('#buzz_header').html('');
    jQuery('#buzz_listing').hide();
    jQuery('#promote_it').show();
    jQuery('#buzz_link_cont').removeClass('active');
    jQuery('#request_link_cont').removeClass('active');
    jQuery('#promote_link_cont').addClass('active');
    jQuery('#new_buzzs').html('');
    jQuery('#price_range').hide();
    profile_show_content('type=3','buzz_list', 'network_cont');
    update_buzz_corners();
}

function buzz_it()
{
    jQuery('#buzz_error').html('');
    var text = CKEDITOR.instances.buzz_text.getData();
    text = str_replace('&','<AMP>',text);
    text = str_replace('#','<SHARP>',text);
    jQuery.ajax({type:"GET",url:"/ajax_add_buzz.php",data:'type='+jQuery('#buzz_type').val()+'&price_range_from='+jQuery('#price_range_from').val()+'&price_range_to='+jQuery('#price_range_to').val()+'&text='+text.substr(0,1500),dataType:"html",success:function(msg)
    {
        if(msg=='error') 
        {
            jQuery('#buzz_error').html('<b>Only 1 buzz every 30 seconds is allowed.</b>');
            setTimeout(function (){jQuery('#buzz_error').html('')},3000);
            return;
        }
        if(msg=='t_error') 
        {
            jQuery('#buzz_error').html('<b>Enter text.</b>');
            setTimeout(function (){jQuery('#buzz_error').html('')},3000);
            return;
        }
        CKEDITOR.instances.buzz_text.setData( jQuery('#buzz_type').val()==2 ? 'I\'m looking for&nbsp;' : '' );
        jQuery('#buzz_text_length').html(400);
        jQuery('#price_range_from').val('');
        jQuery('#price_range_to').val('');
        var temp_index = Math.round(new Date().getTime() / 1000);
        jQuery('#network_cont').html('<div id="new_buzz'+temp_index+'" style="display:none">'+msg+'</div>'+jQuery('#network_cont').html());
        jQuery('#new_buzz'+temp_index).css({opacity:0});
        jQuery('#new_buzz'+temp_index).show('low');
        jQuery('#new_buzz'+temp_index).animate({opacity:1},1000,function(){});
        update_buzz_corners();
    }});
}

function buzz_it_small()
{
    jQuery('#buzz_error').html('');
    var text = CKEDITOR.instances.buzz_text.getData();
    text = str_replace('&','<AMP>',text);
    text = str_replace('#','<SHARP>',text);
    jQuery.ajax({type:"GET",url:"/ajax_add_buzz.php",data:'type=1&text='+text.substr(0,1500),dataType:"html",success:function(msg)
    {
        if(msg=='error') 
        {
            jQuery('#buzz_error').html('<b>Only 1 buzz every 30 seconds is allowed.</b>');
            setTimeout(function (){jQuery('#buzz_error').html('')},3000);
            return;
        }
        if(msg=='t_error') 
        {
            jQuery('#buzz_error').html('<b>Enter text.</b>');
            setTimeout(function (){jQuery('#buzz_error').html('')},3000);
            return;
        }
        CKEDITOR.instances.buzz_text.setData( '' );
        jQuery('#buzz_text_length').html(400);
        var temp_index = Math.round(new Date().getTime() / 1000);
        jQuery('#buzzs').html('<div id="new_buzz'+temp_index+'" style="display:none">'+msg+'</div>'+jQuery('#buzzs').html());
        jQuery('#new_buzz'+temp_index).css({opacity:0});
        jQuery('#new_buzz'+temp_index).show('low');
        jQuery('#new_buzz'+temp_index).animate({opacity:1},1000,function(){});
    }});
}

function promote_buzz(url, text)
{
    disablePopup();
    CKEDITOR.instances.buzz_text.setData(str_replace("</p>","",str_replace("<p>","",CKEDITOR.instances.buzz_text.getData())) + '<a href="/product/'+url+'">'+text+'</a> &nbsp;&nbsp;&nbsp;');
    set_editor_counter('buzz_text');
}

var last_check = '';
function promote_check()
{
    jQuery('#promote_title').html('Wait...');
    var url = jQuery('#promote_url').val();
    if(url=='') 
    {
        jQuery('#promote_title').html('');
        jQuery('#attach_but').hide();
        return false;
    }
    jQuery.ajax({type:"GET",url:"/ajax_check_buzz_url.php",data:'url='+url,dataType:"html",success:function(msg)
    {
        if(msg=='')
        {
            jQuery('#promote_title').html('Page not found');
            jQuery('#attach_but').hide();
            return false;
        }
        else if(msg=='error')
        {
            jQuery('#promote_title').html('Incorrect URL');
            jQuery('#attach_but').hide();
            return false;
        }
        else
        {
            last_check = url;
            jQuery('#promote_title').html(msg);
            jQuery('#attach_but').show();
            return true;
        }
    }});
}

var last_ebay_check = '';
function ebay_check()
{
    jQuery('#ebay_title').html('Wait...');
    var url = jQuery('#ebay_num').val();
    if(url=='') 
    {
        jQuery('#ebay_title').html('');
        jQuery('#ebay_but').hide();
        return false;
    }
    jQuery.ajax({type:"GET",url:"/ajax_check_ebay_url.php",data:'url='+url,dataType:"html",success:function(msg)
    {
        if(msg=='')
        {
            jQuery('#ebay_title').html('Listing not found');
            jQuery('#ebay_but').hide();
            return false;
        }
        else if(msg=='error')
        {
            jQuery('#ebay_title').html('Incorrect URL or Item Number');
            jQuery('#ebay_but').hide();
            return false;
        }
        else
        {
            last_ebay_check = url;
            jQuery('#ebay_title').html(msg);
            jQuery('#ebay_but').show();
            return true;
        }
    }});
}

function ebay_import()
{
    var text = jQuery('#ebay_title').html();
    var url = jQuery('#ebay_num').val();
    if(last_ebay_check != url && !ebay_check())  return false;
    if(url!='' && text!='' && text!='Listing not found')
    {
        disablePopup();
        jQuery.ajax({
              type: "GET",
              url: _BASE_URL+"ajax_ebay_step1.php",
              data: "url="+url,
              success: function(msg){
              eval(msg);
             }
        });
        jQuery.ajax({
              type: "GET",
              url: _BASE_URL+"ajax_ebay_step1_desc.php",
              data: "url="+url,
              success: function(msg){
              CKEDITOR.instances.ckeditor.setData(msg);
             }
        });
        jQuery.ajax({
              type: "GET",
              url: _BASE_URL+"ajax_ebay_steps234.php",
              data: "url="+url,
              success: function(msg){
              jQuery('#recycle_content').html(msg);
              change_quantity();
              change_additional_ship();
              init_image_zoom();
              init_video_upload(51200);
             }
        });
    }
}

function promote_attach()
{
    var text = jQuery('#promote_title').html();
    var url = jQuery('#promote_url').val();
    if(last_check != url && !promote_check())  return false;
    if(url!='' && text!='' && text!='Page not found')
    {
        jQuery('#promote_title').html('');
        jQuery('#promote_url').val('');
        jQuery('#attach_but').hide();
        CKEDITOR.instances.buzz_text.setData(str_replace("</p>","",str_replace("<p>","",CKEDITOR.instances.buzz_text.getData())) + '<a href="'+url+'">'+text+'</a> &nbsp;&nbsp;');
        set_editor_counter('buzz_text');
    }
}

function buzz_reply(id)
{
    jQuery('#net_comment_form'+id).show();
    init_buzzreply_ckeditor(id);
}

function reply_it(reply_id)
{
    var text = eval('CKEDITOR.instances.reply_text'+reply_id+'.getData()');
    text = str_replace('&','<AMP>',text);
    text = str_replace('#','<SHARP>',text);
    jQuery.ajax({type:"GET",url:"/ajax_add_buzz_reply.php",data:'id='+reply_id+'&offer='+jQuery('#reply_quote'+reply_id).val()+'&text='+text.substr(0,1500),dataType:"html",success:function(msg)
    {
        if(msg!='error')
        {
            eval('CKEDITOR.instances.reply_text'+reply_id+'.setData("")');
            jQuery('#reply_quote'+reply_id).val('');
            jQuery('#reply_text'+reply_id+'_length').html(400);
            jQuery('#net_comment_form'+reply_id).hide();
            show_promt('Your reply has been posted.');
            jQuery('#buzz_item'+reply_id+' .replies_counter').html(jQuery('#buzz_item'+reply_id+' .replies_counter').html()/1 + 1);
        }
        else
        {
            jQuery('#buzz_error'+reply_id).html('<b>Only 1 reply every 30 seconds is allowed.</b>');
            setTimeout(function (){jQuery('#buzz_error'+reply_id).html('')},3000);
        }
    }});
}

function check_new_buzzs()
{
    jQuery.ajax({type:"GET",url:"/ajax_check_new_buzzs.php",data:'type='+jQuery('#buzz_type').val()+'&most_recent_buzz='+jQuery('#most_recent_buzz').val()+'&keyword='+jQuery('#buzz_search').val(),dataType:"html",success:function(msg)
    {
        jQuery('#new_buzzs').html(msg);
    }});
    setTimeout("check_new_buzzs()", 20000);
}

function update_network_list(text, type, no_update)
{
    if(type==1)  
    { 
        if((document.getElementById('filter_link_locations') && text=='') || (!document.getElementById('filter_link_locations') && text!=''))
        {
            window.location='/network';
            return true;
        }
        jQuery('#filter_link_locations').html(text); 
        jQuery('#filter_link_locations2').html(text); 
    }
    if(type==2)  jQuery('#filter_link_types').html(text);
    if(type==3)  jQuery('#filter_link_users').html(text);
    jQuery('#new_buzzs').html('');
    if(typeof no_update == 'undefined')
    {
        profile_show_content('type='+jQuery('#buzz_type').val(),'buzz_list', 'network_cont');
        update_buzz_corners();
    }
}

function remove_buzz_comment(id)
{
    jQuery('#rep'+id).remove();
    jQuery.ajax({type:"GET",url:"/buzz_replies.php",data:'delete='+id,dataType:"html",success:function(msg){}});
}

function save_option(option, value)
{
    jQuery.ajax({type:"GET",url:"/ajax_save_option.php",data:'option='+option+'&value='+value,dataType:"html",success:function(msg){}});
}

function buzz_listing(nid, pid)
{
    jQuery.ajax({type:"GET",url:"/ajax_buzz_listing.php",data:'nid='+nid+'&pid='+pid,dataType:"html",success:function(msg){eval(msg);}});
}

function delete_buzz(id)
{
    jQuery('#buzz_item'+id).remove();
    jQuery.ajax({type:"GET",url:"/ajax_delete_buzz.php",data:'id='+id,dataType:"html",success:function(msg){}});
    update_buzz_corners();
}

function set_editor_counter(editor, max)
{
     if(max == undefined) var max = 200;
     var obj = eval("CKEDITOR.instances."+editor);
     var data = obj.getData();
     var text = strip_tags(data);
     text = str_replace('&nbsp;',' ',text);
     if(text.length > max)  
     {
         obj.setData(obj.getData().substr(0,max+(data.length-text.length)));
         jQuery('#'+editor+'_length').html('0');
     }
     else
        jQuery('#'+editor+'_length').html(max-text.length);
}

//// fancy popups
/*
 * FancyBox - simple jQuery plugin for fancy image zooming
 * Examples and documentation at: http://fancy.klade.lv/
 * Version: 1.0.0 (29/04/2008)
 * Copyright (c) 2008 Janis Skarnelis
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
 * Requires: jQuery v1.2.1 or later
*/
(function($) {
    var opts = {}, 
        imgPreloader = new Image, imgTypes = ['png', 'jpg', 'jpeg', 'gif'], 
        loadingTimer, loadingFrame = 1;

   $.fn.fancybox = function(settings) {
        opts.settings = $.extend({}, $.fn.fancybox.defaults, settings);

        $.fn.fancybox.init();

        var $this = $(this);
        var o = $.metadata ? $.extend({}, opts.settings, $this.metadata()) : opts.settings;
        $.fn.fancybox.start(this, o);
    };

    $.fn.fancybox.start = function(el, o) {
        if (opts.animating) return false;

        if (o.overlayShow) {
            $("#fancy_wrap").prepend('<div id="fancy_overlay"></div>');
            $("#fancy_overlay").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': o.overlayOpacity});

            if ($.browser.msie) {
                $("#fancy_wrap").prepend('<iframe id="fancy_bigIframe" scrolling="no" frameborder="0"></iframe>');
                $("#fancy_bigIframe").css({'width': $(window).width(), 'height': $(document).height(), 'opacity': 0});
            }

            $("#fancy_overlay").click($.fn.fancybox.close);
        }

        opts.itemArray    = [];
        opts.itemNum    = 0;

        if (jQuery.isFunction(o.itemLoadCallback)) {
           o.itemLoadCallback.apply(this, [opts]);

            var c    = $(el).children("img:first").length ? $(el).children("img:first") : $(el);
            var tmp    = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)}

           for (var i = 0; i < opts.itemArray.length; i++) {
                opts.itemArray[i].o = $.extend({}, o, opts.itemArray[i].o);
                
                if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) {
                    opts.itemArray[i].orig = tmp;
                }
           }

        } else {
            if (!el.rel || el.rel == '') {
                var item = {url: el.href, title: el.title, o: o};

                if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) {
                    var c = $(el).children("img:first").length ? $(el).children("img:first") : $(el);
                    item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)}
                }

                opts.itemArray.push(item);

            } else {
                var arr    = $("a[@rel=" + el.rel + "]").get();

                for (var i = 0; i < arr.length; i++) {
                    var tmp        = $.metadata ? $.extend({}, o, $(arr[i]).metadata()) : o;
                       var item    = {url: arr[i].href, title: arr[i].title, o: tmp};

                       if (o.zoomSpeedIn > 0 || o.zoomSpeedOut > 0) {
                        var c = $(arr[i]).children("img:first").length ? $(arr[i]).children("img:first") : $(el);

                        item.orig = {'width': c.width(), 'height': c.height(), 'pos': $.fn.fancybox.getPosition(c)}
                    }

                    if (arr[i].href == el.href) opts.itemNum = i;

                    opts.itemArray.push(item);
                }
            }
        }

        $.fn.fancybox.changeItem(opts.itemNum);
    };

    $.fn.fancybox.changeItem = function(n) {
        $.fn.fancybox.showLoading();

        opts.itemNum = n;

        $("#fancy_nav").empty();
        $("#fancy_outer").stop();
        $("#fancy_title").hide();
        $(document).unbind("keydown");

        imgRegExp = imgTypes.join('|');
        imgRegExp = new RegExp('\.' + imgRegExp + '$', 'i');

        $.fn.fancybox.showItem('<div id="fancy_div">' + opts.settings.content + '</div>');
        $("#fancy_loading").hide();
        
    };

    $.fn.fancybox.showIframe = function() {
        $("#fancy_loading").hide();
        $("#fancy_frame").show();
    };

    $.fn.fancybox.showItem = function(val) {
        $.fn.fancybox.preloadNeighborImages();

        var viewportPos    = $.fn.fancybox.getViewport();
        var itemSize    = $.fn.fancybox.getMaxSize(viewportPos[0] - 50, viewportPos[1] - 100, opts.itemArray[opts.itemNum].o.frameWidth, opts.itemArray[opts.itemNum].o.frameHeight);

        var itemLeft    = viewportPos[2] + Math.round((viewportPos[0] - opts.settings.width) / 2) - 20;
        var itemTop        = viewportPos[3] + Math.round((viewportPos[1] - opts.settings.height) / 2) - 40;
        
        var mytop = itemTop;
        if(strpos(val, 'no_search_prompt_checkbox')>0) mytop = jQuery('#filter_shipping_link').position().top;
        if(strpos(val, 'no_sell_prompt_checkbox')>0) mytop = jQuery('#ckeditor').position().top + 80;
        
        var myleft = itemLeft;
        if(document.getElementById('filter_categ_link')) myleft += 130;
        if(strpos(val, '<div class="s_u_b_title">Edit listing</div>')>0) myleft = myleft - 130;
        if(strpos(val, 'no_sell_prompt_checkbox')>0) myleft += 65;
        if(mytop < 0) mytop = 10;
        var itemOpts = {
            'left':        myleft, 
            'top':         mytop, 
            'width':     opts.settings.width + 'px', 
            'height':    opts.settings.height + 'px'    
        }

        if (opts.active) {
            $('#fancy_content').fadeOut("normal", function() {
                $("#fancy_content").empty();
                
                $("#fancy_outer").animate(itemOpts, "normal", function() {
                    $("#fancy_content").append($(val)).fadeIn("normal");
                    $.fn.fancybox.updateDetails();
                    jQuery('#fancy_div').css({'height':jQuery('#fancy_outer').height()-20});
                });
            });

        } else {
            opts.active = true;

            $("#fancy_content").empty();

            if ($("#fancy_content").is(":animated")) {
                console.info('animated!');
            }

            if (opts.itemArray[opts.itemNum].o.zoomSpeedIn > 0) {
                opts.animating        = true;
                itemOpts.opacity    = "show";

                $("#fancy_outer").css({
                    'top':        opts.itemArray[opts.itemNum].orig.pos.top - 18,
                    'left':        opts.itemArray[opts.itemNum].orig.pos.left - 18,
                    'height':    opts.itemArray[opts.itemNum].orig.height,
                    'width':    opts.itemArray[opts.itemNum].orig.width
                });

                $("#fancy_content").append($(val)).show();

                $("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedIn, function() {
                    opts.animating = false;
                    $.fn.fancybox.updateDetails();
                    jQuery('#fancy_div').css({'height':jQuery('#fancy_outer').height()-20});
                });

            } else {
                $("#fancy_content").append($(val)).show();
                $("#fancy_outer").css(itemOpts).show();
                $.fn.fancybox.updateDetails();
            }
         }
    };

    $.fn.fancybox.updateDetails = function() {
        $("#fancy_bg,#fancy_close").show();

        if (opts.itemArray[opts.itemNum].title !== undefined && opts.itemArray[opts.itemNum].title !== '') {
            $('#fancy_title div').html(opts.itemArray[opts.itemNum].title);
            $('#fancy_title').show();
        }

        if (opts.itemArray[opts.itemNum].o.hideOnContentClick) {
            $("#fancy_content").click($.fn.fancybox.close);
        } else {
            $("#fancy_content").unbind('click');
        }

        if (opts.itemNum != 0) {
            $("#fancy_nav").append('<a id="fancy_left" href="javascript:;"></a>');

            $('#fancy_left').click(function() {
                $.fn.fancybox.changeItem(opts.itemNum - 1); return false;
            });
        }

        if (opts.itemNum != (opts.itemArray.length - 1)) {
            $("#fancy_nav").append('<a id="fancy_right" href="javascript:;"></a>');
            
            $('#fancy_right').click(function(){
                $.fn.fancybox.changeItem(opts.itemNum + 1); return false;
            });
        }

        $(document).keydown(function(event) {
            if (event.keyCode == 27) {
                $.fn.fancybox.close();

            } else if(event.keyCode == 37 && opts.itemNum != 0) {
                $.fn.fancybox.changeItem(opts.itemNum - 1);

            } else if(event.keyCode == 39 && opts.itemNum != (opts.itemArray.length - 1)) {
                $.fn.fancybox.changeItem(opts.itemNum + 1);
            }
        });
    };

    $.fn.fancybox.preloadNeighborImages = function() {
        if ((opts.itemArray.length - 1) > opts.itemNum) {
            preloadNextImage = new Image();
            preloadNextImage.src = opts.itemArray[opts.itemNum + 1].url;
        }

        if (opts.itemNum > 0) {
            preloadPrevImage = new Image();
            preloadPrevImage.src = opts.itemArray[opts.itemNum - 1].url;
        }
    };

    $.fn.fancybox.close = function() {
        if (opts.animating) return false;

        $(imgPreloader).unbind('load');
        $(document).unbind("keydown");

        $("#fancy_loading,#fancy_title,#fancy_close,#fancy_bg").hide();

        $("#fancy_nav").empty();

        opts.active    = false;

        if (opts.itemArray[opts.itemNum].o.zoomSpeedOut > 0) {
            var itemOpts = {
                'top':        opts.itemArray[opts.itemNum].orig.pos.top - 18,
                'left':        opts.itemArray[opts.itemNum].orig.pos.left - 18,
                'height':    opts.itemArray[opts.itemNum].orig.height,
                'width':    opts.itemArray[opts.itemNum].orig.width,
                'opacity':    'hide'
            };

            opts.animating = true;

            $("#fancy_outer").animate(itemOpts, opts.itemArray[opts.itemNum].o.zoomSpeedOut, function() {
                $("#fancy_content").hide().empty();
                $("#fancy_overlay,#fancy_bigIframe").remove();
                opts.animating = false;
            });

        } else {
            $("#fancy_outer").hide();
            $("#fancy_content").hide().empty();
            $("#fancy_overlay,#fancy_bigIframe").fadeOut("fast").remove();
        }
    };

    $.fn.fancybox.showLoading = function() {
        clearInterval(loadingTimer);

        var pos = $.fn.fancybox.getViewport();

        $("#fancy_loading").css({'left': ((pos[0] - 40) / 2 + pos[2]), 'top': ((pos[1] - 40) / 2 + pos[3])}).show();
        $("#fancy_loading").bind('click', $.fn.fancybox.close);
        
        loadingTimer = setInterval($.fn.fancybox.animateLoading, 66);
    };

    $.fn.fancybox.animateLoading = function(el, o) {
        if (!$("#fancy_loading").is(':visible')){
            clearInterval(loadingTimer);
            return;
        }

        $("#fancy_loading > div").css('top', (loadingFrame * -40) + 'px');

        loadingFrame = (loadingFrame + 1) % 12;
    };

    $.fn.fancybox.init = function() {
        if (!$('#fancy_wrap').length) {
            $('<div id="fancy_wrap"><div id="fancy_loading"><div></div></div><div id="fancy_outer"><div id="fancy_inner"><div id="fancy_nav"></div><div id="fancy_close"></div><div id="fancy_content"></div><div id="fancy_title"></div></div></div></div>').appendTo("body");
            $('<div id="fancy_bg"><div class="fancy_bg fancy_bg_n"></div><div class="fancy_bg fancy_bg_ne"></div><div class="fancy_bg fancy_bg_e"></div><div class="fancy_bg fancy_bg_se"></div><div class="fancy_bg fancy_bg_s"></div><div class="fancy_bg fancy_bg_sw"></div><div class="fancy_bg fancy_bg_w"></div><div class="fancy_bg fancy_bg_nw"></div></div>').prependTo("#fancy_inner");
            
            $('<table cellspacing="0" cellpadding="0" border="0"><tr><td id="fancy_title_left"></td><td id="fancy_title_main"><div></div></td><td id="fancy_title_right"></td></tr></table>').appendTo('#fancy_title');
        }

        if ($.browser.msie) {
            $("#fancy_inner").prepend('<iframe id="fancy_freeIframe" scrolling="no" frameborder="0"></iframe>');
        }

        if (jQuery.fn.pngFix) $(document).pngFix();

        $("#fancy_close").click($.fn.fancybox.close);
    };

    $.fn.fancybox.getPosition = function(el) {
        var pos = el.offset();

        pos.top    += $.fn.fancybox.num(el, 'paddingTop');
        pos.top    += $.fn.fancybox.num(el, 'borderTopWidth');

         pos.left += $.fn.fancybox.num(el, 'paddingLeft');
        pos.left += $.fn.fancybox.num(el, 'borderLeftWidth');

        return pos;
    };

    $.fn.fancybox.num = function (el, prop) {
        return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0;
    };

    $.fn.fancybox.getPageScroll = function() {
        var xScroll, yScroll;

        if (self.pageYOffset) {
            yScroll = self.pageYOffset;
            xScroll = self.pageXOffset;
        } else if (document.documentElement && document.documentElement.scrollTop) {
            yScroll = document.documentElement.scrollTop;
            xScroll = document.documentElement.scrollLeft;
        } else if (document.body) {
            yScroll = document.body.scrollTop;
            xScroll = document.body.scrollLeft;    
        }

        return [xScroll, yScroll]; 
    };

    $.fn.fancybox.getViewport = function() {
        var scroll = $.fn.fancybox.getPageScroll();

        return [$(window).width(), $(window).height(), scroll[0], scroll[1]];
    };

    $.fn.fancybox.getMaxSize = function(maxWidth, maxHeight, imageWidth, imageHeight) {
        var r = Math.min(Math.min(maxWidth, imageWidth) / imageWidth, Math.min(maxHeight, imageHeight) / imageHeight);

        return [Math.round(r * imageWidth), Math.round(r * imageHeight)];
    };

    $.fn.fancybox.defaults = {
        hideOnContentClick:    false,
        zoomSpeedIn:        500,
        zoomSpeedOut:        500,
        frameWidth:            600,
        frameHeight:        400,
        overlayShow:        false,
        overlayOpacity:        0.4,
        itemLoadCallback:    null
    };
})(jQuery);

function create_note()
{
    jQuery('.notice .ntext').html(str_replace("[TEMP]","",jQuery('#note_form').html()));
    jQuery('.notice .ndate').html('&nbsp;');
}

function change_no_search_prompt(check)
{
  if(check>0) 
    jQuery('#no_search_prompt').html(str_replace('type="checkbox"','type="checkbox" checked="checked"',jQuery('#no_search_prompt').html()));
  else
    jQuery('#no_search_prompt').html(str_replace('checked="checked"','',jQuery('#no_search_prompt').html()));
  jQuery.ajax({
  type:"GET",
  url:_BASE_URL+"ajax_change_no_search_prompt.php",
  data: 'check='+check,
  success:function(msg){}});
}

function change_no_sell_prompt(check)
{
  jQuery.ajax({
  type:"GET",
  url:_BASE_URL+"ajax_change_no_sell_prompt.php",
  data: 'check='+check,
  success:function(msg){}});
}
var no_google_prompt = 0;
function change_no_google_prompt(check)
{
  no_google_prompt = check;  
  jQuery.ajax({
  type:"GET",
  url:_BASE_URL+"ajax_change_no_google_prompt.php",
  data: 'check='+check,
  success:function(msg){}});
}

function yes_my_destination(title, id)
{
  jQuery('#no_search_prompt').html(str_replace('type="checkbox"','type="checkbox" checked="checked"',jQuery('#no_search_prompt').html()));
  autocomplete_MakeBox('result_list','country_id','facelist',{'0':title, '1':id});
  disablePopup();
  jQuery.ajax({
  type:"GET",
  url:_BASE_URL+"ajax_change_no_search_prompt.php",
  data: 'check=1',
  success:function(msg){}});
}

function autocomplete_Remove_tag_data(classname,data)
{
    jQuery('.'+classname+' #bit-'+new String(data).replace(/ /g,'_')).remove();
    jQuery('.'+classname+' .token-input input[type="text"]').show();
    
    if(document.getElementById('main_listing')) apply_search_filter();
}
function autocomplete_MakeBox(result, field, classname,data)
{
    elemLI = jQuery('<li id="bit-'+new String(data[1]).replace(/ /g,'_')+'" class="token"><span><span><span><span>'+data[0]+'</span></span></span></span></li>').click(function () {jQuery('.token').removeClass('token_selected'); jQuery("#list_user").addClass("token_selected");},function () {jQuery("#list_user").removeClass("token_selected");});
    elemA = jQuery('<span class="x" onclick="autocomplete_Remove_tag_data(\''+classname+'\',\''+data[1]+'\');"> .x</span>');
    jQuery(elemLI).append(elemA);
    jQuery('#'+result+' ul').remove();
    jQuery('.'+classname+' .token-input').before(elemLI);
    jQuery('#'+field).val('');
    apply_search_filter();
}

function import_feedbacks(ebay, id)
{
    if(ebay == '') return verify_ebay();
    jQuery.ajax({
      type:"GET",
      url:_BASE_URL+"ajax_ebay_feedbacks.php",
      data: 'ebay='+ebay,
      success:function(msg){
        profile_show_content('ID='+id+'&type=ebay','feedbacks', 'feedbacks','wait_container_feedback');
      }
     });
}

function import_from_ebay(ebay)
{
    jQuery.ajax({
      type:"GET",
      url:_BASE_URL+"import_from_ebay.php",
      data: 'ebay='+ebay,
      success:function(msg){
        if(msg == 'error')  
            return verify_ebay();
        else 
        {
            show_popup_text  (msg, 400, 250);
        }
      }
     });
}

function import_from_bonanza(bonanza)
{
    if(bonanza!='') 
        show_popup_text  ('<br><center>Please wait. Loading listings...<br><br><img src="/templates/default/n_img/wait.gif"></center><br>', 650, 100);
    else
        show_popup_text  ('<br><center>Please wait.<br><br><img src="/templates/default/n_img/wait.gif"></center><br>', 650, 100);
    jQuery.ajax({
      type:"GET",
      url:_BASE_URL+"import_from_bonanza.php",
      data: 'bonanza='+bonanza,
      success:function(msg){
        if(msg == 'error')  
            return verify_bonanza();
        else 
        {
            if(strpos(msg, 'No Bonanza listings found'))
            {
                show_popup_text  (msg, 650, 250);
                setTimeout("jQuery('#fancy_div').css({'height':'230px'});", 1000);
            }
            else
            {
                show_popup_text  (msg, 650, 450);
                setTimeout("jQuery('#fancy_div').css({'height':'430px'});", 1000);
            }
        }
      }
     });
}

function change_ebay_import_site(site_id)
{
    show_popup_text  ('<br><center>Please wait. Loading listings...<br><br><img src="/templates/default/n_img/wait.gif"></center><br>', 650, 100);
    jQuery.ajax({
      type:"GET",
      url:_BASE_URL+"import_from_ebay.php",
      data: 'site_id='+site_id,
      success:function(msg){
        if(strpos(msg, 'No eBay listings found'))
        {
            show_popup_text  (msg, 650, 250);
            setTimeout("jQuery('#fancy_div').css({'height':'230px'});", 1000);
        }
        else
        {
            show_popup_text  (msg, 650, 450);
            setTimeout("jQuery('#fancy_div').css({'height':'430px'});", 1000);
        }
      }
     });
}

function see_other_listings(owner)
{
    var html = '<div style="float:right;"><input type="text" style="width:200px;color:#999;" onclick="if(this.value==this.defaultValue) {this.value=\'\';this.style.color=\'#000\';}" onblur="if(this.value==\'\') {this.value=this.defaultValue;this.style.color=\'#999\';}" value="Search..." onkeyup="profile_show_content(\'ID='+owner+'&keyword=\'+this.value,\'my_products\', \'listings\',\'wait_container_listings\');"/></div><br /><br /> <div class="search_wait"><div id="wait_container_listings"></div></div><div id="listings" class="profile"></div><br clear="all"/><br />';
    show_popup_text  (html, 850, 570);
    profile_show_content('ID='+owner,'my_products', 'listings','wait_container_listings');
}

function my_selected_listings_action(sel)
{
    var ids = '';
    jQuery('.list_action').each(function(id, obj){
        if(obj.checked) 
        {
            ids += obj.value+',';
        }
    });
    if(ids == '') return disablePopup();
    if(sel == 'del')
    {
        jQuery.ajax({
          type:"POST",
          url:_BASE_URL+"ajax_delete_listings.php",
          data: 'ids='+ids,
          success:function(msg){
               jQuery('.list_action').each(function(id, obj){
                    if(obj.checked) 
                    {
                        jQuery('#item'+obj.value).remove();
                    }
                });
                refresh_my_activity();
                disablePopup();
          }
         });
    }
    if(sel == 'relist')
    {
        jQuery.ajax({
          type:"POST",
          url:_BASE_URL+"relist_all.php",
          data: 'ids='+ids,
          success:function(msg){
              refresh_my_activity();
              disablePopup();
          }
         });
    }
    if(sel == 'end')
    {
        jQuery.ajax({
          type:"POST",
          url:_BASE_URL+"end_all.php",
          data: 'ids='+ids,
          success:function(msg){
              refresh_my_activity();
              disablePopup();
          }
         });
    }
    if(sel == 'edit')
    {
        jQuery.ajax({
          type: "POST",
          url: "/edit_products.php",
          data: 'ids='+ids+'&QUERY_STRING='+jQuery('#QUERY_STRING').val()+'&QUERY_SCRIPT='+jQuery('#QUERY_SCRIPT').val(),
          success: function(msg){
            jQuery('#my_activity_cont').html(msg);
          }});
    }
}

function my_selected_listings_action_popup(sel)
{
    if(sel.value == 'edit')
    {
        sel.options[0].selected = true;
        return my_selected_listings_action('edit');
    }
    if(sel.value == 'relist') var text = 'Do you want to relist selected listings?';
    else if(sel.value == 'del') var text = 'Do you want to remove selected from My Activity?';
    else if(sel.value == 'end') var text = 'Do you want to end selected listings?';
    var msg = '<h2>'+text+'</h2><br><div style="float: left;padding-right:5px;"><div class="tabletitle_white"><a onclick="my_selected_listings_action(\''+sel.value+'\')" href="javascript: void(0);" class="button">Yes</a></div></div><div style="float: left;"><div class="tabletitle_white"><a onclick="disablePopup();" href="javascript: void(0);" class="button">No</a></div></div>'+(sel.value == 'relist' ? '<br><br><br><br><br><br>Note: To edit listing settings, you have to re-list each listing individually':'')+'';
    
    show_popup_text(msg, 400, 200);
    sel.options[0].selected = true;
}

function show_ship_countries(val)
{
    jQuery.ajax({
      type:"GET",
      url:_BASE_URL+"ajax_show_ship_countries.php",
      data: 'ids='+val,
      success:function(msg){
          if(msg!='')
          {
              jQuery('#shipping_countries').css({'display':'table-row'});
              jQuery('#shipping_countries .s_u_error_1 div').html(msg);
              jQuery('#shipping_countries .s_u_error_1').show();
          }
          else
          {
              jQuery('#shipping_countries').css({'display':'none'});
              jQuery('#shipping_countries .s_u_error_1 div').html('');
          }
      }
     });
}

function save_new_address()
{
    if(jQuery('#new_address').val() != '')
    {
        var vars = 'billing_title='+jQuery('#billing_title').val();
        vars += '&billing_name='+jQuery('#billing_name').val();
        vars += '&billing_address='+jQuery('#billing_address').val();
        vars += '&billing_email='+jQuery('#billing_email').val();
        vars += '&billing_city='+jQuery('#billing_city').val();
        vars += '&billing_zip='+jQuery('#billing_zip').val();
        vars += '&billing_phone='+jQuery('#billing_phone').val();
        vars += '&same='+document.getElementById('same').checked;
        vars += '&shipping_title='+jQuery('#shipping_title').val();
        vars += '&shipping_name='+jQuery('#shipping_name').val();
        vars += '&shipping_address='+jQuery('#shipping_address').val();
        vars += '&shipping_email='+jQuery('#shipping_email').val();
        vars += '&shipping_city='+jQuery('#shipping_city').val();
        vars += '&shipping_zip='+jQuery('#shipping_zip').val();
        vars += '&shipping_phone='+jQuery('#shipping_phone').val();
        vars += '&name='+jQuery('#new_address').val();
        jQuery.ajax({
          type:"GET",
          url:_BASE_URL+"ajax_save_address.php",
          data: vars,
          success:function(msg){
              jQuery('#addresses').html(jQuery('#addresses').html()+'<option value="'+msg+'">'+jQuery('#new_address').val()+'</option>');
              jQuery('#new_address').val('');
          }
        });
        jQuery('#new_address_cont').hide();
    }
}

function change_address(val)
{
    if(val == 0)
    {
        jQuery('#del_address').hide();
        set_select_value('billing_title','Mr.');
        jQuery('#billing_name').val('');
        jQuery('#billing_address').val('');
        jQuery('#billing_email').val('');
        jQuery('#billing_city').val('');
        jQuery('#billing_zip').val('');
        jQuery('#billing_phone').val('');
        document.getElementById('same').checked=false;
        set_select_value('shipping_title','Mr.');
        jQuery('#shipping_name').val('');
        jQuery('#shipping_address').val('');
        jQuery('#shipping_email').val('');
        jQuery('#shipping_city').val('');
        jQuery('#shipping_zip').val('');
        jQuery('#shipping_phone').val('');
        document.getElementById('shipping_cont').style.display='block';
    }
    else
    {
        jQuery('#del_address').css({'display':'inline'});
        jQuery.ajax({
          type:"GET",
          url:_BASE_URL+"ajax_load_address.php",
          data: 'id='+val,
          success:function(msg){
              eval(msg);
          }
        });
    }
}

function delete_address()
{
    jQuery.ajax({
      type:"GET",
      url:_BASE_URL+"ajax_delete_address.php",
      data: 'id='+jQuery('#addresses').val(),
      success:function(msg){
          jQuery("#addresses option").each(function(id,obj){
              if(jQuery(obj).val() == jQuery('#addresses').val())  jQuery(obj).remove();
          });
          set_select_value('addresses','');
          jQuery('#del_address').hide();
      }
    });
}

var buzz_search_timer = null;
function buzz_search_key()
{
    clearTimeout(buzz_search_timer);
    buzz_search_timer = setTimeout('buzz_search_go()', 500);
}

function buzz_search_go()
{
    profile_show_content('type='+jQuery('#buzz_type').val()+'&keyword='+jQuery('#buzz_search').val(),'buzz_list', 'network_cont');
    update_buzz_corners();
}

function write_to_wall()
{
    if(jQuery('#idtext').val() != '' && jQuery('#idtext').val() != 'Leave a comment')
    {
        submit_ajax_form(document.add_wall_form,'wall');
        go_wall_timer(30);
    }
    else
        jQuery('#form_error').html('Enter text<br>');
}

var wall_post_timer = null;
function go_wall_timer(time)
{
    if(time>0)
    {
        jQuery('#2comment_add_fields').hide();
        jQuery('#write_timer').html(time).show();
        wall_post_timer = setTimeout('go_wall_timer('+(time-1)+')',1000);
    }
    else
    {
        clearTimeout(wall_post_timer);
        jQuery('#2comment_add_fields').show();
        jQuery('#write_timer').hide();
    }
}

function show_buzz_replies(buzz_id)
{
    if(jQuery('#buzz_replies'+buzz_id).css('display') == 'block') 
    {
        jQuery('#buzz_clear'+buzz_id).show();
        jQuery('#buzz_rep_clear'+buzz_id).hide();
        return jQuery('#buzz_replies'+buzz_id).hide();
    }
    jQuery.ajax({
      type:"GET",
      url:_BASE_URL+"buzz_replies_single.php",
      data: 'id='+buzz_id,
      success:function(msg){
          if(msg!='') 
          {
              jQuery('#buzz_clear'+buzz_id).hide();
              jQuery('#buzz_rep_clear'+buzz_id).show();
              jQuery('#buzz_replies'+buzz_id).html(msg).show();
          }
      }
    });
}

function change_help(type)
{
    jQuery('#help1_link_cont').removeClass('active');
    jQuery('#help2_link_cont').removeClass('active');
    jQuery('#help3_link_cont').removeClass('active');
    jQuery('#help4_link_cont').removeClass('active');
    jQuery('#help'+type+'_link_cont').addClass('active');
    
    jQuery('#help_cont').hide();
    jQuery('#help1_cont').hide();
    jQuery('#help2_cont').hide();
    jQuery('#help3_cont').hide();
    jQuery('#help4_cont').hide();
    jQuery('#help'+type+'_cont').show();
    if(type==4)
    {
        jQuery.ajax({
          type:"GET",
          url:_BASE_URL+"get_help_questions.php",
          data: '',
          success:function(msg){
              jQuery('#help4_cont').show().html(msg);
          }
        });
    }
}

function show_help_article(id)
{
    jQuery('#help1_cont').hide();
    jQuery('#help2_cont').hide();
    jQuery('#help3_cont').hide();
    jQuery('#help4_cont').hide();
    jQuery.ajax({
      type:"GET",
      url:_BASE_URL+"get_help_article.php",
      data: 'id='+id,
      success:function(msg){
          jQuery('#help_cont').show().html(msg);
      }
    });
    
}

function post_help_comment(id)
{
    jQuery('#comment_error').html('');
    jQuery('#comment_success').html('');
    if(jQuery('#help_text').val() != '') 
    {
        jQuery.ajax({
          type:"GET",
          url:_BASE_URL+"ajax_add_help_text.php",
          data: 'id='+id+'&text='+jQuery('#help_text').val(),
          success:function(msg){
              jQuery('#help_text').val('');
              jQuery('#comment_success').html('Question has been sent to admin<br>');
          }
        });
    }   
    else
        jQuery('#comment_error').html('Enter text<br>');
}

function remove_help_q(id)
{
    jQuery('#help_comm'+id).remove();
    jQuery.ajax({
      type:"GET",
      url:_BASE_URL+"ajax_del_help_text.php",
      data: 'id='+id,
      success:function(msg){
      }
    });
    
}

function post_help_reply(id)
{
    jQuery('#comment_error'+id).html('');
    jQuery('#comment_success'+id).html('');
    if(jQuery('#help_text'+id).val() != '') 
    {
        jQuery.ajax({
          type:"POST",
          url:"/ajax_add_help_reply_text.php",
          data: 'id='+id+'&text='+jQuery('#help_text'+id).val(),
          success:function(msg){
              jQuery('#help_text'+id).val('');
              jQuery('#comment_success'+id).html('Reply has been added<br>');
          }
        });
    }   
    else
        jQuery('#comment_error'+id).html('Enter text<br>');
}

function remove_help_reply(id)
{
    jQuery('#help_comm'+id).remove();
    jQuery.ajax({
      type:"GET",
      url:_BASE_URL+"ajax_del_help_text.php",
      data: 'id='+id,
      success:function(msg){
      }
    });
    
}

function remove_help_reply(id)
{
    jQuery('#reply'+id).remove();
    jQuery.ajax({
      type:"GET",
      url:_BASE_URL+"ajax_del_help_reply.php",
      data: 'id='+id,
      success:function(msg){
      }
    });
    
}

function show_next_questions(id)
{
    var count = 0;
    jQuery('.comments').each(function(id,obj){count++;});
    jQuery.ajax({
      type:"GET",
      url:_BASE_URL+"ajax_get_help_next.php",
      data: 'id='+id+'&count='+count+'&date='+jQuery('#date_update').val(),
      success:function(msg){
          if(msg[0] == '1') 
              msg = msg.substr(1);
          else
              jQuery('#more_q').hide();
              
          jQuery('.comments:last').after(msg);
      }
    });
    
}

function start_chat_session(id)
{
    var create_div = false;
    if(jQuery('#cometchat_userslist_available .cometchat_nofriends').html()!=null) 
    {
        jQuery('#cometchat_userslist_available .cometchat_nofriends').remove();
        create_div = true;
    }
    if(!document.getElementById('cometchat_userlist_'+id))
    {
        jQuery.ajax({
          type:"GET",
          url:_BASE_URL+"ajax_add_user_to_chat_session.php",
          data: 'id='+id,
          success:function(msg){
              if(!create_div)
                jQuery('.cometchat_userlist:last').after(msg);
              else
                jQuery('#cometchat_userslist_available').html('<div>'+msg+'</div>');
              chat_call(null, jQuery('#cometchat_userlist_'+id));
          }
        });
    }
    else
        chat_call(null, jQuery('#cometchat_userlist_'+id));
}

function change_about(id)
{
    jQuery('.page_links').each(function(id, obj){jQuery(obj).removeClass('active');});
    jQuery('.page_conts').each(function(id, obj){jQuery(obj).hide();});
    jQuery('#cont'+id).show();
    jQuery('#link_cont'+id).addClass('active');
}

function upload_xls_file()
{
    jQuery('#excel_input').hide();
    jQuery('#excel_text').html('Please wait...');
    jQuery.ajaxUpload({
     url:_BASE_URL+'csv_listings.php',
     secureuri:false,
     uploadform: document.getElementById('xls_import_form'),
     dataType: 'html',  
     success: function (response, status){ 

        if(response=='ok')
        {
            jQuery('#excel_text').html('You have successfully uploaded your listings');
            setTimeout("disablePopup();", 2000);
        }
        else
        {
            jQuery('#excel_input').show();
            jQuery('#excel_text').html('<br /><span style="color:#f00;">Incorrect file or data inside. Please check and try again</span>');
        }
      },
      error: function (data, status, e)
      {
        //alert('+'+e);  
      } 
     }); 
}

function show_google_checkout_hep(obj)
{
    if(obj.checked && no_google_prompt==0)
    {
        var text = '<div style="float:left;"><h2>Instruction on how to get Google Checkout to work with Buzzmart.com</h2></div><div style="float:right;padding-right:10px;"><input type="checkbox" class="no_google_prompt_checkbox" onclick="change_no_google_prompt(this.checked ? 1 : 0)"/> Do not show this again</div><br clear="all" /><br />In order for Buzzmart to be able to automatically process listings using Google Checkout please see the screen shot below to see how to configure your Google Checkout Merchant account under the Settings tab. If you do not follow the below instruction Buzzmart will NOT be able to receive automated callbacks regarding the payment status which is required to inform buyers and sellers in their My Activity page or via the automated email notification system. <br />Please make sure your Buzzmart default currency is the same as your Google Merchant account currency.<br /><br /><img src="/templates/default/n_img/merchantsteps.png" /> ';
        show_popup_text(text, 1100, 700);
    }
}

function get_ship_rates(id)
{
    jQuery('#ship_error').html('');
    var ship_quantity = jQuery('#ship_quantity').val();
    var ship_country = jQuery('#ship_country').val();
    var ship_zip = jQuery('#ship_zip').val();
    if(ship_quantity > 0 && ship_country != '' && ship_zip != '')
    {
        jQuery('#ship_calc_result').html('<br>Please wait...');
        jQuery.ajax({
          type:"GET",
          url:_BASE_URL+"ajax_calc_shipping.php",
          data: 'id='+id+'&ship_quantity='+ship_quantity+'&ship_country='+ship_country+'&ship_zip='+ship_zip,
          success:function(msg){
              jQuery('#ship_calc_result').html(msg);
          }
        });
    }
    else
        jQuery('#ship_error').html('Fill all fields<br><br>');
}

function cart_calc_ship_cost(wid)
{
    jQuery('#error'+wid).html('Please wait...');
    jQuery('#service'+wid).val('');
    var ship_country = jQuery('#country'+wid).val();
    var ship_zip = jQuery('#zip'+wid).val();
    if(ship_country != '' && ship_zip != '')
    {
        jQuery.ajax({
          type:"GET",
          url:_BASE_URL+"ajax_cart_calc_shipping.php",
          data: 'wid='+wid+'&ship_country='+ship_country+'&ship_zip='+ship_zip,
          success:function(msg){
              eval(msg);
          }
        });
    }
    else
        jQuery('#error'+wid).html('Fill fields<br><br>');
}

function slide_network_settings()
{
   jQuery.ajax({
      type:"GET",
      url:_BASE_URL+"network_settings.php",
      data: '',
      success:function(msg){
          jQuery('.network_settings').html(msg).slideDown("slow");
          jQuery("#list_user").autocomplete( 'ajax_countries.php', properties = { 
            matchContains: true,
            minChars: 0,
            selectFirst:    true, 
            intro_text: "Type Country", 
            no_result: 'No Countries',
            result_cont: 'result_list',
            user_list: 'user_list',
            classname: 'facelist'
          });     
          jQuery('#list_user').removeAttr("disabled"); 
      }
   });
}

function com_notif(id)
{
   jQuery.ajax({
      type:"GET",
      url:_BASE_URL+"com_notif.php",
      data: 'id='+id,
      success:function(msg){
         
      }
   });
}

function init_home_page_flipper()
{
    jQuery('.galleryImage').hover(  
        function()  
        {  
            
            if(jQuery(this).find('img').attr('resline') == 'width')
                jQuery(this).find('img').animate(  
                       {
                           width:70,  
                           margin:4,
                      },300);  
             else
                jQuery(this).find('img').animate(  
                       {
                           height:70,  
                           margin:4
                      },300); 
            if(-[1,]) 
                jQuery(this).animate(  {width:210, 'border':'1px solid #555'},300);  
            else
                jQuery(this).css(  {width:210, 'border':'1px solid #555'});  
         },  
         function()  
         {  
             
             if(jQuery(this).find('img').attr('resline') == 'width')
                jQuery(this).find('img').animate(  
                       {
                           width:157,  
                           margin:0,
                      },300);  
             else
                jQuery(this).find('img').animate(  
                       {
                           height:124,  
                           margin:0
                      },300); 
             if(-[1,])
                jQuery(this).animate(  {width:157, 'border':'0px'},300);  
             else
                jQuery(this).css(  {width:157, 'border':'0px'});  
         }
    );  
}

function paste_youtube()
{
    var url = jQuery('#record_video_name').val();
    var param = url.substr(strpos(url, '?v=')+3);
    if(strpos(url, '?v=') > 0 && param!='')
    {
        jQuery('#youtube_ex').html('<object width="425" height="350" data="http://www.youtube.com/v/'+param+'" type="application/x-shockwave-flash"><param name="src" value="http://www.youtube.com/v/'+param+'" /></object>')
    }
    else
        jQuery('#youtube_ex').html('<span style="color:#f00;">Incorrect URL or video not found</span>');
}

// TripleFlap, <http://floern.com/software/tripleflap>, a flying twitter bird. Copyright (c) 2010 Florian Buenzli, <http://floern.com/>, GNU/GPL.
if(typeof(twitterAccount)!="string")var twitterAccount="";
if(typeof(tweetThisText)!="string"||tweetThisText=="")var tweetThisText=document.title+" "+document.URL;
if(typeof(showTweet)!="boolean")var showTweet=false;
var tweetthislink=null;
if(typeof(otherPageOrFeed)!="string"||otherPageOrFeed=="")var otherPageOrFeed=false;
var birdSprite="/templates/default/n_img/birdsprite.png";/*Pfad zur Sprite-Grafik*/
var twitterfeedreader="/twitterfeedreader.php";/*Pfad zur PHP-Datei*/
var hyperlinkStyle="color:#27b;text-decoration:none;";
var birdSpeed=12;
var birdSpaceVertical=16;
var birdSetUp=2;
var spriteWidth=64;
var spriteHeight=64;
var spriteAniSpeed=72;
var spriteAniSpeedSlow=Math.round(spriteAniSpeed*1.75);
var targetElems=new Array("img","hr","input","textarea","button","select","table","td","div","ul","ol","li","h1","h2","h3","h4","p","code","object","a","b","strong","span");
var neededElems4random=10;
var minElemWidth=Math.round(spriteWidth/3);
var scareTheBirdMouseOverTimes=4;
var scareTheBirdTime=1000;
var showOnMobile=false;
var birdIsFlying=false;
var scrollPos=0;
var windowHeight=getWindowHeight();
var windowWidth=getWindowWidth();
if(windowHeight<=spriteHeight+2*birdSpaceVertical)windowHeight=spriteHeight+2*birdSpaceVertical+1;
if(windowWidth<=spriteWidth)windowWidth=spriteWidth+1;
var birdPosX=Math.round(Math.random()*(windowWidth-spriteWidth+200)-200);
var birdPosY=-2*spriteHeight;
var timeoutAnimation=false;
var timeoutFlight=false;
var showButtonsTimeout=null;
var hideButtonsTimeout=null;
var scareTheBirdLastTime=0;
var scareTheBirdCount=0;
function tripleflapInit(reallystart){
if(typeof(reallystart)=="undefined"){window.setTimeout("tripleflapInit(1)",250);return;}
if(!showOnMobile&&typeof(navigator.userAgent)=="string"&&is_mobile(navigator.userAgent)){return;}
if(!is_utf8(tweetThisText)) tweetThisText=utf8_encode(tweetThisText);
var tweetthislink="http://twitter.com/home?status="+escape(tweetThisText);
if(twitterAccount=="") showTweet=false;
var accountURL=(twitterAccount!="")?"http://twitter.com/"+twitterAccount:((otherPageOrFeed!=false)?otherPageOrFeed:"http://twitter.com/");
var tBird=document.createElement("a");
tBird.setAttribute("id","tBird");
tBird.setAttribute("href",accountURL);
tBird.setAttribute("target","_blank");
tBird.style.display="block";
tBird.style.position="absolute";
tBird.style.left=birdPosX+"px";
tBird.style.top=birdPosY+"px";
tBird.style.width=spriteWidth+"px";
tBird.style.height=spriteHeight+"px";
tBird.style.background="url('"+birdSprite+"') no-repeat transparent";
tBird.style.backgroundPosition="-0px -0px";
tBird.style.zIndex="947";
tBird.onmouseover=function(){
scareTheBird();
showButtonsTimeout=window.setTimeout("showButtons(0,"+windowWidth+","+windowHeight+")",400);
window.clearTimeout(hideButtonsTimeout);
};
tBird.onmouseout=function(){hideButtonsTimeout=window.setTimeout("hideButtons()",50);};
document.body.appendChild(tBird);
var tBirdLtweet=document.createElement("a");
tBirdLtweet.setAttribute("id","tBirdLtweet");
tBirdLtweet.setAttribute("href",tweetthislink);
tBirdLtweet.setAttribute("target","_blank");
tBirdLtweet.setAttribute("title","tweet this");
tBirdLtweet.style.display="none";
tBirdLtweet.style.position="absolute";
tBirdLtweet.style.left="0px";
tBirdLtweet.style.top="-100px";
tBirdLtweet.style.background="url('"+birdSprite+"') no-repeat transparent";
tBirdLtweet.style.opacity="0";
tBirdLtweet.style.filter="alpha(opacity=0)";
tBirdLtweet.style.backgroundPosition="-64px -0px";
tBirdLtweet.style.width="58px";
tBirdLtweet.style.height="30px";
tBirdLtweet.style.zIndex="951";
tBirdLtweet.onmouseover=function(){window.clearTimeout(hideButtonsTimeout);};
tBirdLtweet.onmouseout=function(){hideButtonsTimeout=window.setTimeout("hideButtons()",50);};
document.body.appendChild(tBirdLtweet);
var tBirdLfollow=tBirdLtweet.cloneNode(false);
tBirdLfollow.setAttribute("id","tBirdLfollow");
tBirdLfollow.setAttribute("href",accountURL);
tBirdLfollow.setAttribute("title","follow "+(twitterAccount?"@"+twitterAccount:"me"));
tBirdLfollow.style.backgroundPosition="-64px -30px";
tBirdLfollow.style.width="58px";
tBirdLfollow.style.height="20px";
tBirdLfollow.style.zIndex="952";
tBirdLfollow.onmouseover=function(){window.clearTimeout(hideButtonsTimeout);};
tBirdLfollow.onmouseout=function(){hideButtonsTimeout=window.setTimeout("hideButtons()",50);};
document.body.appendChild(tBirdLfollow);
if(showTweet==true){
var tBirdStatxLow=document.createElement("div");
tBirdStatxLow.setAttribute("id","tBirdStatxLow");
tBirdStatxLow.style.display="none";
tBirdStatxLow.style.position="absolute";
tBirdStatxLow.style.left="0px";
tBirdStatxLow.style.top="-100px";
tBirdStatxLow.style.background="transparent";
tBirdStatxLow.style.opacity="0";
tBirdStatxLow.style.filter="alpha(opacity=0)";
tBirdStatxLow.style.width="192px";
tBirdStatxLow.style.zIndex="955";
tBirdStatxLow.onmouseover=function(){window.clearTimeout(hideButtonsTimeout);};
tBirdStatxLow.onmouseout=function(){hideButtonsTimeout=window.setTimeout("hideButtons()",50);};
var tBirdStatxUpr=tBirdStatxLow.cloneNode(false);
tBirdStatxUpr.setAttribute("id","tBirdStatxUpr");
tBirdStatxUpr.onmouseover=function(){window.clearTimeout(hideButtonsTimeout);};
tBirdStatxUpr.onmouseout=function(){hideButtonsTimeout=window.setTimeout("hideButtons()",50);};
var tBirdStatxArrLow=document.createElement("div");
tBirdStatxArrLow.setAttribute("id","tBirdStatxArrLow");
tBirdStatxArrLow.style.background="url('"+birdSprite+"') no-repeat transparent";
tBirdStatxArrLow.style.backgroundPosition="-64px -50px";
tBirdStatxArrLow.style.width="32px";
tBirdStatxArrLow.style.height="9px";
tBirdStatxArrLow.style.margin="0 0 -1px 56px";
tBirdStatxArrLow.style.position="relative";
tBirdStatxArrLow.style.zIndex="957";
var tBirdStatxArrUpr=tBirdStatxArrLow.cloneNode(false);
tBirdStatxArrUpr.setAttribute("id","tBirdStatxArrUpr");
tBirdStatxArrUpr.style.backgroundPosition="-96px -50px";
tBirdStatxArrUpr.style.margin="-1px 0 0 60px";
var tBirdStatxInLow=document.createElement("div");
tBirdStatxInLow.setAttribute("id","tBirdStatxInLow");
tBirdStatxInLow.style.background="#fbfcfc";
tBirdStatxInLow.style.border="1px solid #555";
tBirdStatxInLow.style.MozBorderRadius="6px";
tBirdStatxInLow.style.borderRadius="6px";
tBirdStatxInLow.style.padding="3px 5px";
tBirdStatxInLow.style.fontSize="11px";
tBirdStatxInLow.style.fontFamily="Arial";
tBirdStatxInLow.style.textAlign="left";
tBirdStatxInLow.style.position="relative";
tBirdStatxInLow.style.zIndex="956";
tBirdStatxInLow.innerHTML="loading...";
var tBirdStatxInUpr=tBirdStatxInLow.cloneNode(false);
tBirdStatxInUpr.setAttribute("id","tBirdStatxInUpr");
tBirdStatxInUpr.innerHTML="loading...";
tBirdStatxLow.appendChild(tBirdStatxArrLow);
tBirdStatxLow.appendChild(tBirdStatxInLow);
tBirdStatxUpr.appendChild(tBirdStatxInUpr);
tBirdStatxUpr.appendChild(tBirdStatxArrUpr);
document.body.appendChild(tBirdStatxLow);
document.body.appendChild(tBirdStatxUpr);
}
var timeoutAnimation=window.setTimeout("animateSprite(0,0,0,0,null,true)",spriteAniSpeed);
window.onscroll=recheckposition;
if(showTweet==true)
loadStatusText();
recheckposition();
}
function animateSprite(row,posStart,posEnd,count,speed,onlySet){
if(typeof(count)!="number"||count>posEnd-posStart) count=0;
document.getElementById("tBird").style.backgroundPosition="-"+Math.round((posStart+count)*spriteWidth)+"px -"+(spriteHeight*row)+"px";
if(onlySet==true) return;
if(typeof(speed)!="number") speed=spriteAniSpeed;
timeoutAnimation=window.setTimeout("animateSprite("+row+","+posStart+","+posEnd+","+(count+1)+","+speed+")",speed);
}
function animateSpriteAbort(){
window.clearTimeout(timeoutAnimation);
}
function recheckposition(force){
if(force!=true) force=false;
if(birdIsFlying)
return false;
windowHeight=getWindowHeight();
windowWidth=getWindowWidth();
if(windowHeight<=spriteHeight+2*birdSpaceVertical)
windowHeight=spriteHeight+2*birdSpaceVertical+1;
if(windowWidth<=spriteWidth)
windowWidth=spriteWidth+1;
if(typeof(window.pageYOffset)=="number") scrollPos=window.pageYOffset;
else if(document.body&&document.body.scrollTop) scrollPos=document.body.scrollTop;
else if(document.documentElement&&document.documentElement.scrollTop) scrollPos=document.documentElement.scrollTop;
birdPosY=parseInt(document.getElementById("tBird").style.top);
birdPosX=parseInt(document.getElementById("tBird").style.left);
if(scrollPos+birdSpaceVertical>=birdPosY||scrollPos+windowHeight-spriteHeight<birdPosY||force){
hideButtons();
elemPosis=chooseNewTarget();
if(elemPosis.length<1){
elemType=null;
elemNr=null;
elemTop=scrollPos+Math.round(Math.random()*(windowHeight-spriteHeight));
elemLeft=Math.round(Math.random()*(windowWidth-spriteWidth));
elemWidth=0;
}
else{
newTarget=elemPosis[Math.round(Math.random()*(elemPosis.length-1))];
elemType=newTarget[0];
elemNr=newTarget[1];
elemTop=newTarget[2];
elemLeft=newTarget[3];
elemWidth=newTarget[4];
}
targetTop=elemTop-spriteHeight;
targetLeft=Math.round(elemLeft-spriteWidth/2+Math.random()*elemWidth);
if(targetLeft>windowWidth-spriteWidth-24)
targetLeft=windowWidth-spriteWidth-24;
else if(targetLeft<0)
targetLeft=0;
birdIsFlying=true;
flyFromTo(birdPosX,birdPosY,targetLeft,targetTop,0);
}
}
function chooseNewTarget(){
var elemPosis=new Array();
var obergrenze=scrollPos+spriteHeight+birdSpaceVertical;
var untergrenze=scrollPos+windowHeight-birdSpaceVertical;
for(var ce=0;ce<targetElems.length;ce++){
var elemType=targetElems[ce];
var sumElem=document.getElementsByTagName(elemType).length;
for(var cu=0;cu<sumElem;cu++){
var top=document.getElementsByTagName(elemType)[cu].offsetTop;
var left=document.getElementsByTagName(elemType)[cu].offsetLeft;
var width=document.getElementsByTagName(elemType)[cu].offsetWidth;
if(top<=obergrenze||top>=untergrenze||width<minElemWidth||left<0){
continue;
}
elemPosis[elemPosis.length]=new Array(elemType,cu,top,left,width);
if(elemPosis.length>=neededElems4random)
return elemPosis;
}
}
return elemPosis;
}
function flyFromTo(startX,startY,targetX,targetY,solved,direction){
justStarted=(solved==0);
solved+=(solved>birdSpeed/2)?birdSpeed:Math.round( (solved==0)?birdSpeed/4:birdSpeed/2 );
solvedFuture=solved+( (solved>birdSpeed/2)?birdSpeed:Math.round(birdSpeed/2) );
distanceX=targetX-startX;
distanceY=targetY-startY;
distance=Math.sqrt(distanceX*distanceX+distanceY*distanceY);
solvPerc=Math.abs(1/distance*solved);
solvDistX=Math.round(distanceX*solvPerc);
solvDistY=Math.round(distanceY*solvPerc);
solvPercFuture=Math.abs(1/distance*solvedFuture);
solvDistXFuture=Math.round(distanceX*solvPercFuture);
solvDistYFuture=Math.round(distanceY*solvPercFuture);
if(typeof(direction)!="string"){
direction=null;
angle=( (distanceX!=0)?Math.atan((-distanceY)/distanceX)/Math.PI*180:90 )+((distanceX<0)?180:0);
if(angle<0) angle+=360;
if(angle<45) direction='o';
else if(angle<135) direction='n';
else if(angle<202.5) direction='w';
else if(angle<247.5) direction='sw';
else if(angle<292.5) direction='s';
else if(angle<337.5) direction='so';
else direction='o';
}
if(Math.abs(solvDistXFuture)>=Math.abs(distanceX)&&Math.abs(solvDistYFuture)>=Math.abs(distanceY)){
animateSpriteAbort();
switch(direction){
case 'so':animateSprite(1,0,0,0,null,true);break;
case 'sw':animateSprite(1,2,2,0,null,true);break;
case 's':animateSprite(0,2,2,0,null,true);break;
case 'n':animateSprite(4,0,0,0,null,true);break;
case 'o':animateSprite(1,0,0,0,null,true);break;
case 'w':animateSprite(1,2,2,0,null,true);break;
default:animateSprite(0,0,0,0,null,true);
}
timeoutAnimation=window.setTimeout("animateSprite(0,0,0,0,null,true)",spriteAniSpeed);
}
if(Math.abs(solvDistX)>=Math.abs(distanceX)&&Math.abs(solvDistY)>=Math.abs(distanceY)){
solvDistX=distanceX;
solvDistY=distanceY;
birdIsFlying=false;
window.setTimeout("recheckposition()",500);
}
else{
if(justStarted){
animateSpriteAbort();
switch(direction){
case 'so':animateSprite(1,0,0,0,null,true);timeoutAnimation=window.setTimeout("animateSprite(1,1,1,0,null,true)",spriteAniSpeed);break;
case 'sw':animateSprite(1,2,2,0,null,true);timeoutAnimation=window.setTimeout("animateSprite(1,3,3,0,null,true)",spriteAniSpeed);break;
case 's':animateSprite(0,2,2,0,null,true);timeoutAnimation=window.setTimeout("animateSprite(0,3,3,0,null,true)",spriteAniSpeed);break;
case 'n':timeoutAnimation=window.setTimeout("animateSprite(4,0,3,0,"+spriteAniSpeedSlow+")",1);break;
case 'o':animateSprite(1,0,0,0,null,true);timeoutAnimation=window.setTimeout("animateSprite(2,0,3,0,"+spriteAniSpeedSlow+")",spriteAniSpeed);break;
case 'w':animateSprite(1,2,2,0,null,true);timeoutAnimation=window.setTimeout("animateSprite(3,0,3,0,"+spriteAniSpeedSlow+")",spriteAniSpeed);break;
default:animateSprite(0,0,0,0,null,true);
}
}
timeoutFlight=window.setTimeout("flyFromTo("+startX+","+startY+","+targetX+","+targetY+","+solved+",'"+direction+"')",50);
}
hideButtons();
document.getElementById("tBird").style.left=(startX+solvDistX)+"px";
document.getElementById("tBird").style.top=(startY+solvDistY+birdSetUp)+"px";
}
function scareTheBird(nul){
newTS=new Date().getTime();
if(scareTheBirdLastTime<newTS-scareTheBirdTime){
scareTheBirdCount=1;
scareTheBirdLastTime=newTS;
}
else{
scareTheBirdCount++;
if(scareTheBirdCount>=scareTheBirdMouseOverTimes){
scareTheBirdCount=0;
scareTheBirdLastTime=0;
recheckposition(true);
}
}
}
function showButtons(step,winWidth,winHeight){
birdPosY=parseInt(document.getElementById("tBird").style.top);
birdPosX=parseInt(document.getElementById("tBird").style.left);
if(step==0&&document.getElementById("tBirdLtweet").style.display=="block")
step=100;
if(birdIsFlying)
step=0;
opacity=Math.round(step*15);
if(opacity<0) opacity=0;
if(opacity>100) opacity=100;
if(birdPosX<winWidth-300||birdPosX<winWidth/2){
buttonPosX1=birdPosX+spriteWidth-15;
buttonPosX2=birdPosX+spriteWidth-10;
}
else{
buttonPosX1=birdPosX+16-parseInt(document.getElementById("tBirdLtweet").style.width);
buttonPosX2=birdPosX+11-parseInt(document.getElementById("tBirdLfollow").style.width);
}
buttonPosY1=birdPosY-0;
buttonPosY2=birdPosY-0+parseInt(document.getElementById("tBirdLtweet").style.height);
document.getElementById("tBirdLtweet").style.left=buttonPosX1+"px";
document.getElementById("tBirdLtweet").style.top=buttonPosY1+"px";
document.getElementById("tBirdLtweet").style.display="block";
document.getElementById("tBirdLtweet").style.opacity=opacity/100;
document.getElementById("tBirdLtweet").style.filter="alpha(opacity="+opacity+")";
document.getElementById("tBirdLfollow").style.left=buttonPosX2+"px";
document.getElementById("tBirdLfollow").style.top=buttonPosY2+"px";
document.getElementById("tBirdLfollow").style.display="block";
document.getElementById("tBirdLfollow").style.opacity=opacity/100;
document.getElementById("tBirdLfollow").style.filter="alpha(opacity="+opacity+")";
if(showTweet==true){
if(typeof(window.pageYOffset)=="number") scrollPos=window.pageYOffset;
else if(document.body&&document.body.scrollTop) scrollPos=document.body.scrollTop;
else if(document.documentElement&&document.documentElement.scrollTop) scrollPos=document.documentElement.scrollTop;
if(birdPosX<64) boxMoveX=64-birdPosX;
else if(birdPosX>winWidth-64) boxMoveX=winWidth-birdPosX-64;
else boxMoveX=0;
txtBoxPosX=Math.round(birdPosX+spriteWidth/2 - parseInt(document.getElementById("tBirdStatxLow").style.width)/2+boxMoveX);
if(birdPosY<winHeight/2+scrollPos){
txtBoxPosY=birdPosY+spriteHeight;
document.getElementById("tBirdStatxLow").style.left=txtBoxPosX+"px";
document.getElementById("tBirdStatxLow").style.top=txtBoxPosY+"px";
document.getElementById("tBirdStatxLow").style.display="block";
document.getElementById("tBirdStatxLow").style.opacity=opacity/100;
document.getElementById("tBirdStatxLow").style.filter="alpha(opacity="+opacity+")";
}
else{
txtBoxPosY=birdPosY-document.getElementById("tBirdStatxUpr").offsetHeight;
document.getElementById("tBirdStatxUpr").style.left=txtBoxPosX+"px";
document.getElementById("tBirdStatxUpr").style.top=txtBoxPosY+"px";
document.getElementById("tBirdStatxUpr").style.display="block";
document.getElementById("tBirdStatxUpr").style.opacity=opacity/100;
document.getElementById("tBirdStatxUpr").style.filter="alpha(opacity="+opacity+")";
}
}
if(opacity>=100) return;
step++;
showButtonsTimeout=window.setTimeout("showButtons("+step+","+winWidth+","+winHeight+")",60);
}
function hideButtons(){
window.clearTimeout(showButtonsTimeout);
document.getElementById("tBirdLtweet").style.display="none";
document.getElementById("tBirdLtweet").style.opacity="0";
document.getElementById("tBirdLtweet").style.filter="alpha(opacity=0)";
document.getElementById("tBirdLfollow").style.display="none";
document.getElementById("tBirdLfollow").style.opacity="0";
document.getElementById("tBirdLfollow").style.filter="alpha(opacity=0)";
if(showTweet==true){
document.getElementById("tBirdStatxLow").style.display="none";
document.getElementById("tBirdStatxLow").style.opacity="0";
document.getElementById("tBirdStatxLow").style.filter="alpha(opacity=0)";
document.getElementById("tBirdStatxUpr").style.display="none";
document.getElementById("tBirdStatxUpr").style.opacity="0";
document.getElementById("tBirdStatxUpr").style.filter="alpha(opacity=0)";
}
}
function loadStatusText(){
param="tuac="+twitterAccount;
var req=(window.XMLHttpRequest)?new XMLHttpRequest():((window.ActiveXObject)?new ActiveXObject("Microsoft.XMLHTTP"):false);
if(!req){document.getElementById("tBirdStatxInLow").innerHTML="Error: could not create Ajax-request";}
req.open("POST",twitterfeedreader,true);
req.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
req.setRequestHeader("Content-Length",param.length);
req.setRequestHeader("Connection","close");
req.onreadystatechange=function(){
if(req.readyState==4){
resp=(req.status==200)?req.responseText:"Error: Ajax-request failed,HTTP-Code "+req.status;
resp=resp.replace(/<a /g,'<a style="'+hyperlinkStyle+'" ');
document.getElementById("tBirdStatxInLow").innerHTML=resp;
document.getElementById("tBirdStatxInUpr").innerHTML=resp;
}
}
req.send(param);
}
function getWindowWidth(){
if(typeof(window.innerWidth)=="number") ww=window.innerWidth;
else if(document.documentElement&&document.documentElement.clientWidth) ww=document.documentElement.clientWidth;
else if(document.body&&document.body.clientWidth) ww=document.body.clientWidth;
else ww=800;
return ww;
}
function getWindowHeight(){
if(typeof(window.innerHeight)=="number") wh=window.innerHeight;
else if(document.documentElement&&document.documentElement.clientHeight) wh=document.documentElement.clientHeight;
else if(document.body&&document.body.clientHeight) wh=document.body.clientHeight;
else wh=450;
return wh;
}
function is_mobile(is_mobile_ua){
return (is_mobile_ua.toLowerCase().search(/(iphone|ipod|opera mini|windows ce|windows phone|palm|blackberry|android|symbian|series60|samsung|nokia|playstation portable|htc[\-_]|up\.browser|profile\/midp|[1-4][0-9]{2}x[1-4][0-9]{2})/)>-1)
}
function utf8_encode(str) {
str=str.replace(/\r\n/g,"\n");
utf8str="";
for(n=0;n<str.length;n++){
c=str.charCodeAt(n);
if(c<128){
utf8str+=String.fromCharCode(c);
}
else if(c>127&&c<2048){
utf8str+=String.fromCharCode((c>>6)|192);
utf8str+=String.fromCharCode((c&63)|128);
}
else{
utf8str+=String.fromCharCode((c>>12)|224);
utf8str+=String.fromCharCode(((c>>6)&63)|128);
utf8str+=String.fromCharCode((c&63)|128);
}
}
return utf8str;
}
function is_utf8(str){
strlen=str.length;
for(i=0;i<strlen;i++){
ord=str.charCodeAt(i);
if(ord<0x80) continue;
else if((ord&0xE0)===0xC0&&ord>0xC1) n=1;
else if((ord&0xF0)===0xE0) n=2;
else if((ord&0xF8)===0xF0&&ord<0xF5) n=3;
else return false;
for(c=0;c<n;c++)
if(++i===strlen||(str.charCodeAt(i)&0xC0)!==0x80)
return false;
}
return true;
}



function show_gi_prev() {
    var cursor = imageSearch.cursor;
    var curPage = cursor.currentPageIndex; 
    if(curPage > 0)
    {
        imageSearch.gotoPage(curPage-1);
    }
}

function show_gi_next() {
    var cursor = imageSearch.cursor;
    var curPage = cursor.currentPageIndex; 
    var total = cursor.pages.length;
    if(curPage < total-1)
    {
        imageSearch.gotoPage(curPage+1);
    }
}

function searchComplete() {

if (imageSearch.results && imageSearch.results.length > 0) {
  var results = imageSearch.results;
  var html = '';
  for (var i = 0; i < results.length; i++) {
    var result = results[i];
    html += '<div class="google_image"><div><div class="l"><img onclick="add_gi(\''+result.url+'\');" style="'+(result.tbWidth > result.tbHeight ? 'height:100px;' : 'width:100px;')+'" src="'+result.tbUrl+'"></div></div></div>';
  }
  
  jQuery('#content').html(html);
}
}

function IMGSearchLoad(title) {
    imageSearch = new google.search.ImageSearch();
    imageSearch.setSearchCompleteCallback(this, searchComplete, null);
    imageSearch.setResultSetSize(8);
    imageSearch.execute(title);
}

jQuery.noConflict();
/* FILE INCLUDE
*
* prototype.js
* builder.js
* effects.js
* lightbox.js
*
*/


/*  Prototype JavaScript framework, version 1.6.0.2
 *  (c) 2005-2008 Sam Stephenson
 *
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *  For details, see the Prototype web site: http://www.prototypejs.org/
 *
 *--------------------------------------------------------------------------*/

var Prototype = {
  Version: '1.6.0.2',

  Browser: {
    IE:     !!(window.attachEvent && !window.opera),
    Opera:  !!window.opera,
    WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
    Gecko:  navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
    MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
  },

  BrowserFeatures: {
    XPath: !!document.evaluate,
    ElementExtensions: !!window.HTMLElement,
    SpecificElementExtensions:
      document.createElement('div').__proto__ &&
      document.createElement('div').__proto__ !==
        document.createElement('form').__proto__
  },

  ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
  JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,

  emptyFunction: function() { },
  K: function(x) { return x }
};

if (Prototype.Browser.MobileSafari)
  Prototype.BrowserFeatures.SpecificElementExtensions = false;


/* Based on Alex Arnell's inheritance implementation. */
var Class = {
  create: function() {
    var parent = null, properties = $A(arguments);
    if (Object.isFunction(properties[0]))
      parent = properties.shift();

    function klass() {
      this.initialize.apply(this, arguments);
    }

    Object.extend(klass, Class.Methods);
    klass.superclass = parent;
    klass.subclasses = [];

    if (parent) {
      var subclass = function() { };
      subclass.prototype = parent.prototype;
      klass.prototype = new subclass;
      parent.subclasses.push(klass);
    }

    for (var i = 0; i < properties.length; i++)
      klass.addMethods(properties[i]);

    if (!klass.prototype.initialize)
      klass.prototype.initialize = Prototype.emptyFunction;

    klass.prototype.constructor = klass;

    return klass;
  }
};

Class.Methods = {
  addMethods: function(source) {
    var ancestor   = this.superclass && this.superclass.prototype;
    var properties = Object.keys(source);

    if (!Object.keys({ toString: true }).length)
      properties.push("toString", "valueOf");

    for (var i = 0, length = properties.length; i < length; i++) {
      var property = properties[i], value = source[property];
      if (ancestor && Object.isFunction(value) &&
          value.argumentNames().first() == "$super") {
        var method = value, value = Object.extend((function(m) {
          return function() { return ancestor[m].apply(this, arguments) };
        })(property).wrap(method), {
          valueOf:  function() { return method },
          toString: function() { return method.toString() }
        });
      }
      this.prototype[property] = value;
    }

    return this;
  }
};

var Abstract = { };

Object.extend = function(destination, source) {
  for (var property in source)
    destination[property] = source[property];
  return destination;
};

Object.extend(Object, {
  inspect: function(object) {
    try {
      if (Object.isUndefined(object)) return 'undefined';
      if (object === null) return 'null';
      return object.inspect ? object.inspect() : String(object);
    } catch (e) {
      if (e instanceof RangeError) return '...';
      throw e;
    }
  },

  toJSON: function(object) {
    var type = typeof object;
    switch (type) {
      case 'undefined':
      case 'function':
      case 'unknown': return;
      case 'boolean': return object.toString();
    }

    if (object === null) return 'null';
    if (object.toJSON) return object.toJSON();
    if (Object.isElement(object)) return;

    var results = [];
    for (var property in object) {
      var value = Object.toJSON(object[property]);
      if (!Object.isUndefined(value))
        results.push(property.toJSON() + ': ' + value);
    }

    return '{' + results.join(', ') + '}';
  },

  toQueryString: function(object) {
    return $H(object).toQueryString();
  },

  toHTML: function(object) {
    return object && object.toHTML ? object.toHTML() : String.interpret(object);
  },

  keys: function(object) {
    var keys = [];
    for (var property in object)
      keys.push(property);
    return keys;
  },

  values: function(object) {
    var values = [];
    for (var property in object)
      values.push(object[property]);
    return values;
  },

  clone: function(object) {
    return Object.extend({ }, object);
  },

  isElement: function(object) {
    return object && object.nodeType == 1;
  },

  isArray: function(object) {
    return object != null && typeof object == "object" &&
      'splice' in object && 'join' in object;
  },

  isHash: function(object) {
    return object instanceof Hash;
  },

  isFunction: function(object) {
    return typeof object == "function";
  },

  isString: function(object) {
    return typeof object == "string";
  },

  isNumber: function(object) {
    return typeof object == "number";
  },

  isUndefined: function(object) {
    return typeof object == "undefined";
  }
});

Object.extend(Function.prototype, {
  argumentNames: function() {
    var names = this.toString().match(/^[\s\(]*function[^(]*\((.*?)\)/)[1].split(",").invoke("strip");
    return names.length == 1 && !names[0] ? [] : names;
  },

  bind: function() {
    if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this;
    var __method = this, args = $A(arguments), object = args.shift();
    return function() {
      return __method.apply(object, args.concat($A(arguments)));
    }
  },

  bindAsEventListener: function() {
    var __method = this, args = $A(arguments), object = args.shift();
    return function(event) {
      return __method.apply(object, [event || window.event].concat(args));
    }
  },

  curry: function() {
    if (!arguments.length) return this;
    var __method = this, args = $A(arguments);
    return function() {
      return __method.apply(this, args.concat($A(arguments)));
    }
  },

  delay: function() {
    var __method = this, args = $A(arguments), timeout = args.shift() * 1000;
    return window.setTimeout(function() {
      return __method.apply(__method, args);
    }, timeout);
  },

  wrap: function(wrapper) {
    var __method = this;
    return function() {
      return wrapper.apply(this, [__method.bind(this)].concat($A(arguments)));
    }
  },

  methodize: function() {
    if (this._methodized) return this._methodized;
    var __method = this;
    return this._methodized = function() {
      return __method.apply(null, [this].concat($A(arguments)));
    };
  }
});

Function.prototype.defer = Function.prototype.delay.curry(0.01);

Date.prototype.toJSON = function() {
  return '"' + this.getUTCFullYear() + '-' +
    (this.getUTCMonth() + 1).toPaddedString(2) + '-' +
    this.getUTCDate().toPaddedString(2) + 'T' +
    this.getUTCHours().toPaddedString(2) + ':' +
    this.getUTCMinutes().toPaddedString(2) + ':' +
    this.getUTCSeconds().toPaddedString(2) + 'Z"';
};

var Try = {
  these: function() {
    var returnValue;

    for (var i = 0, length = arguments.length; i < length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) { }
    }

    return returnValue;
  }
};

RegExp.prototype.match = RegExp.prototype.test;

RegExp.escape = function(str) {
  return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};

/*--------------------------------------------------------------------------*/

var PeriodicalExecuter = Class.create({
  initialize: function(callback, frequency) {
    this.callback = callback;
    this.frequency = frequency;
    this.currentlyExecuting = false;

    this.registerCallback();
  },

  registerCallback: function() {
    this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  execute: function() {
    this.callback(this);
  },

  stop: function() {
    if (!this.timer) return;
    clearInterval(this.timer);
    this.timer = null;
  },

  onTimerEvent: function() {
    if (!this.currentlyExecuting) {
      try {
        this.currentlyExecuting = true;
        this.execute();
      } finally {
        this.currentlyExecuting = false;
      }
    }
  }
});
Object.extend(String, {
  interpret: function(value) {
    return value == null ? '' : String(value);
  },
  specialChar: {
    '\b': '\\b',
    '\t': '\\t',
    '\n': '\\n',
    '\f': '\\f',
    '\r': '\\r',
    '\\': '\\\\'
  }
});

Object.extend(String.prototype, {
  gsub: function(pattern, replacement) {
    var result = '', source = this, match;
    replacement = arguments.callee.prepareReplacement(replacement);

    while (source.length > 0) {
      if (match = source.match(pattern)) {
        result += source.slice(0, match.index);
        result += String.interpret(replacement(match));
        source  = source.slice(match.index + match[0].length);
      } else {
        result += source, source = '';
      }
    }
    return result;
  },

  sub: function(pattern, replacement, count) {
    replacement = this.gsub.prepareReplacement(replacement);
    count = Object.isUndefined(count) ? 1 : count;

    return this.gsub(pattern, function(match) {
      if (--count < 0) return match[0];
      return replacement(match);
    });
  },

  scan: function(pattern, iterator) {
    this.gsub(pattern, iterator);
    return String(this);
  },

  truncate: function(length, truncation) {
    length = length || 30;
    truncation = Object.isUndefined(truncation) ? '...' : truncation;
    return this.length > length ?
      this.slice(0, length - truncation.length) + truncation : String(this);
  },

  strip: function() {
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
  },

  stripTags: function() {
    return this.replace(/<\/?[^>]+>/gi, '');
  },

  stripScripts: function() {
    return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
  },

  extractScripts: function() {
    var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
    var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
    return (this.match(matchAll) || []).map(function(scriptTag) {
      return (scriptTag.match(matchOne) || ['', ''])[1];
    });
  },

  evalScripts: function() {
    return this.extractScripts().map(function(script) { return eval(script) });
  },

  escapeHTML: function() {
    var self = arguments.callee;
    self.text.data = this;
    return self.div.innerHTML;
  },

  unescapeHTML: function() {
    var div = new Element('div');
    div.innerHTML = this.stripTags();
    return div.childNodes[0] ? (div.childNodes.length > 1 ?
      $A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue }) :
      div.childNodes[0].nodeValue) : '';
  },

  toQueryParams: function(separator) {
    var match = this.strip().match(/([^?#]*)(#.*)?$/);
    if (!match) return { };

    return match[1].split(separator || '&').inject({ }, function(hash, pair) {
      if ((pair = pair.split('='))[0]) {
        var key = decodeURIComponent(pair.shift());
        var value = pair.length > 1 ? pair.join('=') : pair[0];
        if (value != undefined) value = decodeURIComponent(value);

        if (key in hash) {
          if (!Object.isArray(hash[key])) hash[key] = [hash[key]];
          hash[key].push(value);
        }
        else hash[key] = value;
      }
      return hash;
    });
  },

  toArray: function() {
    return this.split('');
  },

  succ: function() {
    return this.slice(0, this.length - 1) +
      String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
  },

  times: function(count) {
    return count < 1 ? '' : new Array(count + 1).join(this);
  },

  camelize: function() {
    var parts = this.split('-'), len = parts.length;
    if (len == 1) return parts[0];

    var camelized = this.charAt(0) == '-'
      ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
      : parts[0];

    for (var i = 1; i < len; i++)
      camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);

    return camelized;
  },

  capitalize: function() {
    return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
  },

  underscore: function() {
    return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
  },

  dasherize: function() {
    return this.gsub(/_/,'-');
  },

  inspect: function(useDoubleQuotes) {
    var escapedString = this.gsub(/[\x00-\x1f\\]/, function(match) {
      var character = String.specialChar[match[0]];
      return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16);
    });
    if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
    return "'" + escapedString.replace(/'/g, '\\\'') + "'";
  },

  toJSON: function() {
    return this.inspect(true);
  },

  unfilterJSON: function(filter) {
    return this.sub(filter || Prototype.JSONFilter, '#{1}');
  },

  isJSON: function() {
    var str = this;
    if (str.blank()) return false;
    str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
    return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
  },

  evalJSON: function(sanitize) {
    var json = this.unfilterJSON();
    try {
      if (!sanitize || json.isJSON()) return eval('(' + json + ')');
    } catch (e) { }
    throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
  },

  include: function(pattern) {
    return this.indexOf(pattern) > -1;
  },

  startsWith: function(pattern) {
    return this.indexOf(pattern) === 0;
  },

  endsWith: function(pattern) {
    var d = this.length - pattern.length;
    return d >= 0 && this.lastIndexOf(pattern) === d;
  },

  empty: function() {
    return this == '';
  },

  blank: function() {
    return /^\s*$/.test(this);
  },

  interpolate: function(object, pattern) {
    return new Template(this, pattern).evaluate(object);
  }
});

if (Prototype.Browser.WebKit || Prototype.Browser.IE) Object.extend(String.prototype, {
  escapeHTML: function() {
    return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
  },
  unescapeHTML: function() {
    return this.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
  }
});

String.prototype.gsub.prepareReplacement = function(replacement) {
  if (Object.isFunction(replacement)) return replacement;
  var template = new Template(replacement);
  return function(match) { return template.evaluate(match) };
};

String.prototype.parseQuery = String.prototype.toQueryParams;

Object.extend(String.prototype.escapeHTML, {
  div:  document.createElement('div'),
  text: document.createTextNode('')
});

with (String.prototype.escapeHTML) div.appendChild(text);

var Template = Class.create({
  initialize: function(template, pattern) {
    this.template = template.toString();
    this.pattern = pattern || Template.Pattern;
  },

  evaluate: function(object) {
    if (Object.isFunction(object.toTemplateReplacements))
      object = object.toTemplateReplacements();

    return this.template.gsub(this.pattern, function(match) {
      if (object == null) return '';

      var before = match[1] || '';
      if (before == '\\') return match[2];

      var ctx = object, expr = match[3];
      var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;
      match = pattern.exec(expr);
      if (match == null) return before;

      while (match != null) {
        var comp = match[1].startsWith('[') ? match[2].gsub('\\\\]', ']') : match[1];
        ctx = ctx[comp];
        if (null == ctx || '' == match[3]) break;
        expr = expr.substring('[' == match[3] ? match[1].length : match[0].length);
        match = pattern.exec(expr);
      }

      return before + String.interpret(ctx);
    });
  }
});
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;

var $break = { };

var Enumerable = {
  each: function(iterator, context) {
    var index = 0;
    iterator = iterator.bind(context);
    try {
      this._each(function(value) {
        iterator(value, index++);
      });
    } catch (e) {
      if (e != $break) throw e;
    }
    return this;
  },

  eachSlice: function(number, iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var index = -number, slices = [], array = this.toArray();
    while ((index += number) < array.length)
      slices.push(array.slice(index, index+number));
    return slices.collect(iterator, context);
  },

  all: function(iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var result = true;
    this.each(function(value, index) {
      result = result && !!iterator(value, index);
      if (!result) throw $break;
    });
    return result;
  },

  any: function(iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var result = false;
    this.each(function(value, index) {
      if (result = !!iterator(value, index))
        throw $break;
    });
    return result;
  },

  collect: function(iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var results = [];
    this.each(function(value, index) {
      results.push(iterator(value, index));
    });
    return results;
  },

  detect: function(iterator, context) {
    iterator = iterator.bind(context);
    var result;
    this.each(function(value, index) {
      if (iterator(value, index)) {
        result = value;
        throw $break;
      }
    });
    return result;
  },

  findAll: function(iterator, context) {
    iterator = iterator.bind(context);
    var results = [];
    this.each(function(value, index) {
      if (iterator(value, index))
        results.push(value);
    });
    return results;
  },

  grep: function(filter, iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var results = [];

    if (Object.isString(filter))
      filter = new RegExp(filter);

    this.each(function(value, index) {
      if (filter.match(value))
        results.push(iterator(value, index));
    });
    return results;
  },

  include: function(object) {
    if (Object.isFunction(this.indexOf))
      if (this.indexOf(object) != -1) return true;

    var found = false;
    this.each(function(value) {
      if (value == object) {
        found = true;
        throw $break;
      }
    });
    return found;
  },

  inGroupsOf: function(number, fillWith) {
    fillWith = Object.isUndefined(fillWith) ? null : fillWith;
    return this.eachSlice(number, function(slice) {
      while(slice.length < number) slice.push(fillWith);
      return slice;
    });
  },

  inject: function(memo, iterator, context) {
    iterator = iterator.bind(context);
    this.each(function(value, index) {
      memo = iterator(memo, value, index);
    });
    return memo;
  },

  invoke: function(method) {
    var args = $A(arguments).slice(1);
    return this.map(function(value) {
      return value[method].apply(value, args);
    });
  },

  max: function(iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var result;
    this.each(function(value, index) {
      value = iterator(value, index);
      if (result == null || value >= result)
        result = value;
    });
    return result;
  },

  min: function(iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var result;
    this.each(function(value, index) {
      value = iterator(value, index);
      if (result == null || value < result)
        result = value;
    });
    return result;
  },

  partition: function(iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var trues = [], falses = [];
    this.each(function(value, index) {
      (iterator(value, index) ?
        trues : falses).push(value);
    });
    return [trues, falses];
  },

  pluck: function(property) {
    var results = [];
    this.each(function(value) {
      results.push(value[property]);
    });
    return results;
  },

  reject: function(iterator, context) {
    iterator = iterator.bind(context);
    var results = [];
    this.each(function(value, index) {
      if (!iterator(value, index))
        results.push(value);
    });
    return results;
  },

  sortBy: function(iterator, context) {
    iterator = iterator.bind(context);
    return this.map(function(value, index) {
      return {value: value, criteria: iterator(value, index)};
    }).sort(function(left, right) {
      var a = left.criteria, b = right.criteria;
      return a < b ? -1 : a > b ? 1 : 0;
    }).pluck('value');
  },

  toArray: function() {
    return this.map();
  },

  zip: function() {
    var iterator = Prototype.K, args = $A(arguments);
    if (Object.isFunction(args.last()))
      iterator = args.pop();

    var collections = [this].concat(args).map($A);
    return this.map(function(value, index) {
      return iterator(collections.pluck(index));
    });
  },

  size: function() {
    return this.toArray().length;
  },

  inspect: function() {
    return '#<Enumerable:' + this.toArray().inspect() + '>';
  }
};

Object.extend(Enumerable, {
  map:     Enumerable.collect,
  find:    Enumerable.detect,
  select:  Enumerable.findAll,
  filter:  Enumerable.findAll,
  member:  Enumerable.include,
  entries: Enumerable.toArray,
  every:   Enumerable.all,
  some:    Enumerable.any
});
function $A(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) return iterable.toArray();
  var length = iterable.length || 0, results = new Array(length);
  while (length--) results[length] = iterable[length];
  return results;
}

if (Prototype.Browser.WebKit) {
  $A = function(iterable) {
    if (!iterable) return [];
    if (!(Object.isFunction(iterable) && iterable == '[object NodeList]') &&
        iterable.toArray) return iterable.toArray();
    var length = iterable.length || 0, results = new Array(length);
    while (length--) results[length] = iterable[length];
    return results;
  };
}

Array.from = $A;

Object.extend(Array.prototype, Enumerable);

if (!Array.prototype._reverse) Array.prototype._reverse = Array.prototype.reverse;

Object.extend(Array.prototype, {
  _each: function(iterator) {
    for (var i = 0, length = this.length; i < length; i++)
      iterator(this[i]);
  },

  clear: function() {
    this.length = 0;
    return this;
  },

  first: function() {
    return this[0];
  },

  last: function() {
    return this[this.length - 1];
  },

  compact: function() {
    return this.select(function(value) {
      return value != null;
    });
  },

  flatten: function() {
    return this.inject([], function(array, value) {
      return array.concat(Object.isArray(value) ?
        value.flatten() : [value]);
    });
  },

  without: function() {
    var values = $A(arguments);
    return this.select(function(value) {
      return !values.include(value);
    });
  },

  reverse: function(inline) {
    return (inline !== false ? this : this.toArray())._reverse();
  },

  reduce: function() {
    return this.length > 1 ? this : this[0];
  },

  uniq: function(sorted) {
    return this.inject([], function(array, value, index) {
      if (0 == index || (sorted ? array.last() != value : !array.include(value)))
        array.push(value);
      return array;
    });
  },

  intersect: function(array) {
    return this.uniq().findAll(function(item) {
      return array.detect(function(value) { return item === value });
    });
  },

  clone: function() {
    return [].concat(this);
  },

  size: function() {
    return this.length;
  },

  inspect: function() {
    return '[' + this.map(Object.inspect).join(', ') + ']';
  },

  toJSON: function() {
    var results = [];
    this.each(function(object) {
      var value = Object.toJSON(object);
      if (!Object.isUndefined(value)) results.push(value);
    });
    return '[' + results.join(', ') + ']';
  }
});

// use native browser JS 1.6 implementation if available
if (Object.isFunction(Array.prototype.forEach))
  Array.prototype._each = Array.prototype.forEach;

if (!Array.prototype.indexOf) Array.prototype.indexOf = function(item, i) {
  i || (i = 0);
  var length = this.length;
  if (i < 0) i = length + i;
  for (; i < length; i++)
    if (this[i] === item) return i;
  return -1;
};

if (!Array.prototype.lastIndexOf) Array.prototype.lastIndexOf = function(item, i) {
  i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1;
  var n = this.slice(0, i).reverse().indexOf(item);
  return (n < 0) ? n : i - n - 1;
};

Array.prototype.toArray = Array.prototype.clone;

function $w(string) {
  if (!Object.isString(string)) return [];
  string = string.strip();
  return string ? string.split(/\s+/) : [];
}

if (Prototype.Browser.Opera){
  Array.prototype.concat = function() {
    var array = [];
    for (var i = 0, length = this.length; i < length; i++) array.push(this[i]);
    for (var i = 0, length = arguments.length; i < length; i++) {
      if (Object.isArray(arguments[i])) {
        for (var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
          array.push(arguments[i][j]);
      } else {
        array.push(arguments[i]);
      }
    }
    return array;
  };
}
Object.extend(Number.prototype, {
  toColorPart: function() {
    return this.toPaddedString(2, 16);
  },

  succ: function() {
    return this + 1;
  },

  times: function(iterator) {
    $R(0, this, true).each(iterator);
    return this;
  },

  toPaddedString: function(length, radix) {
    var string = this.toString(radix || 10);
    return '0'.times(length - string.length) + string;
  },

  toJSON: function() {
    return isFinite(this) ? this.toString() : 'null';
  }
});

$w('abs round ceil floor').each(function(method){
  Number.prototype[method] = Math[method].methodize();
});
function $H(object) {
  return new Hash(object);
};

var Hash = Class.create(Enumerable, (function() {

  function toQueryPair(key, value) {
    if (Object.isUndefined(value)) return key;
    return key + '=' + encodeURIComponent(String.interpret(value));
  }

  return {
    initialize: function(object) {
      this._object = Object.isHash(object) ? object.toObject() : Object.clone(object);
    },

    _each: function(iterator) {
      for (var key in this._object) {
        var value = this._object[key], pair = [key, value];
        pair.key = key;
        pair.value = value;
        iterator(pair);
      }
    },

    set: function(key, value) {
      return this._object[key] = value;
    },

    get: function(key) {
      return this._object[key];
    },

    unset: function(key) {
      var value = this._object[key];
      delete this._object[key];
      return value;
    },

    toObject: function() {
      return Object.clone(this._object);
    },

    keys: function() {
      return this.pluck('key');
    },

    values: function() {
      return this.pluck('value');
    },

    index: function(value) {
      var match = this.detect(function(pair) {
        return pair.value === value;
      });
      return match && match.key;
    },

    merge: function(object) {
      return this.clone().update(object);
    },

    update: function(object) {
      return new Hash(object).inject(this, function(result, pair) {
        result.set(pair.key, pair.value);
        return result;
      });
    },

    toQueryString: function() {
      return this.map(function(pair) {
        var key = encodeURIComponent(pair.key), values = pair.value;

        if (values && typeof values == 'object') {
          if (Object.isArray(values))
            return values.map(toQueryPair.curry(key)).join('&');
        }
        return toQueryPair(key, values);
      }).join('&');
    },

    inspect: function() {
      return '#<Hash:{' + this.map(function(pair) {
        return pair.map(Object.inspect).join(': ');
      }).join(', ') + '}>';
    },

    toJSON: function() {
      return Object.toJSON(this.toObject());
    },

    clone: function() {
      return new Hash(this);
    }
  }
})());

Hash.prototype.toTemplateReplacements = Hash.prototype.toObject;
Hash.from = $H;
var ObjectRange = Class.create(Enumerable, {
  initialize: function(start, end, exclusive) {
    this.start = start;
    this.end = end;
    this.exclusive = exclusive;
  },

  _each: function(iterator) {
    var value = this.start;
    while (this.include(value)) {
      iterator(value);
      value = value.succ();
    }
  },

  include: function(value) {
    if (value < this.start)
      return false;
    if (this.exclusive)
      return value < this.end;
    return value <= this.end;
  }
});

var $R = function(start, end, exclusive) {
  return new ObjectRange(start, end, exclusive);
};

var Ajax = {
  getTransport: function() {
    return Try.these(
      function() {return new XMLHttpRequest()},
      function() {return new ActiveXObject('Msxml2.XMLHTTP')},
      function() {return new ActiveXObject('Microsoft.XMLHTTP')}
    ) || false;
  },

  activeRequestCount: 0
};

Ajax.Responders = {
  responders: [],

  _each: function(iterator) {
    this.responders._each(iterator);
  },

  register: function(responder) {
    if (!this.include(responder))
      this.responders.push(responder);
  },

  unregister: function(responder) {
    this.responders = this.responders.without(responder);
  },

  dispatch: function(callback, request, transport, json) {
    this.each(function(responder) {
      if (Object.isFunction(responder[callback])) {
        try {
          responder[callback].apply(responder, [request, transport, json]);
        } catch (e) { }
      }
    });
  }
};

Object.extend(Ajax.Responders, Enumerable);

Ajax.Responders.register({
  onCreate:   function() { Ajax.activeRequestCount++ },
  onComplete: function() { Ajax.activeRequestCount-- }
});

Ajax.Base = Class.create({
  initialize: function(options) {
    this.options = {
      method:       'post',
      asynchronous: true,
      contentType:  'application/x-www-form-urlencoded',
      encoding:     'UTF-8',
      parameters:   '',
      evalJSON:     true,
      evalJS:       true
    };
    Object.extend(this.options, options || { });

    this.options.method = this.options.method.toLowerCase();

    if (Object.isString(this.options.parameters))
      this.options.parameters = this.options.parameters.toQueryParams();
    else if (Object.isHash(this.options.parameters))
      this.options.parameters = this.options.parameters.toObject();
  }
});

Ajax.Request = Class.create(Ajax.Base, {
  _complete: false,

  initialize: function($super, url, options) {
    $super(options);
    this.transport = Ajax.getTransport();
    this.request(url);
  },

  request: function(url) {
    this.url = url;
    this.method = this.options.method;
    var params = Object.clone(this.options.parameters);

    if (!['get', 'post'].include(this.method)) {
      // simulate other verbs over post
      params['_method'] = this.method;
      this.method = 'post';
    }

    this.parameters = params;

    if (params = Object.toQueryString(params)) {
      // when GET, append parameters to URL
      if (this.method == 'get')
        this.url += (this.url.include('?') ? '&' : '?') + params;
      else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent))
        params += '&_=';
    }

    try {
      var response = new Ajax.Response(this);
      if (this.options.onCreate) this.options.onCreate(response);
      Ajax.Responders.dispatch('onCreate', this, response);

      this.transport.open(this.method.toUpperCase(), this.url,
        this.options.asynchronous);

      if (this.options.asynchronous) this.respondToReadyState.bind(this).defer(1);

      this.transport.onreadystatechange = this.onStateChange.bind(this);
      this.setRequestHeaders();

      this.body = this.method == 'post' ? (this.options.postBody || params) : null;
      this.transport.send(this.body);

      /* Force Firefox to handle ready state 4 for synchronous requests */
      if (!this.options.asynchronous && this.transport.overrideMimeType)
        this.onStateChange();

    }
    catch (e) {
      this.dispatchException(e);
    }
  },

  onStateChange: function() {
    var readyState = this.transport.readyState;
    if (readyState > 1 && !((readyState == 4) && this._complete))
      this.respondToReadyState(this.transport.readyState);
  },

  setRequestHeaders: function() {
    var headers = {
      'X-Requested-With': 'XMLHttpRequest',
      'X-Prototype-Version': Prototype.Version,
      'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
    };

    if (this.method == 'post') {
      headers['Content-type'] = this.options.contentType +
        (this.options.encoding ? '; charset=' + this.options.encoding : '');

      /* Force "Connection: close" for older Mozilla browsers to work
       * around a bug where XMLHttpRequest sends an incorrect
       * Content-length header. See Mozilla Bugzilla #246651.
       */
      if (this.transport.overrideMimeType &&
          (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
            headers['Connection'] = 'close';
    }

    // user-defined headers
    if (typeof this.options.requestHeaders == 'object') {
      var extras = this.options.requestHeaders;

      if (Object.isFunction(extras.push))
        for (var i = 0, length = extras.length; i < length; i += 2)
          headers[extras[i]] = extras[i+1];
      else
        $H(extras).each(function(pair) { headers[pair.key] = pair.value });
    }

    for (var name in headers)
      this.transport.setRequestHeader(name, headers[name]);
  },

  success: function() {
    var status = this.getStatus();
    return !status || (status >= 200 && status < 300);
  },

  getStatus: function() {
    try {
      return this.transport.status || 0;
    } catch (e) { return 0 }
  },

  respondToReadyState: function(readyState) {
    var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this);

    if (state == 'Complete') {
      try {
        this._complete = true;
        (this.options['on' + response.status]
         || this.options['on' + (this.success() ? 'Success' : 'Failure')]
         || Prototype.emptyFunction)(response, response.headerJSON);
      } catch (e) {
        this.dispatchException(e);
      }

      var contentType = response.getHeader('Content-type');
      if (this.options.evalJS == 'force'
          || (this.options.evalJS && this.isSameOrigin() && contentType
          && contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)))
        this.evalResponse();
    }

    try {
      (this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON);
      Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON);
    } catch (e) {
      this.dispatchException(e);
    }

    if (state == 'Complete') {
      // avoid memory leak in MSIE: clean up
      this.transport.onreadystatechange = Prototype.emptyFunction;
    }
  },

  isSameOrigin: function() {
    var m = this.url.match(/^\s*https?:\/\/[^\/]*/);
    return !m || (m[0] == '#{protocol}//#{domain}#{port}'.interpolate({
      protocol: location.protocol,
      domain: document.domain,
      port: location.port ? ':' + location.port : ''
    }));
  },

  getHeader: function(name) {
    try {
      return this.transport.getResponseHeader(name) || null;
    } catch (e) { return null }
  },

  evalResponse: function() {
    try {
      return eval((this.transport.responseText || '').unfilterJSON());
    } catch (e) {
      this.dispatchException(e);
    }
  },

  dispatchException: function(exception) {
    (this.options.onException || Prototype.emptyFunction)(this, exception);
    Ajax.Responders.dispatch('onException', this, exception);
  }
});

Ajax.Request.Events =
  ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];

Ajax.Response = Class.create({
  initialize: function(request){
    this.request = request;
    var transport  = this.transport  = request.transport,
        readyState = this.readyState = transport.readyState;

    if((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) {
      this.status       = this.getStatus();
      this.statusText   = this.getStatusText();
      this.responseText = String.interpret(transport.responseText);
      this.headerJSON   = this._getHeaderJSON();
    }

    if(readyState == 4) {
      var xml = transport.responseXML;
      this.responseXML  = Object.isUndefined(xml) ? null : xml;
      this.responseJSON = this._getResponseJSON();
    }
  },

  status:      0,
  statusText: '',

  getStatus: Ajax.Request.prototype.getStatus,

  getStatusText: function() {
    try {
      return this.transport.statusText || '';
    } catch (e) { return '' }
  },

  getHeader: Ajax.Request.prototype.getHeader,

  getAllHeaders: function() {
    try {
      return this.getAllResponseHeaders();
    } catch (e) { return null }
  },

  getResponseHeader: function(name) {
    return this.transport.getResponseHeader(name);
  },

  getAllResponseHeaders: function() {
    return this.transport.getAllResponseHeaders();
  },

  _getHeaderJSON: function() {
    var json = this.getHeader('X-JSON');
    if (!json) return null;
    json = decodeURIComponent(escape(json));
    try {
      return json.evalJSON(this.request.options.sanitizeJSON ||
        !this.request.isSameOrigin());
    } catch (e) {
      this.request.dispatchException(e);
    }
  },

  _getResponseJSON: function() {
    var options = this.request.options;
    if (!options.evalJSON || (options.evalJSON != 'force' &&
      !(this.getHeader('Content-type') || '').include('application/json')) ||
        this.responseText.blank())
          return null;
    try {
      return this.responseText.evalJSON(options.sanitizeJSON ||
        !this.request.isSameOrigin());
    } catch (e) {
      this.request.dispatchException(e);
    }
  }
});

Ajax.Updater = Class.create(Ajax.Request, {
  initialize: function($super, container, url, options) {
    this.container = {
      success: (container.success || container),
      failure: (container.failure || (container.success ? null : container))
    };

    options = Object.clone(options);
    var onComplete = options.onComplete;
    options.onComplete = (function(response, json) {
      this.updateContent(response.responseText);
      if (Object.isFunction(onComplete)) onComplete(response, json);
    }).bind(this);

    $super(url, options);
  },

  updateContent: function(responseText) {
    var receiver = this.container[this.success() ? 'success' : 'failure'],
        options = this.options;

    if (!options.evalScripts) responseText = responseText.stripScripts();

    if (receiver = $(receiver)) {
      if (options.insertion) {
        if (Object.isString(options.insertion)) {
          var insertion = { }; insertion[options.insertion] = responseText;
          receiver.insert(insertion);
        }
        else options.insertion(receiver, responseText);
      }
      else receiver.update(responseText);
    }
  }
});

Ajax.PeriodicalUpdater = Class.create(Ajax.Base, {
  initialize: function($super, container, url, options) {
    $super(options);
    this.onComplete = this.options.onComplete;

    this.frequency = (this.options.frequency || 2);
    this.decay = (this.options.decay || 1);

    this.updater = { };
    this.container = container;
    this.url = url;

    this.start();
  },

  start: function() {
    this.options.onComplete = this.updateComplete.bind(this);
    this.onTimerEvent();
  },

  stop: function() {
    this.updater.options.onComplete = undefined;
    clearTimeout(this.timer);
    (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
  },

  updateComplete: function(response) {
    if (this.options.decay) {
      this.decay = (response.responseText == this.lastText ?
        this.decay * this.options.decay : 1);

      this.lastText = response.responseText;
    }
    this.timer = this.onTimerEvent.bind(this).delay(this.decay * this.frequency);
  },

  onTimerEvent: function() {
    this.updater = new Ajax.Updater(this.container, this.url, this.options);
  }
});
function $(element) {
  if (arguments.length > 1) {
    for (var i = 0, elements = [], length = arguments.length; i < length; i++)
      elements.push($(arguments[i]));
    return elements;
  }
  if (Object.isString(element))
    element = document.getElementById(element);
  return Element.extend(element);
}

if (Prototype.BrowserFeatures.XPath) {
  document._getElementsByXPath = function(expression, parentElement) {
    var results = [];
    var query = document.evaluate(expression, $(parentElement) || document,
      null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    for (var i = 0, length = query.snapshotLength; i < length; i++)
      results.push(Element.extend(query.snapshotItem(i)));
    return results;
  };
}

/*--------------------------------------------------------------------------*/

if (!window.Node) var Node = { };

if (!Node.ELEMENT_NODE) {
  // DOM level 2 ECMAScript Language Binding
  Object.extend(Node, {
    ELEMENT_NODE: 1,
    ATTRIBUTE_NODE: 2,
    TEXT_NODE: 3,
    CDATA_SECTION_NODE: 4,
    ENTITY_REFERENCE_NODE: 5,
    ENTITY_NODE: 6,
    PROCESSING_INSTRUCTION_NODE: 7,
    COMMENT_NODE: 8,
    DOCUMENT_NODE: 9,
    DOCUMENT_TYPE_NODE: 10,
    DOCUMENT_FRAGMENT_NODE: 11,
    NOTATION_NODE: 12
  });
}

(function() {
  var element = this.Element;
  this.Element = function(tagName, attributes) {
    attributes = attributes || { };
    tagName = tagName.toLowerCase();
    var cache = Element.cache;
    if (Prototype.Browser.IE && attributes.name) {
      tagName = '<' + tagName + ' name="' + attributes.name + '">';
      delete attributes.name;
      return Element.writeAttribute(document.createElement(tagName), attributes);
    }
    if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName));
    return Element.writeAttribute(cache[tagName].cloneNode(false), attributes);
  };
  Object.extend(this.Element, element || { });
}).call(window);

Element.cache = { };

Element.Methods = {
  visible: function(element) {
    return $(element).style.display != 'none';
  },

  toggle: function(element) {
    element = $(element);
    Element[Element.visible(element) ? 'hide' : 'show'](element);
    return element;
  },

  hide: function(element) {
    $(element).style.display = 'none';
    return element;
  },

  show: function(element) {
    $(element).style.display = '';
    return element;
  },

  remove: function(element) {
    element = $(element);
    element.parentNode.removeChild(element);
    return element;
  },

  update: function(element, content) {
    element = $(element);
    if (content && content.toElement) content = content.toElement();
    if (Object.isElement(content)) return element.update().insert(content);
    content = Object.toHTML(content);
    element.innerHTML = content.stripScripts();
    content.evalScripts.bind(content).defer();
    return element;
  },

  replace: function(element, content) {
    element = $(element);
    if (content && content.toElement) content = content.toElement();
    else if (!Object.isElement(content)) {
      content = Object.toHTML(content);
      var range = element.ownerDocument.createRange();
      range.selectNode(element);
      content.evalScripts.bind(content).defer();
      content = range.createContextualFragment(content.stripScripts());
    }
    element.parentNode.replaceChild(content, element);
    return element;
  },

  insert: function(element, insertions) {
    element = $(element);

    if (Object.isString(insertions) || Object.isNumber(insertions) ||
        Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML)))
          insertions = {bottom:insertions};

    var content, insert, tagName, childNodes;

    for (var position in insertions) {
      content  = insertions[position];
      position = position.toLowerCase();
      insert = Element._insertionTranslations[position];

      if (content && content.toElement) content = content.toElement();
      if (Object.isElement(content)) {
        insert(element, content);
        continue;
      }

      content = Object.toHTML(content);

      tagName = ((position == 'before' || position == 'after')
        ? element.parentNode : element).tagName.toUpperCase();

      childNodes = Element._getContentFromAnonymousElement(tagName, content.stripScripts());

      if (position == 'top' || position == 'after') childNodes.reverse();
      childNodes.each(insert.curry(element));

      content.evalScripts.bind(content).defer();
    }

    return element;
  },

  wrap: function(element, wrapper, attributes) {
    element = $(element);
    if (Object.isElement(wrapper))
      $(wrapper).writeAttribute(attributes || { });
    else if (Object.isString(wrapper)) wrapper = new Element(wrapper, attributes);
    else wrapper = new Element('div', wrapper);
    if (element.parentNode)
      element.parentNode.replaceChild(wrapper, element);
    wrapper.appendChild(element);
    return wrapper;
  },

  inspect: function(element) {
    element = $(element);
    var result = '<' + element.tagName.toLowerCase();
    $H({'id': 'id', 'className': 'class'}).each(function(pair) {
      var property = pair.first(), attribute = pair.last();
      var value = (element[property] || '').toString();
      if (value) result += ' ' + attribute + '=' + value.inspect(true);
    });
    return result + '>';
  },

  recursivelyCollect: function(element, property) {
    element = $(element);
    var elements = [];
    while (element = element[property])
      if (element.nodeType == 1)
        elements.push(Element.extend(element));
    return elements;
  },

  ancestors: function(element) {
    return $(element).recursivelyCollect('parentNode');
  },

  descendants: function(element) {
    return $(element).select("*");
  },

  firstDescendant: function(element) {
    element = $(element).firstChild;
    while (element && element.nodeType != 1) element = element.nextSibling;
    return $(element);
  },

  immediateDescendants: function(element) {
    if (!(element = $(element).firstChild)) return [];
    while (element && element.nodeType != 1) element = element.nextSibling;
    if (element) return [element].concat($(element).nextSiblings());
    return [];
  },

  previousSiblings: function(element) {
    return $(element).recursivelyCollect('previousSibling');
  },

  nextSiblings: function(element) {
    return $(element).recursivelyCollect('nextSibling');
  },

  siblings: function(element) {
    element = $(element);
    return element.previousSiblings().reverse().concat(element.nextSiblings());
  },

  match: function(element, selector) {
    if (Object.isString(selector))
      selector = new Selector(selector);
    return selector.match($(element));
  },

  up: function(element, expression, index) {
    element = $(element);
    if (arguments.length == 1) return $(element.parentNode);
    var ancestors = element.ancestors();
    return Object.isNumber(expression) ? ancestors[expression] :
      Selector.findElement(ancestors, expression, index);
  },

  down: function(element, expression, index) {
    element = $(element);
    if (arguments.length == 1) return element.firstDescendant();
    return Object.isNumber(expression) ? element.descendants()[expression] :
      element.select(expression)[index || 0];
  },

  previous: function(element, expression, index) {
    element = $(element);
    if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element));
    var previousSiblings = element.previousSiblings();
    return Object.isNumber(expression) ? previousSiblings[expression] :
      Selector.findElement(previousSiblings, expression, index);
  },

  next: function(element, expression, index) {
    element = $(element);
    if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element));
    var nextSiblings = element.nextSiblings();
    return Object.isNumber(expression) ? nextSiblings[expression] :
      Selector.findElement(nextSiblings, expression, index);
  },

  select: function() {
    var args = $A(arguments), element = $(args.shift());
    return Selector.findChildElements(element, args);
  },

  adjacent: function() {
    var args = $A(arguments), element = $(args.shift());
    return Selector.findChildElements(element.parentNode, args).without(element);
  },

  identify: function(element) {
    element = $(element);
    var id = element.readAttribute('id'), self = arguments.callee;
    if (id) return id;
    do { id = 'anonymous_element_' + self.counter++ } while ($(id));
    element.writeAttribute('id', id);
    return id;
  },

  readAttribute: function(element, name) {
    element = $(element);
    if (Prototype.Browser.IE) {
      var t = Element._attributeTranslations.read;
      if (t.values[name]) return t.values[name](element, name);
      if (t.names[name]) name = t.names[name];
      if (name.include(':')) {
        return (!element.attributes || !element.attributes[name]) ? null :
         element.attributes[name].value;
      }
    }
    return element.getAttribute(name);
  },

  writeAttribute: function(element, name, value) {
    element = $(element);
    var attributes = { }, t = Element._attributeTranslations.write;

    if (typeof name == 'object') attributes = name;
    else attributes[name] = Object.isUndefined(value) ? true : value;

    for (var attr in attributes) {
      name = t.names[attr] || attr;
      value = attributes[attr];
      if (t.values[attr]) name = t.values[attr](element, value);
      if (value === false || value === null)
        element.removeAttribute(name);
      else if (value === true)
        element.setAttribute(name, name);
      else element.setAttribute(name, value);
    }
    return element;
  },

  getHeight: function(element) {
    return $(element).getDimensions().height;
  },

  getWidth: function(element) {
    return $(element).getDimensions().width;
  },

  classNames: function(element) {
    return new Element.ClassNames(element);
  },

  hasClassName: function(element, className) {
    if (!(element = $(element))) return;
    var elementClassName = element.className;
    return (elementClassName.length > 0 && (elementClassName == className ||
      new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
  },

  addClassName: function(element, className) {
    if (!(element = $(element))) return;
    if (!element.hasClassName(className))
      element.className += (element.className ? ' ' : '') + className;
    return element;
  },

  removeClassName: function(element, className) {
    if (!(element = $(element))) return;
    element.className = element.className.replace(
      new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ').strip();
    return element;
  },

  toggleClassName: function(element, className) {
    if (!(element = $(element))) return;
    return element[element.hasClassName(className) ?
      'removeClassName' : 'addClassName'](className);
  },

  // removes whitespace-only text node children
  cleanWhitespace: function(element) {
    element = $(element);
    var node = element.firstChild;
    while (node) {
      var nextNode = node.nextSibling;
      if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
        element.removeChild(node);
      node = nextNode;
    }
    return element;
  },

  empty: function(element) {
    return $(element).innerHTML.blank();
  },

  descendantOf: function(element, ancestor) {
    element = $(element), ancestor = $(ancestor);
    var originalAncestor = ancestor;

    if (element.compareDocumentPosition)
      return (element.compareDocumentPosition(ancestor) & 8) === 8;

    if (element.sourceIndex && !Prototype.Browser.Opera) {
      var e = element.sourceIndex, a = ancestor.sourceIndex,
       nextAncestor = ancestor.nextSibling;
      if (!nextAncestor) {
        do { ancestor = ancestor.parentNode; }
        while (!(nextAncestor = ancestor.nextSibling) && ancestor.parentNode);
      }
      if (nextAncestor && nextAncestor.sourceIndex)
       return (e > a && e < nextAncestor.sourceIndex);
    }

    while (element = element.parentNode)
      if (element == originalAncestor) return true;
    return false;
  },

  scrollTo: function(element) {
    element = $(element);
    var pos = element.cumulativeOffset();
    window.scrollTo(pos[0], pos[1]);
    return element;
  },

  getStyle: function(element, style) {
    element = $(element);
    style = style == 'float' ? 'cssFloat' : style.camelize();
    var value = element.style[style];
    if (!value) {
      var css = document.defaultView.getComputedStyle(element, null);
      value = css ? css[style] : null;
    }
    if (style == 'opacity') return value ? parseFloat(value) : 1.0;
    return value == 'auto' ? null : value;
  },

  getOpacity: function(element) {
    return $(element).getStyle('opacity');
  },

  setStyle: function(element, styles) {
    element = $(element);
    var elementStyle = element.style, match;
    if (Object.isString(styles)) {
      element.style.cssText += ';' + styles;
      return styles.include('opacity') ?
        element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element;
    }
    for (var property in styles)
      if (property == 'opacity') element.setOpacity(styles[property]);
      else
        elementStyle[(property == 'float' || property == 'cssFloat') ?
          (Object.isUndefined(elementStyle.styleFloat) ? 'cssFloat' : 'styleFloat') :
            property] = styles[property];

    return element;
  },

  setOpacity: function(element, value) {
    element = $(element);
    element.style.opacity = (value == 1 || value === '') ? '' :
      (value < 0.00001) ? 0 : value;
    return element;
  },

  getDimensions: function(element) {
    element = $(element);
    var display = $(element).getStyle('display');
    if (display != 'none' && display != null) // Safari bug
      return {width: element.offsetWidth, height: element.offsetHeight};

    // All *Width and *Height properties give 0 on elements with display none,
    // so enable the element temporarily
    var els = element.style;
    var originalVisibility = els.visibility;
    var originalPosition = els.position;
    var originalDisplay = els.display;
    els.visibility = 'hidden';
    els.position = 'absolute';
    els.display = 'block';
    var originalWidth = element.clientWidth;
    var originalHeight = element.clientHeight;
    els.display = originalDisplay;
    els.position = originalPosition;
    els.visibility = originalVisibility;
    return {width: originalWidth, height: originalHeight};
  },

  makePositioned: function(element) {
    element = $(element);
    var pos = Element.getStyle(element, 'position');
    if (pos == 'static' || !pos) {
      element._madePositioned = true;
      element.style.position = 'relative';
      // Opera returns the offset relative to the positioning context, when an
      // element is position relative but top and left have not been defined
      if (window.opera) {
        element.style.top = 0;
        element.style.left = 0;
      }
    }
    return element;
  },

  undoPositioned: function(element) {
    element = $(element);
    if (element._madePositioned) {
      element._madePositioned = undefined;
      element.style.position =
        element.style.top =
        element.style.left =
        element.style.bottom =
        element.style.right = '';
    }
    return element;
  },

  makeClipping: function(element) {
    element = $(element);
    if (element._overflow) return element;
    element._overflow = Element.getStyle(element, 'overflow') || 'auto';
    if (element._overflow !== 'hidden')
      element.style.overflow = 'hidden';
    return element;
  },

  undoClipping: function(element) {
    element = $(element);
    if (!element._overflow) return element;
    element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
    element._overflow = null;
    return element;
  },

  cumulativeOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
    } while (element);
    return Element._returnOffset(valueL, valueT);
  },

  positionedOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
      if (element) {
        if (element.tagName == 'BODY') break;
        var p = Element.getStyle(element, 'position');
        if (p !== 'static') break;
      }
    } while (element);
    return Element._returnOffset(valueL, valueT);
  },

  absolutize: function(element) {
    element = $(element);
    if (element.getStyle('position') == 'absolute') return;
    // Position.prepare(); // To be done manually by Scripty when it needs it.

    var offsets = element.positionedOffset();
    var top     = offsets[1];
    var left    = offsets[0];
    var width   = element.clientWidth;
    var height  = element.clientHeight;

    element._originalLeft   = left - parseFloat(element.style.left  || 0);
    element._originalTop    = top  - parseFloat(element.style.top || 0);
    element._originalWidth  = element.style.width;
    element._originalHeight = element.style.height;

    element.style.position = 'absolute';
    element.style.top    = top + 'px';
    element.style.left   = left + 'px';
    element.style.width  = width + 'px';
    element.style.height = height + 'px';
    return element;
  },

  relativize: function(element) {
    element = $(element);
    if (element.getStyle('position') == 'relative') return;
    // Position.prepare(); // To be done manually by Scripty when it needs it.

    element.style.position = 'relative';
    var top  = parseFloat(element.style.top  || 0) - (element._originalTop || 0);
    var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);

    element.style.top    = top + 'px';
    element.style.left   = left + 'px';
    element.style.height = element._originalHeight;
    element.style.width  = element._originalWidth;
    return element;
  },

  cumulativeScrollOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.scrollTop  || 0;
      valueL += element.scrollLeft || 0;
      element = element.parentNode;
    } while (element);
    return Element._returnOffset(valueL, valueT);
  },

  getOffsetParent: function(element) {
    if (element.offsetParent) return $(element.offsetParent);
    if (element == document.body) return $(element);

    while ((element = element.parentNode) && element != document.body)
      if (Element.getStyle(element, 'position') != 'static')
        return $(element);

    return $(document.body);
  },

  viewportOffset: function(forElement) {
    var valueT = 0, valueL = 0;

    var element = forElement;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;

      // Safari fix
      if (element.offsetParent == document.body &&
        Element.getStyle(element, 'position') == 'absolute') break;

    } while (element = element.offsetParent);

    element = forElement;
    do {
      if (!Prototype.Browser.Opera || element.tagName == 'BODY') {
        valueT -= element.scrollTop  || 0;
        valueL -= element.scrollLeft || 0;
      }
    } while (element = element.parentNode);

    return Element._returnOffset(valueL, valueT);
  },

  clonePosition: function(element, source) {
    var options = Object.extend({
      setLeft:    true,
      setTop:     true,
      setWidth:   true,
      setHeight:  true,
      offsetTop:  0,
      offsetLeft: 0
    }, arguments[2] || { });

    // find page position of source
    source = $(source);
    var p = source.viewportOffset();

    // find coordinate system to use
    element = $(element);
    var delta = [0, 0];
    var parent = null;
    // delta [0,0] will do fine with position: fixed elements,
    // position:absolute needs offsetParent deltas
    if (Element.getStyle(element, 'position') == 'absolute') {
      parent = element.getOffsetParent();
      delta = parent.viewportOffset();
    }

    // correct by body offsets (fixes Safari)
    if (parent == document.body) {
      delta[0] -= document.body.offsetLeft;
      delta[1] -= document.body.offsetTop;
    }

    // set position
    if (options.setLeft)   element.style.left  = (p[0] - delta[0] + options.offsetLeft) + 'px';
    if (options.setTop)    element.style.top   = (p[1] - delta[1] + options.offsetTop) + 'px';
    if (options.setWidth)  element.style.width = source.offsetWidth + 'px';
    if (options.setHeight) element.style.height = source.offsetHeight + 'px';
    return element;
  }
};

Element.Methods.identify.counter = 1;

Object.extend(Element.Methods, {
  getElementsBySelector: Element.Methods.select,
  childElements: Element.Methods.immediateDescendants
});

Element._attributeTranslations = {
  write: {
    names: {
      className: 'class',
      htmlFor:   'for'
    },
    values: { }
  }
};

if (Prototype.Browser.Opera) {
  Element.Methods.getStyle = Element.Methods.getStyle.wrap(
    function(proceed, element, style) {
      switch (style) {
        case 'left': case 'top': case 'right': case 'bottom':
          if (proceed(element, 'position') === 'static') return null;
        case 'height': case 'width':
          // returns '0px' for hidden elements; we want it to return null
          if (!Element.visible(element)) return null;

          // returns the border-box dimensions rather than the content-box
          // dimensions, so we subtract padding and borders from the value
          var dim = parseInt(proceed(element, style), 10);

          if (dim !== element['offset' + style.capitalize()])
            return dim + 'px';

          var properties;
          if (style === 'height') {
            properties = ['border-top-width', 'padding-top',
             'padding-bottom', 'border-bottom-width'];
          }
          else {
            properties = ['border-left-width', 'padding-left',
             'padding-right', 'border-right-width'];
          }
          return properties.inject(dim, function(memo, property) {
            var val = proceed(element, property);
            return val === null ? memo : memo - parseInt(val, 10);
          }) + 'px';
        default: return proceed(element, style);
      }
    }
  );

  Element.Methods.readAttribute = Element.Methods.readAttribute.wrap(
    function(proceed, element, attribute) {
      if (attribute === 'title') return element.title;
      return proceed(element, attribute);
    }
  );
}

else if (Prototype.Browser.IE) {
  // IE doesn't report offsets correctly for static elements, so we change them
  // to "relative" to get the values, then change them back.
  Element.Methods.getOffsetParent = Element.Methods.getOffsetParent.wrap(
    function(proceed, element) {
      element = $(element);
      var position = element.getStyle('position');
      if (position !== 'static') return proceed(element);
      element.setStyle({ position: 'relative' });
      var value = proceed(element);
      element.setStyle({ position: position });
      return value;
    }
  );

  $w('positionedOffset viewportOffset').each(function(method) {
    Element.Methods[method] = Element.Methods[method].wrap(
      function(proceed, element) {
        element = $(element);
        var position = element.getStyle('position');
        if (position !== 'static') return proceed(element);
        // Trigger hasLayout on the offset parent so that IE6 reports
        // accurate offsetTop and offsetLeft values for position: fixed.
        var offsetParent = element.getOffsetParent();
        if (offsetParent && offsetParent.getStyle('position') === 'fixed')
          offsetParent.setStyle({ zoom: 1 });
        element.setStyle({ position: 'relative' });
        var value = proceed(element);
        element.setStyle({ position: position });
        return value;
      }
    );
  });

  Element.Methods.getStyle = function(element, style) {
    element = $(element);
    style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize();
    var value = element.style[style];
    if (!value && element.currentStyle) value = element.currentStyle[style];

    if (style == 'opacity') {
      if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
        if (value[1]) return parseFloat(value[1]) / 100;
      return 1.0;
    }

    if (value == 'auto') {
      if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none'))
        return element['offset' + style.capitalize()] + 'px';
      return null;
    }
    return value;
  };

  Element.Methods.setOpacity = function(element, value) {
    function stripAlpha(filter){
      return filter.replace(/alpha\([^\)]*\)/gi,'');
    }
    element = $(element);
    var currentStyle = element.currentStyle;
    if ((currentStyle && !currentStyle.hasLayout) ||
      (!currentStyle && element.style.zoom == 'normal'))
        element.style.zoom = 1;

    var filter = element.getStyle('filter'), style = element.style;
    if (value == 1 || value === '') {
      (filter = stripAlpha(filter)) ?
        style.filter = filter : style.removeAttribute('filter');
      return element;
    } else if (value < 0.00001) value = 0;
    style.filter = stripAlpha(filter) +
      'alpha(opacity=' + (value * 100) + ')';
    return element;
  };

  Element._attributeTranslations = {
    read: {
      names: {
        'class': 'className',
        'for':   'htmlFor'
      },
      values: {
        _getAttr: function(element, attribute) {
          return element.getAttribute(attribute, 2);
        },
        _getAttrNode: function(element, attribute) {
          var node = element.getAttributeNode(attribute);
          return node ? node.value : "";
        },
        _getEv: function(element, attribute) {
          attribute = element.getAttribute(attribute);
          return attribute ? attribute.toString().slice(23, -2) : null;
        },
        _flag: function(element, attribute) {
          return $(element).hasAttribute(attribute) ? attribute : null;
        },
        style: function(element) {
          return element.style.cssText.toLowerCase();
        },
        title: function(element) {
          return element.title;
        }
      }
    }
  };

  Element._attributeTranslations.write = {
    names: Object.extend({
      cellpadding: 'cellPadding',
      cellspacing: 'cellSpacing'
    }, Element._attributeTranslations.read.names),
    values: {
      checked: function(element, value) {
        element.checked = !!value;
      },

      style: function(element, value) {
        element.style.cssText = value ? value : '';
      }
    }
  };

  Element._attributeTranslations.has = {};

  $w('colSpan rowSpan vAlign dateTime accessKey tabIndex ' +
      'encType maxLength readOnly longDesc').each(function(attr) {
    Element._attributeTranslations.write.names[attr.toLowerCase()] = attr;
    Element._attributeTranslations.has[attr.toLowerCase()] = attr;
  });

  (function(v) {
    Object.extend(v, {
      href:        v._getAttr,
      src:         v._getAttr,
      type:        v._getAttr,
      action:      v._getAttrNode,
      disabled:    v._flag,
      checked:     v._flag,
      readonly:    v._flag,
      multiple:    v._flag,
      onload:      v._getEv,
      onunload:    v._getEv,
      onclick:     v._getEv,
      ondblclick:  v._getEv,
      onmousedown: v._getEv,
      onmouseup:   v._getEv,
      onmouseover: v._getEv,
      onmousemove: v._getEv,
      onmouseout:  v._getEv,
      onfocus:     v._getEv,
      onblur:      v._getEv,
      onkeypress:  v._getEv,
      onkeydown:   v._getEv,
      onkeyup:     v._getEv,
      onsubmit:    v._getEv,
      onreset:     v._getEv,
      onselect:    v._getEv,
      onchange:    v._getEv
    });
  })(Element._attributeTranslations.read.values);
}

else if (Prototype.Browser.Gecko && /rv:1\.8\.0/.test(navigator.userAgent)) {
  Element.Methods.setOpacity = function(element, value) {
    element = $(element);
    element.style.opacity = (value == 1) ? 0.999999 :
      (value === '') ? '' : (value < 0.00001) ? 0 : value;
    return element;
  };
}

else if (Prototype.Browser.WebKit) {
  Element.Methods.setOpacity = function(element, value) {
    element = $(element);
    element.style.opacity = (value == 1 || value === '') ? '' :
      (value < 0.00001) ? 0 : value;

    if (value == 1)
      if(element.tagName == 'IMG' && element.width) {
        element.width++; element.width--;
      } else try {
        var n = document.createTextNode(' ');
        element.appendChild(n);
        element.removeChild(n);
      } catch (e) { }

    return element;
  };

  // Safari returns margins on body which is incorrect if the child is absolutely
  // positioned.  For performance reasons, redefine Element#cumulativeOffset for
  // KHTML/WebKit only.
  Element.Methods.cumulativeOffset = function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      if (element.offsetParent == document.body)
        if (Element.getStyle(element, 'position') == 'absolute') break;

      element = element.offsetParent;
    } while (element);

    return Element._returnOffset(valueL, valueT);
  };
}

if (Prototype.Browser.IE || Prototype.Browser.Opera) {
  // IE and Opera are missing .innerHTML support for TABLE-related and SELECT elements
  Element.Methods.update = function(element, content) {
    element = $(element);

    if (content && content.toElement) content = content.toElement();
    if (Object.isElement(content)) return element.update().insert(content);

    content = Object.toHTML(content);
    var tagName = element.tagName.toUpperCase();

    if (tagName in Element._insertionTranslations.tags) {
      $A(element.childNodes).each(function(node) { element.removeChild(node) });
      Element._getContentFromAnonymousElement(tagName, content.stripScripts())
        .each(function(node) { element.appendChild(node) });
    }
    else element.innerHTML = content.stripScripts();

    content.evalScripts.bind(content).defer();
    return element;
  };
}

if ('outerHTML' in document.createElement('div')) {
  Element.Methods.replace = function(element, content) {
    element = $(element);

    if (content && content.toElement) content = content.toElement();
    if (Object.isElement(content)) {
      element.parentNode.replaceChild(content, element);
      return element;
    }

    content = Object.toHTML(content);
    var parent = element.parentNode, tagName = parent.tagName.toUpperCase();

    if (Element._insertionTranslations.tags[tagName]) {
      var nextSibling = element.next();
      var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
      parent.removeChild(element);
      if (nextSibling)
        fragments.each(function(node) { parent.insertBefore(node, nextSibling) });
      else
        fragments.each(function(node) { parent.appendChild(node) });
    }
    else element.outerHTML = content.stripScripts();

    content.evalScripts.bind(content).defer();
    return element;
  };
}

Element._returnOffset = function(l, t) {
  var result = [l, t];
  result.left = l;
  result.top = t;
  return result;
};

Element._getContentFromAnonymousElement = function(tagName, html) {
  var div = new Element('div'), t = Element._insertionTranslations.tags[tagName];
  if (t) {
    div.innerHTML = t[0] + html + t[1];
    t[2].times(function() { div = div.firstChild });
  } else div.innerHTML = html;
  return $A(div.childNodes);
};

Element._insertionTranslations = {
  before: function(element, node) {
    element.parentNode.insertBefore(node, element);
  },
  top: function(element, node) {
    element.insertBefore(node, element.firstChild);
  },
  bottom: function(element, node) {
    element.appendChild(node);
  },
  after: function(element, node) {
    element.parentNode.insertBefore(node, element.nextSibling);
  },
  tags: {
    TABLE:  ['<table>',                '</table>',                   1],
    TBODY:  ['<table><tbody>',         '</tbody></table>',           2],
    TR:     ['<table><tbody><tr>',     '</tr></tbody></table>',      3],
    TD:     ['<table><tbody><tr><td>', '</td></tr></tbody></table>', 4],
    SELECT: ['<select>',               '</select>',                  1]
  }
};

(function() {
  Object.extend(this.tags, {
    THEAD: this.tags.TBODY,
    TFOOT: this.tags.TBODY,
    TH:    this.tags.TD
  });
}).call(Element._insertionTranslations);

Element.Methods.Simulated = {
  hasAttribute: function(element, attribute) {
    attribute = Element._attributeTranslations.has[attribute] || attribute;
    var node = $(element).getAttributeNode(attribute);
    return node && node.specified;
  }
};

Element.Methods.ByTag = { };

Object.extend(Element, Element.Methods);

if (!Prototype.BrowserFeatures.ElementExtensions &&
    document.createElement('div').__proto__) {
  window.HTMLElement = { };
  window.HTMLElement.prototype = document.createElement('div').__proto__;
  Prototype.BrowserFeatures.ElementExtensions = true;
}

Element.extend = (function() {
  if (Prototype.BrowserFeatures.SpecificElementExtensions)
    return Prototype.K;

  var Methods = { }, ByTag = Element.Methods.ByTag;

  var extend = Object.extend(function(element) {
    if (!element || element._extendedByPrototype ||
        element.nodeType != 1 || element == window) return element;

    var methods = Object.clone(Methods),
      tagName = element.tagName, property, value;

    // extend methods for specific tags
    if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]);

    for (property in methods) {
      value = methods[property];
      if (Object.isFunction(value) && !(property in element))
        element[property] = value.methodize();
    }

    element._extendedByPrototype = Prototype.emptyFunction;
    return element;

  }, {
    refresh: function() {
      // extend methods for all tags (Safari doesn't need this)
      if (!Prototype.BrowserFeatures.ElementExtensions) {
        Object.extend(Methods, Element.Methods);
        Object.extend(Methods, Element.Methods.Simulated);
      }
    }
  });

  extend.refresh();
  return extend;
})();

Element.hasAttribute = function(element, attribute) {
  if (element.hasAttribute) return element.hasAttribute(attribute);
  return Element.Methods.Simulated.hasAttribute(element, attribute);
};

Element.addMethods = function(methods) {
  var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag;

  if (!methods) {
    Object.extend(Form, Form.Methods);
    Object.extend(Form.Element, Form.Element.Methods);
    Object.extend(Element.Methods.ByTag, {
      "FORM":     Object.clone(Form.Methods),
      "INPUT":    Object.clone(Form.Element.Methods),
      "SELECT":   Object.clone(Form.Element.Methods),
      "TEXTAREA": Object.clone(Form.Element.Methods)
    });
  }

  if (arguments.length == 2) {
    var tagName = methods;
    methods = arguments[1];
  }

  if (!tagName) Object.extend(Element.Methods, methods || { });
  else {
    if (Object.isArray(tagName)) tagName.each(extend);
    else extend(tagName);
  }

  function extend(tagName) {
    tagName = tagName.toUpperCase();
    if (!Element.Methods.ByTag[tagName])
      Element.Methods.ByTag[tagName] = { };
    Object.extend(Element.Methods.ByTag[tagName], methods);
  }

  function copy(methods, destination, onlyIfAbsent) {
    onlyIfAbsent = onlyIfAbsent || false;
    for (var property in methods) {
      var value = methods[property];
      if (!Object.isFunction(value)) continue;
      if (!onlyIfAbsent || !(property in destination))
        destination[property] = value.methodize();
    }
  }

  function findDOMClass(tagName) {
    var klass;
    var trans = {
      "OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph",
      "FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList",
      "DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading",
      "H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote",
      "INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION":
      "TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD":
      "TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR":
      "TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET":
      "FrameSet", "IFRAME": "IFrame"
    };
    if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element';
    if (window[klass]) return window[klass];
    klass = 'HTML' + tagName + 'Element';
    if (window[klass]) return window[klass];
    klass = 'HTML' + tagName.capitalize() + 'Element';
    if (window[klass]) return window[klass];

    window[klass] = { };
    window[klass].prototype = document.createElement(tagName).__proto__;
    return window[klass];
  }

  if (F.ElementExtensions) {
    copy(Element.Methods, HTMLElement.prototype);
    copy(Element.Methods.Simulated, HTMLElement.prototype, true);
  }

  if (F.SpecificElementExtensions) {
    for (var tag in Element.Methods.ByTag) {
      var klass = findDOMClass(tag);
      if (Object.isUndefined(klass)) continue;
      copy(T[tag], klass.prototype);
    }
  }

  Object.extend(Element, Element.Methods);
  delete Element.ByTag;

  if (Element.extend.refresh) Element.extend.refresh();
  Element.cache = { };
};

document.viewport = {
  getDimensions: function() {
    var dimensions = { };
    var B = Prototype.Browser;
    $w('width height').each(function(d) {
      var D = d.capitalize();
      dimensions[d] = (B.WebKit && !document.evaluate) ? self['inner' + D] :
        (B.Opera) ? document.body['client' + D] : document.documentElement['client' + D];
    });
    return dimensions;
  },

  getWidth: function() {
    return this.getDimensions().width;
  },

  getHeight: function() {
    return this.getDimensions().height;
  },

  getScrollOffsets: function() {
    return Element._returnOffset(
      window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
      window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
  }
};
/* Portions of the Selector class are derived from Jack Slocumâ€™s DomQuery,
 * part of YUI-Ext version 0.40, distributed under the terms of an MIT-style
 * license.  Please see http://www.yui-ext.com/ for more information. */

var Selector = Class.create({
  initialize: function(expression) {
    this.expression = expression.strip();
    this.compileMatcher();
  },

  shouldUseXPath: function() {
    if (!Prototype.BrowserFeatures.XPath) return false;

    var e = this.expression;

    // Safari 3 chokes on :*-of-type and :empty
    if (Prototype.Browser.WebKit &&
     (e.include("-of-type") || e.include(":empty")))
      return false;

    // XPath can't do namespaced attributes, nor can it read
    // the "checked" property from DOM nodes
    if ((/(\[[\w-]*?:|:checked)/).test(this.expression))
      return false;

    return true;
  },

  compileMatcher: function() {
    if (this.shouldUseXPath())
      return this.compileXPathMatcher();

    var e = this.expression, ps = Selector.patterns, h = Selector.handlers,
        c = Selector.criteria, le, p, m;

    if (Selector._cache[e]) {
      this.matcher = Selector._cache[e];
      return;
    }

    this.matcher = ["this.matcher = function(root) {",
                    "var r = root, h = Selector.handlers, c = false, n;"];

    while (e && le != e && (/\S/).test(e)) {
      le = e;
      for (var i in ps) {
        p = ps[i];
        if (m = e.match(p)) {
          this.matcher.push(Object.isFunction(c[i]) ? c[i](m) :
              new Template(c[i]).evaluate(m));
          e = e.replace(m[0], '');
          break;
        }
      }
    }

    this.matcher.push("return h.unique(n);\n}");
    eval(this.matcher.join('\n'));
    Selector._cache[this.expression] = this.matcher;
  },

  compileXPathMatcher: function() {
    var e = this.expression, ps = Selector.patterns,
        x = Selector.xpath, le, m;

    if (Selector._cache[e]) {
      this.xpath = Selector._cache[e]; return;
    }

    this.matcher = ['.//*'];
    while (e && le != e && (/\S/).test(e)) {
      le = e;
      for (var i in ps) {
        if (m = e.match(ps[i])) {
          this.matcher.push(Object.isFunction(x[i]) ? x[i](m) :
            new Template(x[i]).evaluate(m));
          e = e.replace(m[0], '');
          break;
        }
      }
    }

    this.xpath = this.matcher.join('');
    Selector._cache[this.expression] = this.xpath;
  },

  findElements: function(root) {
    root = root || document;
    if (this.xpath) return document._getElementsByXPath(this.xpath, root);
    return this.matcher(root);
  },

  match: function(element) {
    this.tokens = [];

    var e = this.expression, ps = Selector.patterns, as = Selector.assertions;
    var le, p, m;

    while (e && le !== e && (/\S/).test(e)) {
      le = e;
      for (var i in ps) {
        p = ps[i];
        if (m = e.match(p)) {
          // use the Selector.assertions methods unless the selector
          // is too complex.
          if (as[i]) {
            this.tokens.push([i, Object.clone(m)]);
            e = e.replace(m[0], '');
          } else {
            // reluctantly do a document-wide search
            // and look for a match in the array
            return this.findElements(document).include(element);
          }
        }
      }
    }

    var match = true, name, matches;
    for (var i = 0, token; token = this.tokens[i]; i++) {
      name = token[0], matches = token[1];
      if (!Selector.assertions[name](element, matches)) {
        match = false; break;
      }
    }

    return match;
  },

  toString: function() {
    return this.expression;
  },

  inspect: function() {
    return "#<Selector:" + this.expression.inspect() + ">";
  }
});

Object.extend(Selector, {
  _cache: { },

  xpath: {
    descendant:   "//*",
    child:        "/*",
    adjacent:     "/following-sibling::*[1]",
    laterSibling: '/following-sibling::*',
    tagName:      function(m) {
      if (m[1] == '*') return '';
      return "[local-name()='" + m[1].toLowerCase() +
             "' or local-name()='" + m[1].toUpperCase() + "']";
    },
    className:    "[contains(concat(' ', @class, ' '), ' #{1} ')]",
    id:           "[@id='#{1}']",
    attrPresence: function(m) {
      m[1] = m[1].toLowerCase();
      return new Template("[@#{1}]").evaluate(m);
    },
    attr: function(m) {
      m[1] = m[1].toLowerCase();
      m[3] = m[5] || m[6];
      return new Template(Selector.xpath.operators[m[2]]).evaluate(m);
    },
    pseudo: function(m) {
      var h = Selector.xpath.pseudos[m[1]];
      if (!h) return '';
      if (Object.isFunction(h)) return h(m);
      return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m);
    },
    operators: {
      '=':  "[@#{1}='#{3}']",
      '!=': "[@#{1}!='#{3}']",
      '^=': "[starts-with(@#{1}, '#{3}')]",
      '$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']",
      '*=': "[contains(@#{1}, '#{3}')]",
      '~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]",
      '|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]"
    },
    pseudos: {
      'first-child': '[not(preceding-sibling::*)]',
      'last-child':  '[not(following-sibling::*)]',
      'only-child':  '[not(preceding-sibling::* or following-sibling::*)]',
      'empty':       "[count(*) = 0 and (count(text()) = 0 or translate(text(), ' \t\r\n', '') = '')]",
      'checked':     "[@checked]",
      'disabled':    "[@disabled]",
      'enabled':     "[not(@disabled)]",
      'not': function(m) {
        var e = m[6], p = Selector.patterns,
            x = Selector.xpath, le, v;

        var exclusion = [];
        while (e && le != e && (/\S/).test(e)) {
          le = e;
          for (var i in p) {
            if (m = e.match(p[i])) {
              v = Object.isFunction(x[i]) ? x[i](m) : new Template(x[i]).evaluate(m);
              exclusion.push("(" + v.substring(1, v.length - 1) + ")");
              e = e.replace(m[0], '');
              break;
            }
          }
        }
        return "[not(" + exclusion.join(" and ") + ")]";
      },
      'nth-child':      function(m) {
        return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m);
      },
      'nth-last-child': function(m) {
        return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m);
      },
      'nth-of-type':    function(m) {
        return Selector.xpath.pseudos.nth("position() ", m);
      },
      'nth-last-of-type': function(m) {
        return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m);
      },
      'first-of-type':  function(m) {
        m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m);
      },
      'last-of-type':   function(m) {
        m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m);
      },
      'only-of-type':   function(m) {
        var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m);
      },
      nth: function(fragment, m) {
        var mm, formula = m[6], predicate;
        if (formula == 'even') formula = '2n+0';
        if (formula == 'odd')  formula = '2n+1';
        if (mm = formula.match(/^(\d+)$/)) // digit only
          return '[' + fragment + "= " + mm[1] + ']';
        if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
          if (mm[1] == "-") mm[1] = -1;
          var a = mm[1] ? Number(mm[1]) : 1;
          var b = mm[2] ? Number(mm[2]) : 0;
          predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " +
          "((#{fragment} - #{b}) div #{a} >= 0)]";
          return new Template(predicate).evaluate({
            fragment: fragment, a: a, b: b });
        }
      }
    }
  },

  criteria: {
    tagName:      'n = h.tagName(n, r, "#{1}", c);      c = false;',
    className:    'n = h.className(n, r, "#{1}", c);    c = false;',
    id:           'n = h.id(n, r, "#{1}", c);           c = false;',
    attrPresence: 'n = h.attrPresence(n, r, "#{1}", c); c = false;',
    attr: function(m) {
      m[3] = (m[5] || m[6]);
      return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}", c); c = false;').evaluate(m);
    },
    pseudo: function(m) {
      if (m[6]) m[6] = m[6].replace(/"/g, '\\"');
      return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m);
    },
    descendant:   'c = "descendant";',
    child:        'c = "child";',
    adjacent:     'c = "adjacent";',
    laterSibling: 'c = "laterSibling";'
  },

  patterns: {
    // combinators must be listed first
    // (and descendant needs to be last combinator)
    laterSibling: /^\s*~\s*/,
    child:        /^\s*>\s*/,
    adjacent:     /^\s*\+\s*/,
    descendant:   /^\s/,

    // selectors follow
    tagName:      /^\s*(\*|[\w\-]+)(\b|$)?/,
    id:           /^#([\w\-\*]+)(\b|$)/,
    className:    /^\.([\w\-\*]+)(\b|$)/,
    pseudo:
/^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s|[:+~>]))/,
    attrPresence: /^\[([\w]+)\]/,
    attr:         /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/
  },

  // for Selector.match and Element#match
  assertions: {
    tagName: function(element, matches) {
      return matches[1].toUpperCase() == element.tagName.toUpperCase();
    },

    className: function(element, matches) {
      return Element.hasClassName(element, matches[1]);
    },

    id: function(element, matches) {
      return element.id === matches[1];
    },

    attrPresence: function(element, matches) {
      return Element.hasAttribute(element, matches[1]);
    },

    attr: function(element, matches) {
      var nodeValue = Element.readAttribute(element, matches[1]);
      return nodeValue && Selector.operators[matches[2]](nodeValue, matches[5] || matches[6]);
    }
  },

  handlers: {
    // UTILITY FUNCTIONS
    // joins two collections
    concat: function(a, b) {
      for (var i = 0, node; node = b[i]; i++)
        a.push(node);
      return a;
    },

    // marks an array of nodes for counting
    mark: function(nodes) {
      var _true = Prototype.emptyFunction;
      for (var i = 0, node; node = nodes[i]; i++)
        node._countedByPrototype = _true;
      return nodes;
    },

    unmark: function(nodes) {
      for (var i = 0, node; node = nodes[i]; i++)
        node._countedByPrototype = undefined;
      return nodes;
    },

    // mark each child node with its position (for nth calls)
    // "ofType" flag indicates whether we're indexing for nth-of-type
    // rather than nth-child
    index: function(parentNode, reverse, ofType) {
      parentNode._countedByPrototype = Prototype.emptyFunction;
      if (reverse) {
        for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) {
          var node = nodes[i];
          if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
        }
      } else {
        for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++)
          if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++;
      }
    },

    // filters out duplicates and extends all nodes
    unique: function(nodes) {
      if (nodes.length == 0) return nodes;
      var results = [], n;
      for (var i = 0, l = nodes.length; i < l; i++)
        if (!(n = nodes[i])._countedByPrototype) {
          n._countedByPrototype = Prototype.emptyFunction;
          results.push(Element.extend(n));
        }
      return Selector.handlers.unmark(results);
    },

    // COMBINATOR FUNCTIONS
    descendant: function(nodes) {
      var h = Selector.handlers;
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        h.concat(results, node.getElementsByTagName('*'));
      return results;
    },

    child: function(nodes) {
      var h = Selector.handlers;
      for (var i = 0, results = [], node; node = nodes[i]; i++) {
        for (var j = 0, child; child = node.childNodes[j]; j++)
          if (child.nodeType == 1 && child.tagName != '!') results.push(child);
      }
      return results;
    },

    adjacent: function(nodes) {
      for (var i = 0, results = [], node; node = nodes[i]; i++) {
        var next = this.nextElementSibling(node);
        if (next) results.push(next);
      }
      return results;
    },

    laterSibling: function(nodes) {
      var h = Selector.handlers;
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        h.concat(results, Element.nextSiblings(node));
      return results;
    },

    nextElementSibling: function(node) {
      while (node = node.nextSibling)
          if (node.nodeType == 1) return node;
      return null;
    },

    previousElementSibling: function(node) {
      while (node = node.previousSibling)
        if (node.nodeType == 1) return node;
      return null;
    },

    // TOKEN FUNCTIONS
    tagName: function(nodes, root, tagName, combinator) {
      var uTagName = tagName.toUpperCase();
      var results = [], h = Selector.handlers;
      if (nodes) {
        if (combinator) {
          // fastlane for ordinary descendant combinators
          if (combinator == "descendant") {
            for (var i = 0, node; node = nodes[i]; i++)
              h.concat(results, node.getElementsByTagName(tagName));
            return results;
          } else nodes = this[combinator](nodes);
          if (tagName == "*") return nodes;
        }
        for (var i = 0, node; node = nodes[i]; i++)
          if (node.tagName.toUpperCase() === uTagName) results.push(node);
        return results;
      } else return root.getElementsByTagName(tagName);
    },

    id: function(nodes, root, id, combinator) {
      var targetNode = $(id), h = Selector.handlers;
      if (!targetNode) return [];
      if (!nodes && root == document) return [targetNode];
      if (nodes) {
        if (combinator) {
          if (combinator == 'child') {
            for (var i = 0, node; node = nodes[i]; i++)
              if (targetNode.parentNode == node) return [targetNode];
          } else if (combinator == 'descendant') {
            for (var i = 0, node; node = nodes[i]; i++)
              if (Element.descendantOf(targetNode, node)) return [targetNode];
          } else if (combinator == 'adjacent') {
            for (var i = 0, node; node = nodes[i]; i++)
              if (Selector.handlers.previousElementSibling(targetNode) == node)
                return [targetNode];
          } else nodes = h[combinator](nodes);
        }
        for (var i = 0, node; node = nodes[i]; i++)
          if (node == targetNode) return [targetNode];
        return [];
      }
      return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : [];
    },

    className: function(nodes, root, className, combinator) {
      if (nodes && combinator) nodes = this[combinator](nodes);
      return Selector.handlers.byClassName(nodes, root, className);
    },

    byClassName: function(nodes, root, className) {
      if (!nodes) nodes = Selector.handlers.descendant([root]);
      var needle = ' ' + className + ' ';
      for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) {
        nodeClassName = node.className;
        if (nodeClassName.length == 0) continue;
        if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle))
          results.push(node);
      }
      return results;
    },

    attrPresence: function(nodes, root, attr, combinator) {
      if (!nodes) nodes = root.getElementsByTagName("*");
      if (nodes && combinator) nodes = this[combinator](nodes);
      var results = [];
      for (var i = 0, node; node = nodes[i]; i++)
        if (Element.hasAttribute(node, attr)) results.push(node);
      return results;
    },

    attr: function(nodes, root, attr, value, operator, combinator) {
      if (!nodes) nodes = root.getElementsByTagName("*");
      if (nodes && combinator) nodes = this[combinator](nodes);
      var handler = Selector.operators[operator], results = [];
      for (var i = 0, node; node = nodes[i]; i++) {
        var nodeValue = Element.readAttribute(node, attr);
        if (nodeValue === null) continue;
        if (handler(nodeValue, value)) results.push(node);
      }
      return results;
    },

    pseudo: function(nodes, name, value, root, combinator) {
      if (nodes && combinator) nodes = this[combinator](nodes);
      if (!nodes) nodes = root.getElementsByTagName("*");
      return Selector.pseudos[name](nodes, value, root);
    }
  },

  pseudos: {
    'first-child': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++) {
        if (Selector.handlers.previousElementSibling(node)) continue;
          results.push(node);
      }
      return results;
    },
    'last-child': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++) {
        if (Selector.handlers.nextElementSibling(node)) continue;
          results.push(node);
      }
      return results;
    },
    'only-child': function(nodes, value, root) {
      var h = Selector.handlers;
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        if (!h.previousElementSibling(node) && !h.nextElementSibling(node))
          results.push(node);
      return results;
    },
    'nth-child':        function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, formula, root);
    },
    'nth-last-child':   function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, formula, root, true);
    },
    'nth-of-type':      function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, formula, root, false, true);
    },
    'nth-last-of-type': function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, formula, root, true, true);
    },
    'first-of-type':    function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, "1", root, false, true);
    },
    'last-of-type':     function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, "1", root, true, true);
    },
    'only-of-type':     function(nodes, formula, root) {
      var p = Selector.pseudos;
      return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root);
    },

    // handles the an+b logic
    getIndices: function(a, b, total) {
      if (a == 0) return b > 0 ? [b] : [];
      return $R(1, total).inject([], function(memo, i) {
        if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i);
        return memo;
      });
    },

    // handles nth(-last)-child, nth(-last)-of-type, and (first|last)-of-type
    nth: function(nodes, formula, root, reverse, ofType) {
      if (nodes.length == 0) return [];
      if (formula == 'even') formula = '2n+0';
      if (formula == 'odd')  formula = '2n+1';
      var h = Selector.handlers, results = [], indexed = [], m;
      h.mark(nodes);
      for (var i = 0, node; node = nodes[i]; i++) {
        if (!node.parentNode._countedByPrototype) {
          h.index(node.parentNode, reverse, ofType);
          indexed.push(node.parentNode);
        }
      }
      if (formula.match(/^\d+$/)) { // just a number
        formula = Number(formula);
        for (var i = 0, node; node = nodes[i]; i++)
          if (node.nodeIndex == formula) results.push(node);
      } else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
        if (m[1] == "-") m[1] = -1;
        var a = m[1] ? Number(m[1]) : 1;
        var b = m[2] ? Number(m[2]) : 0;
        var indices = Selector.pseudos.getIndices(a, b, nodes.length);
        for (var i = 0, node, l = indices.length; node = nodes[i]; i++) {
          for (var j = 0; j < l; j++)
            if (node.nodeIndex == indices[j]) results.push(node);
        }
      }
      h.unmark(nodes);
      h.unmark(indexed);
      return results;
    },

    'empty': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++) {
        // IE treats comments as element nodes
        if (node.tagName == '!' || (node.firstChild && !node.innerHTML.match(/^\s*$/))) continue;
        results.push(node);
      }
      return results;
    },

    'not': function(nodes, selector, root) {
      var h = Selector.handlers, selectorType, m;
      var exclusions = new Selector(selector).findElements(root);
      h.mark(exclusions);
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        if (!node._countedByPrototype) results.push(node);
      h.unmark(exclusions);
      return results;
    },

    'enabled': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        if (!node.disabled) results.push(node);
      return results;
    },

    'disabled': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        if (node.disabled) results.push(node);
      return results;
    },

    'checked': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        if (node.checked) results.push(node);
      return results;
    }
  },

  operators: {
    '=':  function(nv, v) { return nv == v; },
    '!=': function(nv, v) { return nv != v; },
    '^=': function(nv, v) { return nv.startsWith(v); },
    '$=': function(nv, v) { return nv.endsWith(v); },
    '*=': function(nv, v) { return nv.include(v); },
    '~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); },
    '|=': function(nv, v) { return ('-' + nv.toUpperCase() + '-').include('-' + v.toUpperCase() + '-'); }
  },

  split: function(expression) {
    var expressions = [];
    expression.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) {
      expressions.push(m[1].strip());
    });
    return expressions;
  },

  matchElements: function(elements, expression) {
    var matches = $$(expression), h = Selector.handlers;
    h.mark(matches);
    for (var i = 0, results = [], element; element = elements[i]; i++)
      if (element._countedByPrototype) results.push(element);
    h.unmark(matches);
    return results;
  },

  findElement: function(elements, expression, index) {
    if (Object.isNumber(expression)) {
      index = expression; expression = false;
    }
    return Selector.matchElements(elements, expression || '*')[index || 0];
  },

  findChildElements: function(element, expressions) {
    expressions = Selector.split(expressions.join(','));
    var results = [], h = Selector.handlers;
    for (var i = 0, l = expressions.length, selector; i < l; i++) {
      selector = new Selector(expressions[i].strip());
      h.concat(results, selector.findElements(element));
    }
    return (l > 1) ? h.unique(results) : results;
  }
});

if (Prototype.Browser.IE) {
  Object.extend(Selector.handlers, {
    // IE returns comment nodes on getElementsByTagName("*").
    // Filter them out.
    concat: function(a, b) {
      for (var i = 0, node; node = b[i]; i++)
        if (node.tagName !== "!") a.push(node);
      return a;
    },

    // IE improperly serializes _countedByPrototype in (inner|outer)HTML.
    unmark: function(nodes) {
      for (var i = 0, node; node = nodes[i]; i++)
        node.removeAttribute('_countedByPrototype');
      return nodes;
    }
  });
}

function $$() {
  return Selector.findChildElements(document, $A(arguments));
}
var Form = {
  reset: function(form) {
    $(form).reset();
    return form;
  },

  serializeElements: function(elements, options) {
    if (typeof options != 'object') options = { hash: !!options };
    else if (Object.isUndefined(options.hash)) options.hash = true;
    var key, value, submitted = false, submit = options.submit;

    var data = elements.inject({ }, function(result, element) {
      if (!element.disabled && element.name) {
        key = element.name; value = $(element).getValue();
        if (value != null && (element.type != 'submit' || (!submitted &&
            submit !== false && (!submit || key == submit) && (submitted = true)))) {
          if (key in result) {
            // a key is already present; construct an array of values
            if (!Object.isArray(result[key])) result[key] = [result[key]];
            result[key].push(value);
          }
          else result[key] = value;
        }
      }
      return result;
    });

    return options.hash ? data : Object.toQueryString(data);
  }
};

Form.Methods = {
  serialize: function(form, options) {
    return Form.serializeElements(Form.getElements(form), options);
  },

  getElements: function(form) {
    return $A($(form).getElementsByTagName('*')).inject([],
      function(elements, child) {
        if (Form.Element.Serializers[child.tagName.toLowerCase()])
          elements.push(Element.extend(child));
        return elements;
      }
    );
  },

  getInputs: function(form, typeName, name) {
    form = $(form);
    var inputs = form.getElementsByTagName('input');

    if (!typeName && !name) return $A(inputs).map(Element.extend);

    for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
      var input = inputs[i];
      if ((typeName && input.type != typeName) || (name && input.name != name))
        continue;
      matchingInputs.push(Element.extend(input));
    }

    return matchingInputs;
  },

  disable: function(form) {
    form = $(form);
    Form.getElements(form).invoke('disable');
    return form;
  },

  enable: function(form) {
    form = $(form);
    Form.getElements(form).invoke('enable');
    return form;
  },

  findFirstElement: function(form) {
    var elements = $(form).getElements().findAll(function(element) {
      return 'hidden' != element.type && !element.disabled;
    });
    var firstByIndex = elements.findAll(function(element) {
      return element.hasAttribute('tabIndex') && element.tabIndex >= 0;
    }).sortBy(function(element) { return element.tabIndex }).first();

    return firstByIndex ? firstByIndex : elements.find(function(element) {
      return ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
    });
  },

  focusFirstElement: function(form) {
    form = $(form);
    form.findFirstElement().activate();
    return form;
  },

  request: function(form, options) {
    form = $(form), options = Object.clone(options || { });

    var params = options.parameters, action = form.readAttribute('action') || '';
    if (action.blank()) action = window.location.href;
    options.parameters = form.serialize(true);

    if (params) {
      if (Object.isString(params)) params = params.toQueryParams();
      Object.extend(options.parameters, params);
    }

    if (form.hasAttribute('method') && !options.method)
      options.method = form.method;

    return new Ajax.Request(action, options);
  }
};

/*--------------------------------------------------------------------------*/

Form.Element = {
  focus: function(element) {
    $(element).focus();
    return element;
  },

  select: function(element) {
    $(element).select();
    return element;
  }
};

Form.Element.Methods = {
  serialize: function(element) {
    element = $(element);
    if (!element.disabled && element.name) {
      var value = element.getValue();
      if (value != undefined) {
        var pair = { };
        pair[element.name] = value;
        return Object.toQueryString(pair);
      }
    }
    return '';
  },

  getValue: function(element) {
    element = $(element);
    var method = element.tagName.toLowerCase();
    return Form.Element.Serializers[method](element);
  },

  setValue: function(element, value) {
    element = $(element);
    var method = element.tagName.toLowerCase();
    Form.Element.Serializers[method](element, value);
    return element;
  },

  clear: function(element) {
    $(element).value = '';
    return element;
  },

  present: function(element) {
    return $(element).value != '';
  },

  activate: function(element) {
    element = $(element);
    try {
      element.focus();
      if (element.select && (element.tagName.toLowerCase() != 'input' ||
          !['button', 'reset', 'submit'].include(element.type)))
        element.select();
    } catch (e) { }
    return element;
  },

  disable: function(element) {
    element = $(element);
    element.blur();
    element.disabled = true;
    return element;
  },

  enable: function(element) {
    element = $(element);
    element.disabled = false;
    return element;
  }
};

/*--------------------------------------------------------------------------*/

var Field = Form.Element;
var $F = Form.Element.Methods.getValue;

/*--------------------------------------------------------------------------*/

Form.Element.Serializers = {
  input: function(element, value) {
    switch (element.type.toLowerCase()) {
      case 'checkbox':
      case 'radio':
        return Form.Element.Serializers.inputSelector(element, value);
      default:
        return Form.Element.Serializers.textarea(element, value);
    }
  },

  inputSelector: function(element, value) {
    if (Object.isUndefined(value)) return element.checked ? element.value : null;
    else element.checked = !!value;
  },

  textarea: function(element, value) {
    if (Object.isUndefined(value)) return element.value;
    else element.value = value;
  },

  select: function(element, index) {
    if (Object.isUndefined(index))
      return this[element.type == 'select-one' ?
        'selectOne' : 'selectMany'](element);
    else {
      var opt, value, single = !Object.isArray(index);
      for (var i = 0, length = element.length; i < length; i++) {
        opt = element.options[i];
        value = this.optionValue(opt);
        if (single) {
          if (value == index) {
            opt.selected = true;
            return;
          }
        }
        else opt.selected = index.include(value);
      }
    }
  },

  selectOne: function(element) {
    var index = element.selectedIndex;
    return index >= 0 ? this.optionValue(element.options[index]) : null;
  },

  selectMany: function(element) {
    var values, length = element.length;
    if (!length) return null;

    for (var i = 0, values = []; i < length; i++) {
      var opt = element.options[i];
      if (opt.selected) values.push(this.optionValue(opt));
    }
    return values;
  },

  optionValue: function(opt) {
    // extend element because hasAttribute may not be native
    return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
  }
};

/*--------------------------------------------------------------------------*/

Abstract.TimedObserver = Class.create(PeriodicalExecuter, {
  initialize: function($super, element, frequency, callback) {
    $super(callback, frequency);
    this.element   = $(element);
    this.lastValue = this.getValue();
  },

  execute: function() {
    var value = this.getValue();
    if (Object.isString(this.lastValue) && Object.isString(value) ?
        this.lastValue != value : String(this.lastValue) != String(value)) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  }
});

Form.Element.Observer = Class.create(Abstract.TimedObserver, {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.Observer = Class.create(Abstract.TimedObserver, {
  getValue: function() {
    return Form.serialize(this.element);
  }
});

/*--------------------------------------------------------------------------*/

Abstract.EventObserver = Class.create({
  initialize: function(element, callback) {
    this.element  = $(element);
    this.callback = callback;

    this.lastValue = this.getValue();
    if (this.element.tagName.toLowerCase() == 'form')
      this.registerFormCallbacks();
    else
      this.registerCallback(this.element);
  },

  onElementEvent: function() {
    var value = this.getValue();
    if (this.lastValue != value) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  },

  registerFormCallbacks: function() {
    Form.getElements(this.element).each(this.registerCallback, this);
  },

  registerCallback: function(element) {
    if (element.type) {
      switch (element.type.toLowerCase()) {
        case 'checkbox':
        case 'radio':
          Event.observe(element, 'click', this.onElementEvent.bind(this));
          break;
        default:
          Event.observe(element, 'change', this.onElementEvent.bind(this));
          break;
      }
    }
  }
});

Form.Element.EventObserver = Class.create(Abstract.EventObserver, {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.EventObserver = Class.create(Abstract.EventObserver, {
  getValue: function() {
    return Form.serialize(this.element);
  }
});
if (!window.Event) var Event = { };

Object.extend(Event, {
  KEY_BACKSPACE: 8,
  KEY_TAB:       9,
  KEY_RETURN:   13,
  KEY_ESC:      27,
  KEY_LEFT:     37,
  KEY_UP:       38,
  KEY_RIGHT:    39,
  KEY_DOWN:     40,
  KEY_DELETE:   46,
  KEY_HOME:     36,
  KEY_END:      35,
  KEY_PAGEUP:   33,
  KEY_PAGEDOWN: 34,
  KEY_INSERT:   45,

  cache: { },

  relatedTarget: function(event) {
    var element;
    switch(event.type) {
      case 'mouseover': element = event.fromElement; break;
      case 'mouseout':  element = event.toElement;   break;
      default: return null;
    }
    return Element.extend(element);
  }
});

Event.Methods = (function() {
  var isButton;

  if (Prototype.Browser.IE) {
    var buttonMap = { 0: 1, 1: 4, 2: 2 };
    isButton = function(event, code) {
      return event.button == buttonMap[code];
    };

  } else if (Prototype.Browser.WebKit) {
    isButton = function(event, code) {
      switch (code) {
        case 0: return event.which == 1 && !event.metaKey;
        case 1: return event.which == 1 && event.metaKey;
        default: return false;
      }
    };

  } else {
    isButton = function(event, code) {
      return event.which ? (event.which === code + 1) : (event.button === code);
    };
  }

  return {
    isLeftClick:   function(event) { return isButton(event, 0) },
    isMiddleClick: function(event) { return isButton(event, 1) },
    isRightClick:  function(event) { return isButton(event, 2) },

    element: function(event) {
      var node = Event.extend(event).target;
      return Element.extend(node.nodeType == Node.TEXT_NODE ? node.parentNode : node);
    },

    findElement: function(event, expression) {
      var element = Event.element(event);
      if (!expression) return element;
      var elements = [element].concat(element.ancestors());
      return Selector.findElement(elements, expression, 0);
    },

    pointer: function(event) {
      return {
        x: event.pageX || (event.clientX +
          (document.documentElement.scrollLeft || document.body.scrollLeft)),
        y: event.pageY || (event.clientY +
          (document.documentElement.scrollTop || document.body.scrollTop))
      };
    },

    pointerX: function(event) { return Event.pointer(event).x },
    pointerY: function(event) { return Event.pointer(event).y },

    stop: function(event) {
      Event.extend(event);
      event.preventDefault();
      event.stopPropagation();
      event.stopped = true;
    }
  };
})();

Event.extend = (function() {
  var methods = Object.keys(Event.Methods).inject({ }, function(m, name) {
    m[name] = Event.Methods[name].methodize();
    return m;
  });

  if (Prototype.Browser.IE) {
    Object.extend(methods, {
      stopPropagation: function() { this.cancelBubble = true },
      preventDefault:  function() { this.returnValue = false },
      inspect: function() { return "[object Event]" }
    });

    return function(event) {
      if (!event) return false;
      if (event._extendedByPrototype) return event;

      event._extendedByPrototype = Prototype.emptyFunction;
      var pointer = Event.pointer(event);
      Object.extend(event, {
        target: event.srcElement,
        relatedTarget: Event.relatedTarget(event),
        pageX:  pointer.x,
        pageY:  pointer.y
      });
      return Object.extend(event, methods);
    };

  } else {
    Event.prototype = Event.prototype || document.createEvent("HTMLEvents").__proto__;
    Object.extend(Event.prototype, methods);
    return Prototype.K;
  }
})();

Object.extend(Event, (function() {
  var cache = Event.cache;

  function getEventID(element) {
    if (element._prototypeEventID) return element._prototypeEventID[0];
    arguments.callee.id = arguments.callee.id || 1;
    return element._prototypeEventID = [++arguments.callee.id];
  }

  function getDOMEventName(eventName) {
    if (eventName && eventName.include(':')) return "dataavailable";
    return eventName;
  }

  function getCacheForID(id) {
    return cache[id] = cache[id] || { };
  }

  function getWrappersForEventName(id, eventName) {
    var c = getCacheForID(id);
    return c[eventName] = c[eventName] || [];
  }

  function createWrapper(element, eventName, handler) {
    var id = getEventID(element);
    var c = getWrappersForEventName(id, eventName);
    if (c.pluck("handler").include(handler)) return false;

    var wrapper = function(event) {
      if (!Event || !Event.extend ||
        (event.eventName && event.eventName != eventName))
          return false;

      Event.extend(event);
      handler.call(element, event);
    };

    wrapper.handler = handler;
    c.push(wrapper);
    return wrapper;
  }

  function findWrapper(id, eventName, handler) {
    var c = getWrappersForEventName(id, eventName);
    return c.find(function(wrapper) { return wrapper.handler == handler });
  }

  function destroyWrapper(id, eventName, handler) {
    var c = getCacheForID(id);
    if (!c[eventName]) return false;
    c[eventName] = c[eventName].without(findWrapper(id, eventName, handler));
  }

  function destroyCache() {
    for (var id in cache)
      for (var eventName in cache[id])
        cache[id][eventName] = null;
  }

  if (window.attachEvent) {
    window.attachEvent("onunload", destroyCache);
  }

  return {
    observe: function(element, eventName, handler) {
      element = $(element);
      var name = getDOMEventName(eventName);

      var wrapper = createWrapper(element, eventName, handler);
      if (!wrapper) return element;

      if (element.addEventListener) {
        element.addEventListener(name, wrapper, false);
      } else {
        element.attachEvent("on" + name, wrapper);
      }

      return element;
    },

    stopObserving: function(element, eventName, handler) {
      element = $(element);
      var id = getEventID(element), name = getDOMEventName(eventName);

      if (!handler && eventName) {
        getWrappersForEventName(id, eventName).each(function(wrapper) {
          element.stopObserving(eventName, wrapper.handler);
        });
        return element;

      } else if (!eventName) {
        Object.keys(getCacheForID(id)).each(function(eventName) {
          element.stopObserving(eventName);
        });
        return element;
      }

      var wrapper = findWrapper(id, eventName, handler);
      if (!wrapper) return element;

      if (element.removeEventListener) {
        element.removeEventListener(name, wrapper, false);
      } else {
        element.detachEvent("on" + name, wrapper);
      }

      destroyWrapper(id, eventName, handler);

      return element;
    },

    fire: function(element, eventName, memo) {
      element = $(element);
      if (element == document && document.createEvent && !element.dispatchEvent)
        element = document.documentElement;

      var event;
      if (document.createEvent) {
        event = document.createEvent("HTMLEvents");
        event.initEvent("dataavailable", true, true);
      } else {
        event = document.createEventObject();
        event.eventType = "ondataavailable";
      }

      event.eventName = eventName;
      event.memo = memo || { };

      if (document.createEvent) {
        element.dispatchEvent(event);
      } else {
        element.fireEvent(event.eventType, event);
      }

      return Event.extend(event);
    }
  };
})());

Object.extend(Event, Event.Methods);

Element.addMethods({
  fire:          Event.fire,
  observe:       Event.observe,
  stopObserving: Event.stopObserving
});

Object.extend(document, {
  fire:          Element.Methods.fire.methodize(),
  observe:       Element.Methods.observe.methodize(),
  stopObserving: Element.Methods.stopObserving.methodize(),
  loaded:        false
});

(function() {
  /* Support for the DOMContentLoaded event is based on work by Dan Webb,
     Matthias Miller, Dean Edwards and John Resig. */

  var timer;

  function fireContentLoadedEvent() {
    if (document.loaded) return;
    if (timer) window.clearInterval(timer);
    document.fire("dom:loaded");
    document.loaded = true;
  }

  if (document.addEventListener) {
    if (Prototype.Browser.WebKit) {
      timer = window.setInterval(function() {
        if (/loaded|complete/.test(document.readyState))
          fireContentLoadedEvent();
      }, 0);

      Event.observe(window, "load", fireContentLoadedEvent);

    } else {
      document.addEventListener("DOMContentLoaded",
        fireContentLoadedEvent, false);
    }

  } else {
    document.write("<script id=__onDOMContentLoaded defer src=//:><\/script>");
    $("__onDOMContentLoaded").onreadystatechange = function() {
      if (this.readyState == "complete") {
        this.onreadystatechange = null;
        fireContentLoadedEvent();
      }
    };
  }
})();
/*------------------------------- DEPRECATED -------------------------------*/

Hash.toQueryString = Object.toQueryString;

var Toggle = { display: Element.toggle };

Element.Methods.childOf = Element.Methods.descendantOf;

var Insertion = {
  Before: function(element, content) {
    return Element.insert(element, {before:content});
  },

  Top: function(element, content) {
    return Element.insert(element, {top:content});
  },

  Bottom: function(element, content) {
    return Element.insert(element, {bottom:content});
  },

  After: function(element, content) {
    return Element.insert(element, {after:content});
  }
};

var $continue = new Error('"throw $continue" is deprecated, use "return" instead');

// This should be moved to script.aculo.us; notice the deprecated methods
// further below, that map to the newer Element methods.
var Position = {
  // set to true if needed, warning: firefox performance problems
  // NOT neeeded for page scrolling, only if draggable contained in
  // scrollable elements
  includeScrollOffsets: false,

  // must be called before calling withinIncludingScrolloffset, every time the
  // page is scrolled
  prepare: function() {
    this.deltaX =  window.pageXOffset
                || document.documentElement.scrollLeft
                || document.body.scrollLeft
                || 0;
    this.deltaY =  window.pageYOffset
                || document.documentElement.scrollTop
                || document.body.scrollTop
                || 0;
  },

  // caches x/y coordinate pair to use with overlap
  within: function(element, x, y) {
    if (this.includeScrollOffsets)
      return this.withinIncludingScrolloffsets(element, x, y);
    this.xcomp = x;
    this.ycomp = y;
    this.offset = Element.cumulativeOffset(element);

    return (y >= this.offset[1] &&
            y <  this.offset[1] + element.offsetHeight &&
            x >= this.offset[0] &&
            x <  this.offset[0] + element.offsetWidth);
  },

  withinIncludingScrolloffsets: function(element, x, y) {
    var offsetcache = Element.cumulativeScrollOffset(element);

    this.xcomp = x + offsetcache[0] - this.deltaX;
    this.ycomp = y + offsetcache[1] - this.deltaY;
    this.offset = Element.cumulativeOffset(element);

    return (this.ycomp >= this.offset[1] &&
            this.ycomp <  this.offset[1] + element.offsetHeight &&
            this.xcomp >= this.offset[0] &&
            this.xcomp <  this.offset[0] + element.offsetWidth);
  },

  // within must be called directly before
  overlap: function(mode, element) {
    if (!mode) return 0;
    if (mode == 'vertical')
      return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
        element.offsetHeight;
    if (mode == 'horizontal')
      return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
        element.offsetWidth;
  },

  // Deprecation layer -- use newer Element methods now (1.5.2).

  cumulativeOffset: Element.Methods.cumulativeOffset,

  positionedOffset: Element.Methods.positionedOffset,

  absolutize: function(element) {
    Position.prepare();
    return Element.absolutize(element);
  },

  relativize: function(element) {
    Position.prepare();
    return Element.relativize(element);
  },

  realOffset: Element.Methods.cumulativeScrollOffset,

  offsetParent: Element.Methods.getOffsetParent,

  page: Element.Methods.viewportOffset,

  clone: function(source, target, options) {
    options = options || { };
    return Element.clonePosition(target, source, options);
  }
};

/*--------------------------------------------------------------------------*/

if (!document.getElementsByClassName) document.getElementsByClassName = function(instanceMethods){
  function iter(name) {
    return name.blank() ? null : "[contains(concat(' ', @class, ' '), ' " + name + " ')]";
  }

  instanceMethods.getElementsByClassName = Prototype.BrowserFeatures.XPath ?
  function(element, className) {
    className = className.toString().strip();
    var cond = /\s/.test(className) ? $w(className).map(iter).join('') : iter(className);
    return cond ? document._getElementsByXPath('.//*' + cond, element) : [];
  } : function(element, className) {
    className = className.toString().strip();
    var elements = [], classNames = (/\s/.test(className) ? $w(className) : null);
    if (!classNames && !className) return elements;

    var nodes = $(element).getElementsByTagName('*');
    className = ' ' + className + ' ';

    for (var i = 0, child, cn; child = nodes[i]; i++) {
      if (child.className && (cn = ' ' + child.className + ' ') && (cn.include(className) ||
          (classNames && classNames.all(function(name) {
            return !name.toString().blank() && cn.include(' ' + name + ' ');
          }))))
        elements.push(Element.extend(child));
    }
    return elements;
  };

  return function(className, parentElement) {
    return $(parentElement || document.body).getElementsByClassName(className);
  };
}(Element.Methods);

/*--------------------------------------------------------------------------*/

Element.ClassNames = Class.create();
Element.ClassNames.prototype = {
  initialize: function(element) {
    this.element = $(element);
  },

  _each: function(iterator) {
    this.element.className.split(/\s+/).select(function(name) {
      return name.length > 0;
    })._each(iterator);
  },

  set: function(className) {
    this.element.className = className;
  },

  add: function(classNameToAdd) {
    if (this.include(classNameToAdd)) return;
    this.set($A(this).concat(classNameToAdd).join(' '));
  },

  remove: function(classNameToRemove) {
    if (!this.include(classNameToRemove)) return;
    this.set($A(this).without(classNameToRemove).join(' '));
  },

  toString: function() {
    return $A(this).join(' ');
  }
};

Object.extend(Element.ClassNames.prototype, Enumerable);

/*--------------------------------------------------------------------------*/

Element.addMethods();




// script.aculo.us scriptaculous.js v1.8.1, Thu Jan 03 22:07:12 -0500 2008

// Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// 
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// For details, see the script.aculo.us web site: http://script.aculo.us/

var Scriptaculous = {
  Version: '1.8.1',
  require: function(libraryName) {
    // inserting via DOM fails in Safari 2.0, so brute force approach
    document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>');
  },
  REQUIRED_PROTOTYPE: '1.6.0',
  load: function() {
    function convertVersionString(versionString){
      var r = versionString.split('.');
      return parseInt(r[0])*100000 + parseInt(r[1])*1000 + parseInt(r[2]);
    }
 
    if((typeof Prototype=='undefined') || 
       (typeof Element == 'undefined') || 
       (typeof Element.Methods=='undefined') ||
       (convertVersionString(Prototype.Version) < 
        convertVersionString(Scriptaculous.REQUIRED_PROTOTYPE)))
       throw("script.aculo.us requires the Prototype JavaScript framework >= " +
        Scriptaculous.REQUIRED_PROTOTYPE);
    
//    $A(document.getElementsByTagName("script")).findAll( function(s) {
//      return (s.src && s.src.match(/scriptaculous\.js(\?.*)?$/))
//    }).each( function(s) {
//      var path = s.src.replace(/scriptaculous\.js(\?.*)?$/,'');
//      var includes = s.src.match(/\?.*load=([a-z,]*)/);
//      (includes ? includes[1] : 'builder,effects,dragdrop,controls,slider,sound').split(',').each(
//       function(include) { Scriptaculous.require(path+include+'.js') });
//    });
  }
}

Scriptaculous.load();


// script.aculo.us builder.js v1.8.1, Thu Jan 03 22:07:12 -0500 2008

// Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/

var Builder = {
  NODEMAP: {
    AREA: 'map',
    CAPTION: 'table',
    COL: 'table',
    COLGROUP: 'table',
    LEGEND: 'fieldset',
    OPTGROUP: 'select',
    OPTION: 'select',
    PARAM: 'object',
    TBODY: 'table',
    TD: 'table',
    TFOOT: 'table',
    TH: 'table',
    THEAD: 'table',
    TR: 'table'
  },
  // note: For Firefox < 1.5, OPTION and OPTGROUP tags are currently broken,
  //       due to a Firefox bug
  node: function(elementName) {
    elementName = elementName.toUpperCase();
    
    // try innerHTML approach
    var parentTag = this.NODEMAP[elementName] || 'div';
    var parentElement = document.createElement(parentTag);
    try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
      parentElement.innerHTML = "<" + elementName + "></" + elementName + ">";
    } catch(e) {}
    var element = parentElement.firstChild || null;
      
    // see if browser added wrapping tags
    if(element && (element.tagName.toUpperCase() != elementName))
      element = element.getElementsByTagName(elementName)[0];
    
    // fallback to createElement approach
    if(!element) element = document.createElement(elementName);
    
    // abort if nothing could be created
    if(!element) return;

    // attributes (or text)
    if(arguments[1])
      if(this._isStringOrNumber(arguments[1]) ||
        (arguments[1] instanceof Array) ||
        arguments[1].tagName) {
          this._children(element, arguments[1]);
        } else {
          var attrs = this._attributes(arguments[1]);
          if(attrs.length) {
            try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707
              parentElement.innerHTML = "<" +elementName + " " +
                attrs + "></" + elementName + ">";
            } catch(e) {}
            element = parentElement.firstChild || null;
            // workaround firefox 1.0.X bug
            if(!element) {
              element = document.createElement(elementName);
              for(attr in arguments[1]) 
                element[attr == 'class' ? 'className' : attr] = arguments[1][attr];
            }
            if(element.tagName.toUpperCase() != elementName)
              element = parentElement.getElementsByTagName(elementName)[0];
          }
        } 

    // text, or array of children
    if(arguments[2])
      this._children(element, arguments[2]);

     return element;
  },
  _text: function(text) {
     return document.createTextNode(text);
  },

  ATTR_MAP: {
    'className': 'class',
    'htmlFor': 'for'
  },

  _attributes: function(attributes) {
    var attrs = [];
    for(attribute in attributes)
      attrs.push((attribute in this.ATTR_MAP ? this.ATTR_MAP[attribute] : attribute) +
          '="' + attributes[attribute].toString().escapeHTML().gsub(/"/,'&quot;') + '"');
    return attrs.join(" ");
  },
  _children: function(element, children) {
    if(children.tagName) {
      element.appendChild(children);
      return;
    }
    if(typeof children=='object') { // array can hold nodes and text
      children.flatten().each( function(e) {
        if(typeof e=='object')
          element.appendChild(e)
        else
          if(Builder._isStringOrNumber(e))
            element.appendChild(Builder._text(e));
      });
    } else
      if(Builder._isStringOrNumber(children))
        element.appendChild(Builder._text(children));
  },
  _isStringOrNumber: function(param) {
    return(typeof param=='string' || typeof param=='number');
  },
  build: function(html) {
    var element = this.node('div');
    $(element).update(html.strip());
    return element.down();
  },
  dump: function(scope) { 
    if(typeof scope != 'object' && typeof scope != 'function') scope = window; //global scope 
  
    var tags = ("A ABBR ACRONYM ADDRESS APPLET AREA B BASE BASEFONT BDO BIG BLOCKQUOTE BODY " +
      "BR BUTTON CAPTION CENTER CITE CODE COL COLGROUP DD DEL DFN DIR DIV DL DT EM FIELDSET " +
      "FONT FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HR HTML I IFRAME IMG INPUT INS ISINDEX "+
      "KBD LABEL LEGEND LI LINK MAP MENU META NOFRAMES NOSCRIPT OBJECT OL OPTGROUP OPTION P "+
      "PARAM PRE Q S SAMP SCRIPT SELECT SMALL SPAN STRIKE STRONG STYLE SUB SUP TABLE TBODY TD "+
      "TEXTAREA TFOOT TH THEAD TITLE TR TT U UL VAR").split(/\s+/);
  
    tags.each( function(tag){ 
      scope[tag] = function() { 
        return Builder.node.apply(Builder, [tag].concat($A(arguments)));  
      } 
    });
  }
}

// script.aculo.us effects.js v1.8.1, Thu Jan 03 22:07:12 -0500 2008

// Copyright (c) 2005-2007 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// Contributors:
//  Justin Palmer (http://encytemedia.com/)
//  Mark Pilgrim (http://diveintomark.org/)
//  Martin Bialasinki
// 
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/ 

// converts rgb() and #xxx to #xxxxxx format,  
// returns self (or first argument) if not convertable  
String.prototype.parseColor = function() {  
  var color = '#';
  if (this.slice(0,4) == 'rgb(') {  
    var cols = this.slice(4,this.length-1).split(',');  
    var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);  
  } else {  
    if (this.slice(0,1) == '#') {  
      if (this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase();  
      if (this.length==7) color = this.toLowerCase();  
    }  
  }  
  return (color.length==7 ? color : (arguments[0] || this));  
};

/*--------------------------------------------------------------------------*/

Element.collectTextNodes = function(element) {  
  return $A($(element).childNodes).collect( function(node) {
    return (node.nodeType==3 ? node.nodeValue : 
      (node.hasChildNodes() ? Element.collectTextNodes(node) : ''));
  }).flatten().join('');
};

Element.collectTextNodesIgnoreClass = function(element, className) {  
  return $A($(element).childNodes).collect( function(node) {
    return (node.nodeType==3 ? node.nodeValue : 
      ((node.hasChildNodes() && !Element.hasClassName(node,className)) ? 
        Element.collectTextNodesIgnoreClass(node, className) : ''));
  }).flatten().join('');
};

Element.setContentZoom = function(element, percent) {
  element = $(element);  
  element.setStyle({fontSize: (percent/100) + 'em'});   
  if (Prototype.Browser.WebKit) window.scrollBy(0,0);
  return element;
};

Element.getInlineOpacity = function(element){
  return $(element).style.opacity || '';
};

Element.forceRerendering = function(element) {
  try {
    element = $(element);
    var n = document.createTextNode(' ');
    element.appendChild(n);
    element.removeChild(n);
  } catch(e) { }
};

/*--------------------------------------------------------------------------*/

var Effect = {
  _elementDoesNotExistError: {
    name: 'ElementDoesNotExistError',
    message: 'The specified DOM element does not exist, but is required for this effect to operate'
  },
  Transitions: {
    linear: Prototype.K,
    sinoidal: function(pos) {
      return (-Math.cos(pos*Math.PI)/2) + 0.5;
    },
    reverse: function(pos) {
      return 1-pos;
    },
    flicker: function(pos) {
      var pos = ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4;
      return pos > 1 ? 1 : pos;
    },
    wobble: function(pos) {
      return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5;
    },
    pulse: function(pos, pulses) { 
      pulses = pulses || 5; 
      return (
        ((pos % (1/pulses)) * pulses).round() == 0 ? 
              ((pos * pulses * 2) - (pos * pulses * 2).floor()) : 
          1 - ((pos * pulses * 2) - (pos * pulses * 2).floor())
        );
    },
    spring: function(pos) { 
      return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6)); 
    },
    none: function(pos) {
      return 0;
    },
    full: function(pos) {
      return 1;
    }
  },
  DefaultOptions: {
    duration:   1.0,   // seconds
    fps:        100,   // 100= assume 66fps max.
    sync:       false, // true for combining
    from:       0.0,
    to:         1.0,
    delay:      0.0,
    queue:      'parallel'
  },
  tagifyText: function(element) {
    var tagifyStyle = 'position:relative';
    if (Prototype.Browser.IE) tagifyStyle += ';zoom:1';
    
    element = $(element);
    $A(element.childNodes).each( function(child) {
      if (child.nodeType==3) {
        child.nodeValue.toArray().each( function(character) {
          element.insertBefore(
            new Element('span', {style: tagifyStyle}).update(
              character == ' ' ? String.fromCharCode(160) : character), 
              child);
        });
        Element.remove(child);
      }
    });
  },
  multiple: function(element, effect) {
    var elements;
    if (((typeof element == 'object') || 
        Object.isFunction(element)) && 
       (element.length))
      elements = element;
    else
      elements = $(element).childNodes;
      
    var options = Object.extend({
      speed: 0.1,
      delay: 0.0
    }, arguments[2] || { });
    var masterDelay = options.delay;

    $A(elements).each( function(element, index) {
      new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay }));
    });
  },
  PAIRS: {
    'slide':  ['SlideDown','SlideUp'],
    'blind':  ['BlindDown','BlindUp'],
    'appear': ['Appear','Fade']
  },
  toggle: function(element, effect) {
    element = $(element);
    effect = (effect || 'appear').toLowerCase();
    var options = Object.extend({
      queue: { position:'end', scope:(element.id || 'global'), limit: 1 }
    }, arguments[2] || { });
    Effect[element.visible() ? 
      Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options);
  }
};

Effect.DefaultOptions.transition = Effect.Transitions.sinoidal;

/* ------------- core effects ------------- */

Effect.ScopedQueue = Class.create(Enumerable, {
  initialize: function() {
    this.effects  = [];
    this.interval = null;    
  },
  _each: function(iterator) {
    this.effects._each(iterator);
  },
  add: function(effect) {
    var timestamp = new Date().getTime();
    
    var position = Object.isString(effect.options.queue) ? 
      effect.options.queue : effect.options.queue.position;
    
    switch(position) {
      case 'front':
        // move unstarted effects after this effect  
        this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) {
            e.startOn  += effect.finishOn;
            e.finishOn += effect.finishOn;
          });
        break;
      case 'with-last':
        timestamp = this.effects.pluck('startOn').max() || timestamp;
        break;
      case 'end':
        // start effect after last queued effect has finished
        timestamp = this.effects.pluck('finishOn').max() || timestamp;
        break;
    }
    
    effect.startOn  += timestamp;
    effect.finishOn += timestamp;

    if (!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit))
      this.effects.push(effect);
    
    if (!this.interval)
      this.interval = setInterval(this.loop.bind(this), 15);
  },
  remove: function(effect) {
    this.effects = this.effects.reject(function(e) { return e==effect });
    if (this.effects.length == 0) {
      clearInterval(this.interval);
      this.interval = null;
    }
  },
  loop: function() {
    var timePos = new Date().getTime();
    for(var i=0, len=this.effects.length;i<len;i++) 
      this.effects[i] && this.effects[i].loop(timePos);
  }
});

Effect.Queues = {
  instances: $H(),
  get: function(queueName) {
    if (!Object.isString(queueName)) return queueName;
    
    return this.instances.get(queueName) ||
      this.instances.set(queueName, new Effect.ScopedQueue());
  }
};
Effect.Queue = Effect.Queues.get('global');

Effect.Base = Class.create({
  position: null,
  start: function(options) {
    function codeForEvent(options,eventName){
      return (
        (options[eventName+'Internal'] ? 'this.options.'+eventName+'Internal(this);' : '') +
        (options[eventName] ? 'this.options.'+eventName+'(this);' : '')
      );
    }
    if (options && options.transition === false) options.transition = Effect.Transitions.linear;
    this.options      = Object.extend(Object.extend({ },Effect.DefaultOptions), options || { });
    this.currentFrame = 0;
    this.state        = 'idle';
    this.startOn      = this.options.delay*1000;
    this.finishOn     = this.startOn+(this.options.duration*1000);
    this.fromToDelta  = this.options.to-this.options.from;
    this.totalTime    = this.finishOn-this.startOn;
    this.totalFrames  = this.options.fps*this.options.duration;
    
    eval('this.render = function(pos){ '+
      'if (this.state=="idle"){this.state="running";'+
      codeForEvent(this.options,'beforeSetup')+
      (this.setup ? 'this.setup();':'')+ 
      codeForEvent(this.options,'afterSetup')+
      '};if (this.state=="running"){'+
      'pos=this.options.transition(pos)*'+this.fromToDelta+'+'+this.options.from+';'+
      'this.position=pos;'+
      codeForEvent(this.options,'beforeUpdate')+
      (this.update ? 'this.update(pos);':'')+
      codeForEvent(this.options,'afterUpdate')+
      '}}');
    
    this.event('beforeStart');
    if (!this.options.sync)
      Effect.Queues.get(Object.isString(this.options.queue) ? 
        'global' : this.options.queue.scope).add(this);
  },
  loop: function(timePos) {
    if (timePos >= this.startOn) {
      if (timePos >= this.finishOn) {
        this.render(1.0);
        this.cancel();
        this.event('beforeFinish');
        if (this.finish) this.finish(); 
        this.event('afterFinish');
        return;  
      }
      var pos   = (timePos - this.startOn) / this.totalTime,
          frame = (pos * this.totalFrames).round();
      if (frame > this.currentFrame) {
        this.render(pos);
        this.currentFrame = frame;
      }
    }
  },
  cancel: function() {
    if (!this.options.sync)
      Effect.Queues.get(Object.isString(this.options.queue) ? 
        'global' : this.options.queue.scope).remove(this);
    this.state = 'finished';
  },
  event: function(eventName) {
    if (this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this);
    if (this.options[eventName]) this.options[eventName](this);
  },
  inspect: function() {
    var data = $H();
    for(property in this)
      if (!Object.isFunction(this[property])) data.set(property, this[property]);
    return '#<Effect:' + data.inspect() + ',options:' + $H(this.options).inspect() + '>';
  }
});

Effect.Parallel = Class.create(Effect.Base, {
  initialize: function(effects) {
    this.effects = effects || [];
    this.start(arguments[1]);
  },
  update: function(position) {
    this.effects.invoke('render', position);
  },
  finish: function(position) {
    this.effects.each( function(effect) {
      effect.render(1.0);
      effect.cancel();
      effect.event('beforeFinish');
      if (effect.finish) effect.finish(position);
      effect.event('afterFinish');
    });
  }
});

Effect.Tween = Class.create(Effect.Base, {
  initialize: function(object, from, to) {
    object = Object.isString(object) ? $(object) : object;
    var args = $A(arguments), method = args.last(), 
      options = args.length == 5 ? args[3] : null;
    this.method = Object.isFunction(method) ? method.bind(object) :
      Object.isFunction(object[method]) ? object[method].bind(object) : 
      function(value) { object[method] = value };
    this.start(Object.extend({ from: from, to: to }, options || { }));
  },
  update: function(position) {
    this.method(position);
  }
});

Effect.Event = Class.create(Effect.Base, {
  initialize: function() {
    this.start(Object.extend({ duration: 0 }, arguments[0] || { }));
  },
  update: Prototype.emptyFunction
});

Effect.Opacity = Class.create(Effect.Base, {
  initialize: function(element) {
    this.element = $(element);
    if (!this.element) throw(Effect._elementDoesNotExistError);
    // make this work on IE on elements without 'layout'
    if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
      this.element.setStyle({zoom: 1});
    var options = Object.extend({
      from: this.element.getOpacity() || 0.0,
      to:   1.0
    }, arguments[1] || { });
    this.start(options);
  },
  update: function(position) {
    this.element.setOpacity(position);
  }
});

Effect.Move = Class.create(Effect.Base, {
  initialize: function(element) {
    this.element = $(element);
    if (!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({
      x:    0,
      y:    0,
      mode: 'relative'
    }, arguments[1] || { });
    this.start(options);
  },
  setup: function() {
    this.element.makePositioned();
    this.originalLeft = parseFloat(this.element.getStyle('left') || '0');
    this.originalTop  = parseFloat(this.element.getStyle('top')  || '0');
    if (this.options.mode == 'absolute') {
      this.options.x = this.options.x - this.originalLeft;
      this.options.y = this.options.y - this.originalTop;
    }
  },
  update: function(position) {
    this.element.setStyle({
      left: (this.options.x  * position + this.originalLeft).round() + 'px',
      top:  (this.options.y  * position + this.originalTop).round()  + 'px'
    });
  }
});

// for backwards compatibility
Effect.MoveBy = function(element, toTop, toLeft) {
  return new Effect.Move(element, 
    Object.extend({ x: toLeft, y: toTop }, arguments[3] || { }));
};

Effect.Scale = Class.create(Effect.Base, {
  initialize: function(element, percent) {
    this.element = $(element);
    if (!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({
      scaleX: true,
      scaleY: true,
      scaleContent: true,
      scaleFromCenter: false,
      scaleMode: 'box',        // 'box' or 'contents' or { } with provided values
      scaleFrom: 100.0,
      scaleTo:   percent
    }, arguments[2] || { });
    this.start(options);
  },
  setup: function() {
    this.restoreAfterFinish = this.options.restoreAfterFinish || false;
    this.elementPositioning = this.element.getStyle('position');
    
    this.originalStyle = { };
    ['top','left','width','height','fontSize'].each( function(k) {
      this.originalStyle[k] = this.element.style[k];
    }.bind(this));
      
    this.originalTop  = this.element.offsetTop;
    this.originalLeft = this.element.offsetLeft;
    
    var fontSize = this.element.getStyle('font-size') || '100%';
    ['em','px','%','pt'].each( function(fontSizeType) {
      if (fontSize.indexOf(fontSizeType)>0) {
        this.fontSize     = parseFloat(fontSize);
        this.fontSizeType = fontSizeType;
      }
    }.bind(this));
    
    this.factor = (this.options.scaleTo - this.options.scaleFrom)/100;
    
    this.dims = null;
    if (this.options.scaleMode=='box')
      this.dims = [this.element.offsetHeight, this.element.offsetWidth];
    if (/^content/.test(this.options.scaleMode))
      this.dims = [this.element.scrollHeight, this.element.scrollWidth];
    if (!this.dims)
      this.dims = [this.options.scaleMode.originalHeight,
                   this.options.scaleMode.originalWidth];
  },
  update: function(position) {
    var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position);
    if (this.options.scaleContent && this.fontSize)
      this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType });
    this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale);
  },
  finish: function(position) {
    if (this.restoreAfterFinish) this.element.setStyle(this.originalStyle);
  },
  setDimensions: function(height, width) {
    var d = { };
    if (this.options.scaleX) d.width = width.round() + 'px';
    if (this.options.scaleY) d.height = height.round() + 'px';
    if (this.options.scaleFromCenter) {
      var topd  = (height - this.dims[0])/2;
      var leftd = (width  - this.dims[1])/2;
      if (this.elementPositioning == 'absolute') {
        if (this.options.scaleY) d.top = this.originalTop-topd + 'px';
        if (this.options.scaleX) d.left = this.originalLeft-leftd + 'px';
      } else {
        if (this.options.scaleY) d.top = -topd + 'px';
        if (this.options.scaleX) d.left = -leftd + 'px';
      }
    }
    this.element.setStyle(d);
  }
});

Effect.Highlight = Class.create(Effect.Base, {
  initialize: function(element) {
    this.element = $(element);
    if (!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || { });
    this.start(options);
  },
  setup: function() {
    // Prevent executing on elements not in the layout flow
    if (this.element.getStyle('display')=='none') { this.cancel(); return; }
    // Disable background image during the effect
    this.oldStyle = { };
    if (!this.options.keepBackgroundImage) {
      this.oldStyle.backgroundImage = this.element.getStyle('background-image');
      this.element.setStyle({backgroundImage: 'none'});
    }
    if (!this.options.endcolor)
      this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff');
    if (!this.options.restorecolor)
      this.options.restorecolor = this.element.getStyle('background-color');
    // init color calculations
    this._base  = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
    this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this));
  },
  update: function(position) {
    this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){
      return m+((this._base[i]+(this._delta[i]*position)).round().toColorPart()); }.bind(this)) });
  },
  finish: function() {
    this.element.setStyle(Object.extend(this.oldStyle, {
      backgroundColor: this.options.restorecolor
    }));
  }
});

Effect.ScrollTo = function(element) {
  var options = arguments[1] || { },
    scrollOffsets = document.viewport.getScrollOffsets(),
    elementOffsets = $(element).cumulativeOffset(),
    max = (window.height || document.body.scrollHeight) - document.viewport.getHeight();  

  if (options.offset) elementOffsets[1] += options.offset;

  return new Effect.Tween(null,
    scrollOffsets.top,
    elementOffsets[1] > max ? max : elementOffsets[1],
    options,
    function(p){ scrollTo(scrollOffsets.left, p.round()) }
  );
};

/* ------------- combination effects ------------- */

Effect.Fade = function(element) {
  element = $(element);
  if(-[1,]) var oldOpacity = element.getInlineOpacity(); else var oldOpacity = 1;
  var options = Object.extend({
    from: element.getOpacity() || 1.0,
    to:   0.0,
    afterFinishInternal: function(effect) { 
      if (effect.options.to!=0) return;
      effect.element.hide().setStyle({opacity: oldOpacity}); 
    }
  }, arguments[1] || { });
  return new Effect.Opacity(element,options);
};

Effect.Appear = function(element) {
  element = $(element);
  var options = Object.extend({
  from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0),
  to:   1.0,
  // force Safari to render floated elements properly
  afterFinishInternal: function(effect) {
    effect.element.forceRerendering();
  },
  beforeSetup: function(effect) {
    effect.element.setOpacity(effect.options.from).show(); 
  }}, arguments[1] || { });
  return new Effect.Opacity(element,options);
};

Effect.Puff = function(element) {
  element = $(element);
  var oldStyle = { 
    opacity: element.getInlineOpacity(), 
    position: element.getStyle('position'),
    top:  element.style.top,
    left: element.style.left,
    width: element.style.width,
    height: element.style.height
  };
  return new Effect.Parallel(
   [ new Effect.Scale(element, 200, 
      { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }), 
     new Effect.Opacity(element, { sync: true, to: 0.0 } ) ], 
     Object.extend({ duration: 1.0, 
      beforeSetupInternal: function(effect) {
        Position.absolutize(effect.effects[0].element)
      },
      afterFinishInternal: function(effect) {
         effect.effects[0].element.hide().setStyle(oldStyle); }
     }, arguments[1] || { })
   );
};

Effect.BlindUp = function(element) {
  element = $(element);
  element.makeClipping();
  return new Effect.Scale(element, 0,
    Object.extend({ scaleContent: false, 
      scaleX: false, 
      restoreAfterFinish: true,
      afterFinishInternal: function(effect) {
        effect.element.hide().undoClipping();
      } 
    }, arguments[1] || { })
  );
};

Effect.BlindDown = function(element) {
  element = $(element);
  var elementDimensions = element.getDimensions();
  return new Effect.Scale(element, 100, Object.extend({ 
    scaleContent: false, 
    scaleX: false,
    scaleFrom: 0,
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    restoreAfterFinish: true,
    afterSetup: function(effect) {
      effect.element.makeClipping().setStyle({height: '0px'}).show(); 
    },  
    afterFinishInternal: function(effect) {
      effect.element.undoClipping();
    }
  }, arguments[1] || { }));
};

Effect.SwitchOff = function(element) {
  element = $(element);
  var oldOpacity = element.getInlineOpacity();
  return new Effect.Appear(element, Object.extend({
    duration: 0.4,
    from: 0,
    transition: Effect.Transitions.flicker,
    afterFinishInternal: function(effect) {
      new Effect.Scale(effect.element, 1, { 
        duration: 0.3, scaleFromCenter: true,
        scaleX: false, scaleContent: false, restoreAfterFinish: true,
        beforeSetup: function(effect) { 
          effect.element.makePositioned().makeClipping();
        },
        afterFinishInternal: function(effect) {
          effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity});
        }
      })
    }
  }, arguments[1] || { }));
};

Effect.DropOut = function(element) {
  element = $(element);
  var oldStyle = {
    top: element.getStyle('top'),
    left: element.getStyle('left'),
    opacity: element.getInlineOpacity() };
  return new Effect.Parallel(
    [ new Effect.Move(element, {x: 0, y: 100, sync: true }), 
      new Effect.Opacity(element, { sync: true, to: 0.0 }) ],
    Object.extend(
      { duration: 0.5,
        beforeSetup: function(effect) {
          effect.effects[0].element.makePositioned(); 
        },
        afterFinishInternal: function(effect) {
          effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);
        } 
      }, arguments[1] || { }));
};

Effect.Shake = function(element) {
  element = $(element);
  var options = Object.extend({
    distance: 20,
    duration: 0.5
  }, arguments[1] || {});
  var distance = parseFloat(options.distance);
  var split = parseFloat(options.duration) / 10.0;
  var oldStyle = {
    top: element.getStyle('top'),
    left: element.getStyle('left') };
    return new Effect.Move(element,
      { x:  distance, y: 0, duration: split, afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x: -distance*2, y: 0, duration: split*2,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x:  distance*2, y: 0, duration: split*2,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x: -distance*2, y: 0, duration: split*2,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x:  distance*2, y: 0, duration: split*2,  afterFinishInternal: function(effect) {
    new Effect.Move(effect.element,
      { x: -distance, y: 0, duration: split, afterFinishInternal: function(effect) {
        effect.element.undoPositioned().setStyle(oldStyle);
  }}) }}) }}) }}) }}) }});
};

Effect.SlideDown = function(element) {
  element = $(element).cleanWhitespace();
  // SlideDown need to have the content of the element wrapped in a container element with fixed height!
  var oldInnerBottom = element.down().getStyle('bottom');
  var elementDimensions = element.getDimensions();
  return new Effect.Scale(element, 100, Object.extend({ 
    scaleContent: false, 
    scaleX: false, 
    scaleFrom: window.opera ? 0 : 1,
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    restoreAfterFinish: true,
    afterSetup: function(effect) {
      effect.element.makePositioned();
      effect.element.down().makePositioned();
      if (window.opera) effect.element.setStyle({top: ''});
      effect.element.makeClipping().setStyle({height: '0px'}).show(); 
    },
    afterUpdateInternal: function(effect) {
      effect.element.down().setStyle({bottom:
        (effect.dims[0] - effect.element.clientHeight) + 'px' }); 
    },
    afterFinishInternal: function(effect) {
      effect.element.undoClipping().undoPositioned();
      effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); }
    }, arguments[1] || { })
  );
};

Effect.SlideUp = function(element) {
  element = $(element).cleanWhitespace();
  var oldInnerBottom = element.down().getStyle('bottom');
  var elementDimensions = element.getDimensions();
  return new Effect.Scale(element, window.opera ? 0 : 1,
   Object.extend({ scaleContent: false, 
    scaleX: false, 
    scaleMode: 'box',
    scaleFrom: 100,
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    restoreAfterFinish: true,
    afterSetup: function(effect) {
      effect.element.makePositioned();
      effect.element.down().makePositioned();
      if (window.opera) effect.element.setStyle({top: ''});
      effect.element.makeClipping().show();
    },  
    afterUpdateInternal: function(effect) {
      effect.element.down().setStyle({bottom:
        (effect.dims[0] - effect.element.clientHeight) + 'px' });
    },
    afterFinishInternal: function(effect) {
      effect.element.hide().undoClipping().undoPositioned();
      effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom});
    }
   }, arguments[1] || { })
  );
};

// Bug in opera makes the TD containing this element expand for a instance after finish 
Effect.Squish = function(element) {
  return new Effect.Scale(element, window.opera ? 1 : 0, { 
    restoreAfterFinish: true,
    beforeSetup: function(effect) {
      effect.element.makeClipping(); 
    },  
    afterFinishInternal: function(effect) {
      effect.element.hide().undoClipping(); 
    }
  });
};

Effect.Grow = function(element) {
  element = $(element);
  var options = Object.extend({
    direction: 'center',
    moveTransition: Effect.Transitions.sinoidal,
    scaleTransition: Effect.Transitions.sinoidal,
    opacityTransition: Effect.Transitions.full
  }, arguments[1] || { });
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    height: element.style.height,
    width: element.style.width,
    opacity: element.getInlineOpacity() };

  var dims = element.getDimensions();    
  var initialMoveX, initialMoveY;
  var moveX, moveY;
  
  switch (options.direction) {
    case 'top-left':
      initialMoveX = initialMoveY = moveX = moveY = 0; 
      break;
    case 'top-right':
      initialMoveX = dims.width;
      initialMoveY = moveY = 0;
      moveX = -dims.width;
      break;
    case 'bottom-left':
      initialMoveX = moveX = 0;
      initialMoveY = dims.height;
      moveY = -dims.height;
      break;
    case 'bottom-right':
      initialMoveX = dims.width;
      initialMoveY = dims.height;
      moveX = -dims.width;
      moveY = -dims.height;
      break;
    case 'center':
      initialMoveX = dims.width / 2;
      initialMoveY = dims.height / 2;
      moveX = -dims.width / 2;
      moveY = -dims.height / 2;
      break;
  }
  
  return new Effect.Move(element, {
    x: initialMoveX,
    y: initialMoveY,
    duration: 0.01, 
    beforeSetup: function(effect) {
      effect.element.hide().makeClipping().makePositioned();
    },
    afterFinishInternal: function(effect) {
      new Effect.Parallel(
        [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }),
          new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }),
          new Effect.Scale(effect.element, 100, {
            scaleMode: { originalHeight: dims.height, originalWidth: dims.width }, 
            sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})
        ], Object.extend({
             beforeSetup: function(effect) {
               effect.effects[0].element.setStyle({height: '0px'}).show(); 
             },
             afterFinishInternal: function(effect) {
               effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle); 
             }
           }, options)
      )
    }
  });
};

Effect.Shrink = function(element) {
  element = $(element);
  var options = Object.extend({
    direction: 'center',
    moveTransition: Effect.Transitions.sinoidal,
    scaleTransition: Effect.Transitions.sinoidal,
    opacityTransition: Effect.Transitions.none
  }, arguments[1] || { });
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    height: element.style.height,
    width: element.style.width,
    opacity: element.getInlineOpacity() };

  var dims = element.getDimensions();
  var moveX, moveY;
  
  switch (options.direction) {
    case 'top-left':
      moveX = moveY = 0;
      break;
    case 'top-right':
      moveX = dims.width;
      moveY = 0;
      break;
    case 'bottom-left':
      moveX = 0;
      moveY = dims.height;
      break;
    case 'bottom-right':
      moveX = dims.width;
      moveY = dims.height;
      break;
    case 'center':  
      moveX = dims.width / 2;
      moveY = dims.height / 2;
      break;
  }
  
  return new Effect.Parallel(
    [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }),
      new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}),
      new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })
    ], Object.extend({            
         beforeStartInternal: function(effect) {
           effect.effects[0].element.makePositioned().makeClipping(); 
         },
         afterFinishInternal: function(effect) {
           effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); }
       }, options)
  );
};

Effect.Pulsate = function(element) {
  element = $(element);
  var options    = arguments[1] || { };
  var oldOpacity = element.getInlineOpacity();
  var transition = options.transition || Effect.Transitions.sinoidal;
  var reverser   = function(pos){ return transition(1-Effect.Transitions.pulse(pos, options.pulses)) };
  reverser.bind(transition);
  return new Effect.Opacity(element, 
    Object.extend(Object.extend({  duration: 2.0, from: 0,
      afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); }
    }, options), {transition: reverser}));
};

Effect.Fold = function(element) {
  element = $(element);
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    width: element.style.width,
    height: element.style.height };
  element.makeClipping();
  return new Effect.Scale(element, 5, Object.extend({   
    scaleContent: false,
    scaleX: false,
    afterFinishInternal: function(effect) {
    new Effect.Scale(element, 1, { 
      scaleContent: false, 
      scaleY: false,
      afterFinishInternal: function(effect) {
        effect.element.hide().undoClipping().setStyle(oldStyle);
      } });
  }}, arguments[1] || { }));
};

Effect.Morph = Class.create(Effect.Base, {
  initialize: function(element) {
    this.element = $(element);
    if (!this.element) throw(Effect._elementDoesNotExistError);
    var options = Object.extend({
      style: { }
    }, arguments[1] || { });
    
    if (!Object.isString(options.style)) this.style = $H(options.style);
    else {
      if (options.style.include(':'))
        this.style = options.style.parseStyle();
      else {
        this.element.addClassName(options.style);
        this.style = $H(this.element.getStyles());
        this.element.removeClassName(options.style);
        var css = this.element.getStyles();
        this.style = this.style.reject(function(style) {
          return style.value == css[style.key];
        });
        options.afterFinishInternal = function(effect) {
          effect.element.addClassName(effect.options.style);
          effect.transforms.each(function(transform) {
            effect.element.style[transform.style] = '';
          });
        }
      }
    }
    this.start(options);
  },
  
  setup: function(){
    function parseColor(color){
      if (!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff';
      color = color.parseColor();
      return $R(0,2).map(function(i){
        return parseInt( color.slice(i*2+1,i*2+3), 16 ) 
      });
    }
    this.transforms = this.style.map(function(pair){
      var property = pair[0], value = pair[1], unit = null;

      if (value.parseColor('#zzzzzz') != '#zzzzzz') {
        value = value.parseColor();
        unit  = 'color';
      } else if (property == 'opacity') {
        value = parseFloat(value);
        if (Prototype.Browser.IE && (!this.element.currentStyle.hasLayout))
          this.element.setStyle({zoom: 1});
      } else if (Element.CSS_LENGTH.test(value)) {
          var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/);
          value = parseFloat(components[1]);
          unit = (components.length == 3) ? components[2] : null;
      }

      var originalValue = this.element.getStyle(property);
      return { 
        style: property.camelize(), 
        originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0), 
        targetValue: unit=='color' ? parseColor(value) : value,
        unit: unit
      };
    }.bind(this)).reject(function(transform){
      return (
        (transform.originalValue == transform.targetValue) ||
        (
          transform.unit != 'color' &&
          (isNaN(transform.originalValue) || isNaN(transform.targetValue))
        )
      )
    });
  },
  update: function(position) {
    var style = { }, transform, i = this.transforms.length;
    while(i--)
      style[(transform = this.transforms[i]).style] = 
        transform.unit=='color' ? '#'+
          (Math.round(transform.originalValue[0]+
            (transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart() +
          (Math.round(transform.originalValue[1]+
            (transform.targetValue[1]-transform.originalValue[1])*position)).toColorPart() +
          (Math.round(transform.originalValue[2]+
            (transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart() :
        (transform.originalValue +
          (transform.targetValue - transform.originalValue) * position).toFixed(3) + 
            (transform.unit === null ? '' : transform.unit);
    this.element.setStyle(style, true);
  }
});

Effect.Transform = Class.create({
  initialize: function(tracks){
    this.tracks  = [];
    this.options = arguments[1] || { };
    this.addTracks(tracks);
  },
  addTracks: function(tracks){
    tracks.each(function(track){
      track = $H(track);
      var data = track.values().first();
      this.tracks.push($H({
        ids:     track.keys().first(),
        effect:  Effect.Morph,
        options: { style: data }
      }));
    }.bind(this));
    return this;
  },
  play: function(){
    return new Effect.Parallel(
      this.tracks.map(function(track){
        var ids = track.get('ids'), effect = track.get('effect'), options = track.get('options');
        var elements = [$(ids) || $$(ids)].flatten();
        return elements.map(function(e){ return new effect(e, Object.extend({ sync:true }, options)) });
      }).flatten(),
      this.options
    );
  }
});

Element.CSS_PROPERTIES = $w(
  'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' + 
  'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' +
  'borderRightColor borderRightStyle borderRightWidth borderSpacing ' +
  'borderTopColor borderTopStyle borderTopWidth bottom clip color ' +
  'fontSize fontWeight height left letterSpacing lineHeight ' +
  'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+
  'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' +
  'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' +
  'right textIndent top width wordSpacing zIndex');
  
Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;

String.__parseStyleElement = document.createElement('div');
String.prototype.parseStyle = function(){
  var style, styleRules = $H();
  if (Prototype.Browser.WebKit)
    style = new Element('div',{style:this}).style;
  else {
    String.__parseStyleElement.innerHTML = '<div style="' + this + '"></div>';
    style = String.__parseStyleElement.childNodes[0].style;
  }
  
  Element.CSS_PROPERTIES.each(function(property){
    if (style[property]) styleRules.set(property, style[property]); 
  });
  
  if (Prototype.Browser.IE && this.include('opacity'))
    styleRules.set('opacity', this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]);

  return styleRules;
};

if (document.defaultView && document.defaultView.getComputedStyle) {
  Element.getStyles = function(element) {
    var css = document.defaultView.getComputedStyle($(element), null);
    return Element.CSS_PROPERTIES.inject({ }, function(styles, property) {
      styles[property] = css[property];
      return styles;
    });
  };
} else {
  Element.getStyles = function(element) {
    element = $(element);
    var css = element.currentStyle, styles;
    styles = Element.CSS_PROPERTIES.inject({ }, function(results, property) {
      results[property] = css[property];
      return results;
    });
    if (!styles.opacity) styles.opacity = element.getOpacity();
    return styles;
  };
};

Effect.Methods = {
  morph: function(element, style) {
    element = $(element);
    new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || { }));
    return element;
  },
  visualEffect: function(element, effect, options) {
    element = $(element)
    var s = effect.dasherize().camelize(), klass = s.charAt(0).toUpperCase() + s.substring(1);
    new Effect[klass](element, options);
    return element;
  },
  highlight: function(element, options) {
    element = $(element);
    new Effect.Highlight(element, options);
    return element;
  }
};

$w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+
  'pulsate shake puff squish switchOff dropOut').each(
  function(effect) { 
    Effect.Methods[effect] = function(element, options){
      element = $(element);
      Effect[effect.charAt(0).toUpperCase() + effect.substring(1)](element, options);
      return element;
    }
  }
);

$w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each( 
  function(f) { Effect.Methods[f] = Element[f]; }
);

Element.addMethods(Effect.Methods);


// -----------------------------------------------------------------------------------
//
//    Lightbox v2.04
//    by Lokesh Dhakar - http://www.lokeshdhakar.com
//    Last Modification: 2/9/08
//
//    For more information, visit:
//    http://lokeshdhakar.com/projects/lightbox2/
//
//    Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
//      - Free for use in both personal and commercial projects
//        - Attribution requires leaving author name, author link, and the license info intact.
//    
//  Thanks: Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.com), and Thomas Fuchs(mir.aculo.us) for ideas, libs, and snippets.
//          Artemy Tregubenko (arty.name) for cleanup and help in updating to latest ver of proto-aculous.
//
// -----------------------------------------------------------------------------------
/*

    Table of Contents
    -----------------
    Configuration

    Lightbox Class Declaration
    - initialize()
    - updateImageList()
    - start()
    - changeImage()
    - resizeImageContainer()
    - showImage()
    - updateDetails()
    - updateNav()
    - enableKeyboardNav()
    - disableKeyboardNav()
    - keyboardAction()
    - preloadNeighborImages()
    - end()
    
    Function Calls
    - document.observe()
   
*/
// -----------------------------------------------------------------------------------

//
//  Configurationl
//
LightboxOptions = Object.extend({
    fileLoadingImage:        '/templates/default/n_img/gallery/loading.gif',     
    fileBottomNavCloseImage: '/templates/default/n_img/gallery/closelabel.gif',

    overlayOpacity: 0.8,   // controls transparency of shadow overlay

    animate: true,         // toggles resizing animations
    resizeSpeed: 7,        // controls the speed of the image resizing animations (1=slowest and 10=fastest)

    borderSize: 10,         //if you adjust the padding in the CSS, you will need to update this variable

    // When grouping images this is used to write: Image # of #.
    // Change it for non-english localization
    labelImage: "Image",
    labelOf: "of"
}, window.LightboxOptions || {});

// -----------------------------------------------------------------------------------

var Lightbox = Class.create();

Lightbox.prototype = {
    imageArray: [],
    activeImage: undefined,
    
    // initialize()
    // Constructor runs on completion of the DOM loading. Calls updateImageList and then
    // the function inserts html at the bottom of the page which is used to display the shadow 
    // overlay and the image container.
    //
    initialize: function() {    
        
        this.updateImageList();
        
        this.keyboardAction = this.keyboardAction.bindAsEventListener(this);

        if (LightboxOptions.resizeSpeed > 10) LightboxOptions.resizeSpeed = 10;
        if (LightboxOptions.resizeSpeed < 1)  LightboxOptions.resizeSpeed = 1;

        this.resizeDuration = LightboxOptions.animate ? ((11 - LightboxOptions.resizeSpeed) * 0.15) : 0;
        this.overlayDuration = LightboxOptions.animate ? 0.2 : 0;  // shadow fade in/out duration

        // When Lightbox starts it will resize itself from 250 by 250 to the current image dimension.
        // If animations are turned off, it will be hidden as to prevent a flicker of a
        // white 250 by 250 box.
        var size = (LightboxOptions.animate ? 250 : 1) + 'px';
        

        // Code inserts html at the bottom of the page that looks similar to this:
        //
        //  <div id="overlay"></div>
        //  <div id="lightbox">
        //      <div id="outerImageContainer">
        //          <div id="imageContainer">
        //              <img id="lightboxImage">
        //              <div style="" id="hoverNav">
        //                  <a href="#" id="prevLink"></a>
        //                  <a href="#" id="nextLink"></a>
        //              </div>
        //              <div id="loading">
        //                  <a href="#" id="loadingLink">
        //                      <img src="images/loading.gif">
        //                  </a>
        //              </div>
        //          </div>
        //      </div>
        //      <div id="imageDataContainer">
        //          <div id="imageData">
        //              <div id="imageDetails">
        //                  <span id="caption"></span>
        //                  <span id="numberDisplay"></span>
        //              </div>
        //              <div id="bottomNav">
        //                  <a href="#" id="bottomNavClose">
        //                      <img src="images/close.gif">
        //                  </a>
        //              </div>
        //          </div>
        //      </div>
        //  </div>


        var objBody = $$('body')[0];

        objBody.appendChild(Builder.node('div',{id:'overlay'}));
    
        objBody.appendChild(Builder.node('div',{id:'lightbox'}, [
            Builder.node('div',{id:'outerImageContainer'}, 
                Builder.node('div',{id:'imageContainer'}, [
                    Builder.node('a',{id:'lightboxMylink', 'class':'jqzoom'},[
                        Builder.node('img',{id:'lightboxImage'})
                    ]), 
                    Builder.node('div',{id:'hoverNav'}, [
                        Builder.node('a',{id:'prevLink', href: '#' }),
                        Builder.node('a',{id:'nextLink', href: '#' })
                    ]),
                    Builder.node('div',{id:'loading'}, 
                        Builder.node('a',{id:'loadingLink', href: '#' }, 
                            Builder.node('img', {src: LightboxOptions.fileLoadingImage})
                        )
                    )
                ])
            ),
            Builder.node('div', {id:'imageDataContainer'},
                Builder.node('div',{id:'imageData'}, [
                    Builder.node('div',{id:'imageDetails'}, [
                        Builder.node('span',{id:'caption'}),
                        Builder.node('span',{id:'numberDisplay'})
                    ]),
                    Builder.node('div',{id:'bottomNav'},
                        Builder.node('a',{id:'bottomNavClose', href: '#' },
                            Builder.node('img', { src: LightboxOptions.fileBottomNavCloseImage })
                        )
                    )
                ])
            )
        ]));


        $('overlay').hide().observe('click', (function() { this.end(); }).bind(this));
        $('lightbox').hide().observe('click', (function(event) { if (event.element().id == 'lightbox') this.end(); }).bind(this));
        $('outerImageContainer').setStyle({ width: size, height: size });
        $('prevLink').observe('click', (function(event) { event.stop(); this.changeImage(this.activeImage - 1); }).bindAsEventListener(this));
        $('nextLink').observe('click', (function(event) { event.stop(); this.changeImage(this.activeImage + 1); }).bindAsEventListener(this));
        $('loadingLink').observe('click', (function(event) { event.stop(); this.end(); }).bind(this));
        $('bottomNavClose').observe('click', (function(event) { event.stop(); this.end(); }).bind(this));

        var th = this;
        (function(){
            var ids = 
                'overlay lightbox outerImageContainer imageContainer lightboxMylink lightboxImage hoverNav prevLink nextLink loading loadingLink ' + 
                'imageDataContainer imageData imageDetails caption numberDisplay bottomNav bottomNavClose';   
            $w(ids).each(function(id){ th[id] = $(id); });
        }).defer();
    },

    //
    // updateImageList()
    // Loops through anchor tags looking for 'lightbox' references and applies onclick
    // events to appropriate links. You can rerun after dynamically adding images w/ajax.
    //
    updateImageList: function() {   
        this.updateImageList = Prototype.emptyFunction;

        document.observe('click', (function(event){
            var target = event.findElement('a[rel^=lightbox]') || event.findElement('area[rel^=lightbox]');
            if (target) {
                event.stop();
                this.start(target);
            }
        }).bind(this));
    },
    
    //
    //  start()
    //  Display overlay and lightbox. If image is part of a set, add siblings to imageArray.
    //
    start: function(imageLink) {    

        $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' });

        // stretch overlay to fill page and fade in
        var arrayPageSize = this.getPageSize();
        $('overlay').setStyle({ width: arrayPageSize[0] + 'px', height: arrayPageSize[1] + 'px' });

        new Effect.Appear(this.overlay, { duration: this.overlayDuration, from: 0.0, to: LightboxOptions.overlayOpacity });

        this.imageArray = [];
        var imageNum = 0;       

        if ((imageLink.rel == 'lightbox')){
            // if image is NOT part of a set, add single image to imageArray
            this.imageArray.push([imageLink.href, imageLink.title]);         
        } else {
            // if image is part of a set..
            this.imageArray = 
                $$(imageLink.tagName + '[href][rel="' + imageLink.rel + '"]').
                collect(function(anchor){ return [anchor.href, anchor.title]; }).
                uniq();
            
            while (this.imageArray[imageNum][0] != imageLink.href) { imageNum++; }
        }

        // calculate top and left offset for the lightbox 
        var arrayPageScroll = document.viewport.getScrollOffsets();
        var lightboxTop = arrayPageScroll[1] + (document.viewport.getHeight() / 10);
        var lightboxLeft = arrayPageScroll[0];
        this.lightbox.setStyle({ top: lightboxTop + 'px', left: lightboxLeft + 'px' }).show();
        
        this.changeImage(imageNum);
    },

    //
    //  changeImage()
    //  Hide most elements and preload image in preparation for resizing image container.
    //
    changeImage: function(imageNum) {   
        
        this.activeImage = imageNum; // update global var

        // hide elements during transition
        if (LightboxOptions.animate) this.loading.show();
        this.lightboxImage.hide();
        this.hoverNav.hide();
        this.prevLink.hide();
        this.nextLink.hide();
        // HACK: Opera9 does not currently support scriptaculous opacity and appear fx
        this.imageDataContainer.setStyle({opacity: .0001});
        this.numberDisplay.hide();      
        
        var imgPreloader = new Image();
        
        // once image is preloaded, resize image container


        imgPreloader.onload = (function(){
            this.lightboxImage.src = this.imageArray[this.activeImage][0];
            this.resizeImageContainer(imgPreloader.width, imgPreloader.height);
        }).bind(this);
        imgPreloader.src = this.imageArray[this.activeImage][0];
    },

    //
    //  resizeImageContainer()
    //
    resizeImageContainer: function(imgWidth, imgHeight) {

        // get current width and height
        var widthCurrent  = this.outerImageContainer.getWidth();
        var heightCurrent = this.outerImageContainer.getHeight();

        // get new width and height
        var widthNew  = (imgWidth  + LightboxOptions.borderSize * 2);
        var heightNew = (imgHeight + LightboxOptions.borderSize * 2);

        // scalars based on change from old to new
        var xScale = (widthNew  / widthCurrent)  * 100;
        var yScale = (heightNew / heightCurrent) * 100;

        // calculate size difference between new and old image, and resize if necessary
        var wDiff = widthCurrent - widthNew;
        var hDiff = heightCurrent - heightNew;

        if (hDiff != 0) new Effect.Scale(this.outerImageContainer, yScale, {scaleX: false, duration: this.resizeDuration, queue: 'front'}); 
        if (wDiff != 0) new Effect.Scale(this.outerImageContainer, xScale, {scaleY: false, duration: this.resizeDuration, delay: this.resizeDuration}); 

        // if new and old image are same size and no scaling transition is necessary, 
        // do a quick pause to prevent image flicker.
        jQuery('.jqzoom').jqzoom({zoomType: 'standard',lens:true,preloadImages: false,alwaysOn:false});
        var timeout = 0;
        if ((hDiff == 0) && (wDiff == 0)){
            timeout = 100;
            if (Prototype.Browser.IE) timeout = 250;   
        }

        (function(){
            this.prevLink.setStyle({ height: imgHeight + 'px' });
            this.nextLink.setStyle({ height: imgHeight + 'px' });
            this.imageDataContainer.setStyle({ width: widthNew + 'px' });

            this.showImage();
        }).bind(this).delay(timeout / 1000);
    },
    
    //
    //  showImage()
    //  Display image and begin preloading neighbors.
    //
    showImage: function(){
        this.loading.hide();
        new Effect.Appear(this.lightboxImage, { 
            duration: this.resizeDuration, 
            queue: 'end', 
            afterFinish: (function(){ 
                this.updateDetails(); 
                this.lightboxMylink.href=str_replace('big_', jQuery("a[href='"+str_replace('http://www.buzzmart.com','',this.imageArray[this.activeImage][0])+"']").attr('zoom') == '1' ? 'zoom_' : 'big_' ,this.imageArray[this.activeImage][0]);
                jQuery('.jqzoom').trigger('changeimage');
            }).bind(this) 
        });
        this.preloadNeighborImages();
    },

    //
    //  updateDetails()
    //  Display caption, image number, and bottom nav.
    //
    updateDetails: function() {
    
        // if caption is not null
        if (this.imageArray[this.activeImage][1] != ""){
            this.caption.update(this.imageArray[this.activeImage][1]).show();
        }
        
        // if image is part of set display 'Image x of x' 
        if (this.imageArray.length > 1){
            this.numberDisplay.update( LightboxOptions.labelImage + ' ' + (this.activeImage + 1) + ' ' + LightboxOptions.labelOf + '  ' + this.imageArray.length).show();
        }

        new Effect.Parallel(
            [ 
                new Effect.SlideDown(this.imageDataContainer, { sync: true, duration: this.resizeDuration, from: 0.0, to: 1.0 }), 
                new Effect.Appear(this.imageDataContainer, { sync: true, duration: this.resizeDuration }) 
            ], 
            { 
                duration: this.resizeDuration, 
                afterFinish: (function() {
                    // update overlay size and update nav
                    var arrayPageSize = this.getPageSize();
                    this.overlay.setStyle({ height: arrayPageSize[1] + 'px' });
                    this.updateNav();
                }).bind(this)
            } 
        );
    },

    //
    //  updateNav()
    //  Display appropriate previous and next hover navigation.
    //
    updateNav: function() {

        this.hoverNav.show();               

        // if not first image in set, display prev image button
        if (this.activeImage > 0) this.prevLink.show();

        // if not last image in set, display next image button
        if (this.activeImage < (this.imageArray.length - 1)) this.nextLink.show();
        
        this.enableKeyboardNav();
    },

    //
    //  enableKeyboardNav()
    //
    enableKeyboardNav: function() {
        document.observe('keydown', this.keyboardAction); 
    },

    //
    //  disableKeyboardNav()
    //
    disableKeyboardNav: function() {
        document.stopObserving('keydown', this.keyboardAction); 
    },

    //
    //  keyboardAction()
    //
    keyboardAction: function(event) {
        var keycode = event.keyCode;

        var escapeKey;
        if (event.DOM_VK_ESCAPE) {  // mozilla
            escapeKey = event.DOM_VK_ESCAPE;
        } else { // ie
            escapeKey = 27;
        }

        var key = String.fromCharCode(keycode).toLowerCase();
        
        if (key.match(/x|o|c/) || (keycode == escapeKey)){ // close lightbox
            this.end();
        } else if ((key == 'p') || (keycode == 37)){ // display previous image
            if (this.activeImage != 0){
                this.disableKeyboardNav();
                this.changeImage(this.activeImage - 1);
            }
        } else if ((key == 'n') || (keycode == 39)){ // display next image
            if (this.activeImage != (this.imageArray.length - 1)){
                this.disableKeyboardNav();
                this.changeImage(this.activeImage + 1);
            }
        }
    },

    //
    //  preloadNeighborImages()
    //  Preload previous and next images.
    //
    preloadNeighborImages: function(){
        var preloadNextImage, preloadPrevImage;
        if (this.imageArray.length > this.activeImage + 1){
            preloadNextImage = new Image();
            preloadNextImage.src = this.imageArray[this.activeImage + 1][0];
        }
        if (this.activeImage > 0){
            preloadPrevImage = new Image();
            preloadPrevImage.src = this.imageArray[this.activeImage - 1][0];
        }
    
    },

    //
    //  end()
    //
    end: function() {
        this.disableKeyboardNav();
        this.lightbox.hide();
        new Effect.Fade(this.overlay, { duration: this.overlayDuration });
        $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
    },

    //
    //  getPageSize()
    //
    getPageSize: function() {
            
         var xScroll, yScroll;
        
        if (window.innerHeight && window.scrollMaxY) {    
            xScroll = window.innerWidth + window.scrollMaxX;
            yScroll = window.innerHeight + window.scrollMaxY;
        } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
            xScroll = document.body.scrollWidth;
            yScroll = document.body.scrollHeight;
        } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
            xScroll = document.body.offsetWidth;
            yScroll = document.body.offsetHeight;
        }
        
        var windowWidth, windowHeight;
        
        if (self.innerHeight) {    // all except Explorer
            if(document.documentElement.clientWidth){
                windowWidth = document.documentElement.clientWidth; 
            } else {
                windowWidth = self.innerWidth;
            }
            windowHeight = self.innerHeight;
        } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
            windowWidth = document.documentElement.clientWidth;
            windowHeight = document.documentElement.clientHeight;
        } else if (document.body) { // other Explorers
            windowWidth = document.body.clientWidth;
            windowHeight = document.body.clientHeight;
        }    
        
        // for small pages with total height less then height of the viewport
        if(yScroll < windowHeight){
            pageHeight = windowHeight;
        } else { 
            pageHeight = yScroll;
        }
    
        // for small pages with total width less then width of the viewport
        if(xScroll < windowWidth){    
            pageWidth = xScroll;        
        } else {
            pageWidth = windowWidth;
        }

        return [pageWidth,pageHeight];
    }
}

jQuery( document ).ready(function(){new Lightbox();});

function change_ebay_categ(obj)
{
    var input = jQuery(obj).parent().find('input');
    var val = input.val();
    var html = str_replace('<select>', '<select style="width:300px;" name="'+input.attr('name')+'">', bz_cats_ebay_import);
    jQuery(obj).parent().html(html + '<br><a href="" onclick="save_ebay_categ(this);return false;">Save</a>').find('select').attr({'value':val});
}

function save_ebay_categ(obj)
{
    var select = jQuery(obj).parent().find('select');
    jQuery(obj).parent().html('<input type="hidden" name="'+select.attr('name')+'" value="'+select.val()+'"><a href="" title="Click to change" onclick="change_ebay_categ(this);return false;">'+select.find('option:selected').parent().attr('label')+' -&gt; '+select.find('option:selected').html()+'</a>');
}
