var myImage = '';
var isOpera = (navigator.userAgent.indexOf('Opera') != -1);
var isIE = (!isOpera && navigator.userAgent.indexOf('MSIE') != -1);

// {{{ UpdateChecklist(event)
var hidemetimer;
var isFading = 0;

function UpdateChecklist(ev, el) {

  var type;
  if(el) {
    type = el.src.match('_checked.png$') ? 'del' : 'add';
  } else {
    el = Event.element(ev);
    type = el.src.match('_checked.png$') ? 'del' : 'add';
  }

  if(el.nodeName != "IMG")
    return true;

  if(hidemetimer)
    clearTimeout(hidemetimer);

  var m = el.id.match(/^check_(.+)_([0-9]+)$/);
  if(!m) return true;

  var sec = m[1];
  var dbid = m[2];


  var ret;

  if(type == 'add') {
    ret = Checklist.add(sec, dbid);
  } else if(type == 'del') {
    ret = Checklist.del(sec, dbid);
  }


  if(!ret)
    return alert('Error updating this entry on your Checklist');

  el.src = '/graphics/checklist_' + (type == 'add' ? '' : 'un') + 'checked.png';

  var tip = $('checklistupdate');
  var isnew = tip ? true : false;

  if(tip) {
    tip.removeClassName('checklistadd');
    tip.removeClassName('checklistdel');
    tip.removeClassName('checklistokay');
    tip.removeClassName('checklistfail');
  } else {
    tip = new Element('div', {id:'checklistupdate'});
    $$('body')[0].appendChild(tip);
  }
  tip.addClassName('checklist' + type);
  tip.addClassName('checklist' + (ret ? 'okay' : 'fail'));
  tip.update('Checklist contains: ' + Checklist.toString());

  var osL = $$('.fullsize_ad').length ? 15 : -1 * (10 + tip.getWidth());
  Element.clonePosition(tip, el, {setWidth: false, setHeight: false,
                                  offsetLeft: osL, offsetTop: -3 });
  tip.show();

  hidemetimer = setTimeout(function() {
    if(typeof(Scriptaculous) === 'undefined') {
      tip.hide();
    } else {
      if(!isFading) {
        tip.fade({beforeStart: function(eff) { isFading = 1; },
                  afterFinish: function(eff) {
                    eff.element.setOpacity(1);
                    isFading = 0;
                  } });
      }
    }
  }, 700);

  if(isnew) {
    Event.observe(tip, 'mouseout', function(ev) {
      tip.hide();

      if(hidemetimer)
        clearTimeout(hidemetimer);
    });
  };

  el.parentNode.blur();
  return true;
} // }}}

// {{{  rowMouseOver(ev)
function rowMouseOver(ev){
  var el = Event.element(ev);

  if(el.nodeName !== 'TR') {
    el = el.up('tr');
    if(!el) return;
  }

  el.addClassName('headlinerowover');

  var isHLR = el.hasClassName('highlightedrow');
  if(isHLR)
    el.addClassName('highlightedrowover');

  el.childElements().each(function(td) {
    if(td.hasClassName('selectedcolumn1')
       || td.hasClassName('selectedcolumn2')) {
      td.addClassName('headlinerowover');

      if(isHLR)
        td.addClassName('highlightedrowover');

      throw $break;
    }
  });
} // }}}

// {{{ rowMouseOut(ev)
function rowMouseOut(ev) {
  var el = Event.element(ev);

  if(el.nodeName !== 'TR') {
    el = el.up('tr');
    if(!el) return;
  }

  el.removeClassName('highlightedrowover');
  el.removeClassName('headlinerowover');

  el.childElements().each(function(td) {
    td.removeClassName('highlightedrowover');
    td.removeClassName('headlinerowover');
  });
} // }}}

// {{{ rowClick(ev)
function rowClick(ev) {
  var el = Event.element(ev);

  if(el.nodeName !== 'TR') {
    if(el.colspan && el.colspan > 1) {
      el = el.up('tr').previousSiblings()[0];
    } else {
      el = el.up('tr');
    }
    if(!el) return;
  }

/*
  var alink = el.select('a[rel!="nofollow"]').grep({
    match: function(rec) { return rec.href && !rec.rel.match('nofollow'); }
  });
*/
  var alink = el.select('a[rel!="nofollow"]');

  if(alink.length) {
    if(ev.shiftKey) {
      window.open(alink[0].href);
    } else {
      window.location = alink[0].href;
    }

    ev.stop();
    return false;
  }
} // }}}

// {{{ onload()
Event.observe(window, 'load', function() {
  $$('.tnpop').each(function(el) {
    el.observe('mouseover', function(ev) {
      ev.stop();
      var parts = el.src.match(/#([0-9]+):([0-9]+):(.+)$/);
      new Tip(el, '<img src="'  + parts[3].replace(/,/g, '/') + '" '
                 +    'width="' + parts[1] + '" '
                 +   'height="' + parts[2] + '"/>');
    });
  });


  $$('.headlinerow').each(function(el){

    el.observe('mouseover', rowMouseOver)
      .observe('mouseout', rowMouseOut)
      .observe('click', rowClick);
  });

  $$('.cl_status').each(function(el) {
    Event.observe(el, 'click', ChecklistClick);
    Event.observe(el.parentNode, 'click', ChecklistClick);
  });

  $$('.nomapavailable').each(function(el) {
    el.observe('click', function(ev) { ev.stop(); });
  });

  $$('.tnlink').each(function(el) {
    Event.observe(el, 'click', function(ev) {
      var el = Event.element(ev);
      if(el) {
        if(el.nodeName == 'IMG') el = el.parentNode;
        ev.stop();
        window.open(el.href, 'userhelp', 'WIDTH=640,HEIGHT=480,resizable=yes,'
                                       + 'scrollbars=yes,left=150,top=100,'
                                       + 'screenX=150,screenY=100');
        return false;
      }
    });
  });

  $$('a.mapnewwindow').invoke('observe', 'click', function(ev) {
    ev.stop();
    window.open(Event.element(ev).href, 'mapwindow');
  });

  if($('contactadmin')) {
    $$('.alertadmin').invoke('observe', 'click', initAlertAdminForm);
    $('closealertadmin').observe('click', closeAlertAdminForm);
  }

  if($('sendfriend')) {
    $$('.sendfriend').invoke('observe', 'click', initSendToFriend);
    $('closesendfriend').observe('click', closeSendToFriend);
  }
}); // }}}

// {{{ closeAlertAdminForm (ev)
function closeAlertAdminForm (ev) {
  ev.stop();
  $('contactadmin').hide();
} // }}}

// {{{ closeSendToFriend (ev)
function closeSendToFriend (ev) {
  ev.stop();
  $('sendfriend').hide();
} // }}}

// {{{ initSendToFriend(ev)
function initSendToFriend(ev) {
  ev.stop();
  var adno = Event.element(ev).id.replace(/^sendfriend_/, '');
  $('sendfriendadno').update(adno);
  $('sendfrienddb_id').value = adno;
  $('sendfriend').show();
  var l = location.protocol + '//' + location.hostname;
  var v = $('sendfriend_body').value
          .replace(/(at the .* in .*)#[0-9]*/, '$1#' +adno)
          .replace(new RegExp(l + '[^ ]*'), getAdURL(adno));
  $('sendfriend_body').value = v;
  centerEl($('sendfriend'), 1);
} // }}}

// {{{ initAlertAdminForm (ev)
function initAlertAdminForm (ev) {
  ev.stop();
  var adno = Event.element(ev).id.replace(/^alertadmin_/, '');
  $('alertadminadno').update(adno);
  $('alertadmindb_id').value = adno;
  var el = $('sender_body');

  if(el && typeof(defAlertAdminMsg) !== 'undefined') {
     el.value = defAlertAdminMsg.replace('<adno>', adno);
  }

  $('contactadmin').show();
  centerEl($('contactadmin'), 1);
} // }}}

function CreateWindow(sec, dbid, price, type){
  if(type == 'loan')
    type = 'car_payments';
  window.open(surlnodb + 'db=' + sec +';print_' + type + '_popup=on;price=' + price,'TheWindow','WIDTH=400,HEIGHT=600,scrollbars=yes,resize=yes,left=150,top=100,screenX=150,screenY=100');
}

function printPage(){
  if(window.print)
    window.print();
  else
   printMsg()
}

function printMsg(){
  if(navigator.appVersion.indexOf("Mac") != -1)
    alert("To print this page press Command-P.")
  else
    alert("To print this page press Control-P.")
}


// {{{ ChecklistClick()
function ChecklistClick(ev) {
 ev.stop();
 var el = Event.element(ev);

 if(el.nodeName == 'IMG') {
   return UpdateChecklist(ev);
 }

 // Catches "near misses" around checklist checkbox
 var img = el.select('img')[0];
 if(img) {
   return UpdateChecklist(ev, img);
 }
} // }}}


Event.observe(window, 'load', function() {
  if(typeof(adName) == 'undefined')
    adName = 'Ad';

  if(typeof(isAdmin) == 'undefined')
    isAdmin = 0;

  if($('mark_as_sold')) {
    Event.observe($('mark_as_sold'), 'click', confirmMarkAsSold);
  }

  if($('is_sold')) {
    Event.observe($('is_sold'), 'click', blockEdit);
  }

  $$('a.hlbroken').invoke('observe', 'click', highlightBrokenAd);
});

// {{{ blockEdit(ev)
function blockEdit(ev) {
  if(isAdmin) {
    if(!confirm('This ' + adName + ' has been marked as Sold and should\n' +
                'not be edited so as to allow visitors to see the item\n' +
                'as it was sold.\n\n' +
                'However as you are an admin user you can modify the\n' +
                adName + ' by clicking on the "OK" button below.')) {
      ev_stop();
      return;
    }
  } else {
    ev.stop();
    alert('This ' + adName + ' has been marked as Sold. To allow visitors to\n'
        + 'see the item as it was sold this ' + adName +' cannot be edited.\n'
        + 'To edit this ' + adName +' you must remove the "Sold" mark.');
  }
} // }}}

// {{{ confirmMarkAsSold(ev)
function confirmMarkAsSold(ev) {
  var isSold = $('is_sold');

  if(isSold) {
    confirmed = confirm(
      'This will remove the "sold" sign from your ' + adName + ' and\n' +
      'return it back to its regular type so it can be edited.\n\n' +
      'Note:\n'+
      'The entry should not be marked as unsold if this item really\n' +
      'has been sold. This option is provided in case the sale is not\n' +
      'completed and you wish to re-list the ' + adName + '.\n');
  } else {
    confirmed = confirm(
      'This will mark your ' + adName + ' as sold. You will not be\n' +
      'able to make further changes to your ' + adName + ' once it\n' +
      'has been marked as sold. (But you can unmark it).\n\n' +
      'Click OK to Mark your ' +adName+' as having been sold.');
  }

  if(!confirmed) {
    ev.stop();
    return;
  }

  if(isSold && isAdmin) {
  }
} // }}}

// {{{ highlightBrokenAd(ev)
function highlightBrokenAd(ev) {
  ev.stop();
  var findID = ev.element ? Event.element(ev) : ev;
      findID = $(findID.id.replace(/^hb/, 'va'));

  if(findID) {
    new Effect.Highlight(findID.up('tr'));
  }
} // }}}

