function basename(path) {
  return path.replace(/\\/g,'/').replace( /.*\//, '' );
};


/*
 * to do: find first tab with form errors (after submission), and activate
 */

var STBeach = {
  _active:'main',
  _evtSrc:null,
  onTab: function() {
    STBeach._evtSrc = this;
    STBeach._active = $(this).attr('name');
    $('div.sttabs div.sttab').each(function(i,e){
      if( $(e).attr('name')==STBeach._active ) {
        $(e).show();
        var fn = $(e).attr('onactivate');
        if( fn ) eval(fn);
        
        if( STBeach._active=='safety') {
          $('.lat-long').hide();
          $('.alt-name').hide();
        }
      }
      else {
        $(e).hide();
        $('.lat-long').show();
        $('.alt-name').show();
      }
    });
    $('div.sttabs li a').each(function(i,e){
      if( $(e).attr('name')==STBeach._active ) {
        $(e).parent().addClass('active');
      }
      else {
        $(e).parent().removeClass('active');
      }
    });
    $(this).blur();
    return false;
  }
};

var STSearch = {
  _speed:400,
  showShortForm: function (ev) {
    var o = ev.target || ev.srcElement;
    o.blur();
    if( STSearch._busy ) return false; STSearch._busy = true;
    $('#search-short').slideDown(STSearch._speed, STSearch.endOperation);
    if( STSearch._timerID ) {
      clearTimeout( STSearch._timerID );
      STSearch._timerID=null;
    }
    return false;
  },
  closeShortForm: function() {
    if( STSearch._busy ) return; STSearch._busy = true;
    $('#search-short').slideUp(STSearch._speed, STSearch.endOperation);
    if( STSearch._timerID ) {
      clearTimeout( STSearch._timerID );
      STSearch._timerID=null;
    }
  },
  onMouseOver: function() {
    if( STSearch._timerID ) {
      clearTimeout( STSearch._timerID );
      STSearch._timerID=null;
    }
  },
  onMouseOut: function() {
    if( !STSearch._timerID ) {
      STSearch._timerID=setTimeout( 'STSearch.onTimedOut()', 2500 );
    }
  },
  onTimedOut: function() {
    if( STSearch._busy ) return; STSearch._busy = true;
    $('#search-short').slideUp(STSearch._speed, STSearch.endOperation);
    STSearch._timerID=null;
  },
  endOperation: function() {
    STSearch._busy = false;
  },
  _timerID:null,
  _busy:false
};


var points = new Array();

function dooutp(e) {
  var pos = $(this).position();
  var pp = $('#page').position();
  var pl = pp.left;
  var pt = pp.top;
  var ssl = parseInt($('#search-short').css('marginLeft'),10);
  var sst = parseInt($('#search-short').css('marginTop'),10);
  var px = e.pageX - pl - ssl - 5;
  var py = e.pageY - pt - sst - 30;

  var h = $('#outp').html();
  if( h!='' ) h+=', ';
  h += px+','+py;
  $('#outp').html(h);
}


var Front = {
  mouseover: function(ev) {
    Front._idx = $(this).attr('idx');
    $('div.front-item').each(function(i,e){
      if( $(e).attr('idx')==Front._idx ) $(e).show(); else $(e).hide();
    });
    $('div.front-tabs a').each(function(i,e){
      if( $(e).attr('idx')==Front._idx ) $(e).addClass('active'+i); else $(e).removeClass('active'+i);
    });
  }
}

var FrontMap = {
  click: function(o) {
    var f = $('#stbeach-search-short-form');
    f.find('select[name=region]').val($(o).attr('alt'));
    f.submit();
    return false;
  }
}


var STThreeState = {
  _map:['no','yes','unknown'],
  init: function(i,e) {
    var inp = $(e).parent().parent().next('input');
    var v = $(inp).attr('value');
    if( v>2 || v<0 ) return;
    $(e).attr('class',STThreeState._map[v]);
    $(e).attr('title',STThreeState._map[v]);
    $(inp).attr('value',v);
  },
  over: function() {
  },
  out: function() {
  },
  click: function() {
    var inp = $(this).parent().parent().next('input');
    var v = $(inp).attr('value');
    v = (v+1)%3;
    if( v>2 || v<0 ) return;
    $(this).attr('class',STThreeState._map[v]);
    $(this).attr('title',STThreeState._map[v]);
    $(inp).attr('value',v);
    $(this).blur();
    return false;
  }
};


var BM = {
  IWantTo: function() {
    if( $('#iwantto').length ) {
      BM.onShow();
      $('#iwantto').fadeIn();
      $('#iwantto input:first').focus();
    }
  },
  Register: function() {
    if( $('#register').length ) {
      BM.onShow();
      $('#register').fadeIn();
      $('#register input:first').focus();
    }
  },
  Login: function(error) {
    if( $('#login').length ) {
      BM.onShow();
      if( error ) $('#login p.error').show();
      else $('#login p.error').hide();
      $('#login').fadeIn();
      $('#login input:first').focus();
    }
  },
  Postcard: function(error) {
    if($('#postcard').length ) {
      BM.onShow();
      if( error ) $('#postcard p.error').show();
      else $('#postcard p.error').hide();
      $('#postcard').fadeIn();
      $('#postcard input:first').focus();
    }
  },

  onShow: function() {
    $('div.blackbox').hide();
    $('#blockout').show();
    $(document).scrollTop(0);
	},
	close: function()
	{
    $('.blackbox').fadeOut();
		if(STBeach._isie6) $('#block-stbeach-1').show();
    $('#blockout').hide();
	}
}

var BlockOut = {
  stretch:function() {
    $('#blockout').css({height:$(window).height()+'px'});
  }
}

var Scroll = {
  _idx:0,
  _items:null,
  _container:null,

  _containerheight:250,
  _barrange:250,
  _barheight:50,
  _baroff:16,
  _bardown:false,
  _startpos:{x:0,y:0,bartop:0},

  init: function() {
    Scroll._items = $('#front-news div.item');
    Scroll._container = $('#front-news div.container');
    if( Scroll._items.size()==0 ) return false;

    $('#scroll_up').click(Scroll.up);
    $('#scroll_down').click(Scroll.down);

    Scroll._baroff = parseInt($('#scrollbar').css('marginTop'),10);

    Scroll._barrange = parseInt($('#scroll_down').css('marginTop'),10) -
                       parseInt($('#scroll_up').css('marginTop'),10) -
//                       Scroll._baroff -
                       20;

    var last = Scroll._items.eq(Scroll._items.size()-1);
    var pos = getRelativePosition(last);

    Scroll._containerheight = pos.top;// + last.height();
    Scroll._barheight = Scroll._barrange/Scroll._items.size();
    Scroll._barrange -= Scroll._barheight;

    $('#scrollbar').height(Scroll._barheight);
    $('#scrollbar').mousedown(Scroll.bardown);

    $('#scrollbar').mouseover(Scroll.barover);
    $('#scrollbar').mouseout(Scroll.barout);

    $(document).mouseup(Scroll.barup);
    $(document).mousemove(Scroll.mousemove);


    Scroll.showCurrent();
  },
  down: function() {
    Scroll._idx = parseInt(Scroll._idx,10);
    if( Scroll._idx<Scroll._items.size()-1 ) Scroll._idx++;
    Scroll.showCurrent();
    return false;
  },
  up: function() {
    Scroll._idx = parseInt(Scroll._idx,10);
    if( Scroll._idx>0 ) Scroll._idx--;
    Scroll.showCurrent();
    return false;
  },
  showCurrent: function() {
    var idx = parseInt(Scroll._idx,10);
    var pos = getRelativePosition(Scroll._items.eq(idx));
    Scroll._container.stop().animate({scrollTop: pos.top}, 800);
    var y = Scroll._barheight * Scroll._idx + Scroll._baroff;
    $('#scrollbar').stop().animate({marginTop: y}, 800);
  },
  bardown: function(e) {
    if( Scroll._bardown ) return false;
    Scroll._bardown = true;
    Scroll._startpos.x = e.pageX;
    Scroll._startpos.y = e.pageY;
    Scroll._container.stop();
    Scroll._startpos.bartop = parseInt($('#scrollbar').stop().css('marginTop'),10);
    return false;
  },
  barup: function() {
    if( !Scroll._bardown ) return false;
    Scroll._bardown = false;
    return false;
  },
  barover: function(e) {
    $(this).addClass('over');
  },
  barout: function(e) {
    $(this).removeClass('over');
  },
  mousemove: function(e) {
    if( !Scroll._bardown ) return false;
    var dy = e.pageY-Scroll._startpos.y;
    var y = Scroll._startpos.bartop+dy;
    if( y<Scroll._baroff ) y=Scroll._baroff;
    else if( y>Scroll._barrange+Scroll._baroff ) y = Scroll._barrange+Scroll._baroff;
    $('#scrollbar').css('marginTop', y);
    y -= Scroll._baroff;
    Scroll._idx = (y/Scroll._barrange)*(Scroll._items.size()-1);

    y = (y/Scroll._barrange) * Scroll._containerheight;

    Scroll._container.scrollTop(y);
    return false
  }
}

function getRelativePosition(e) {
  var elementPosition = $(e).position();
  var parentPosition = $(e).parent().position();
  var scrtop = $(e).parent().scrollTop();

  return {top: elementPosition.top - parentPosition.top + scrtop,
          left: elementPosition.left - parentPosition.left};
}

/*
$(function() {
  $('.front-map').maphilight();
});
*/

var STTip = {
  mouseover: function(e) {
    var lbl = $('#sttooltip');
    var inner = lbl.find('div.inner');

    if(this.tagName=='AREA') {
      var ox = e.pageX+8;
      var oy = e.pageY-8;
      lbl.css({top:oy,left:ox});
      inner.html($(this).attr('alt'));
    }
    else {
      var offx = 17; var offy=-8;
      var p = $(this).position();
      var pg = $('#page').position();
      var ox = p.left+pg.left+offx;
      var oy = p.top+pg.top+offy;
      inner.html($(this).html());
      var w = lbl.width();
      var h = lbl.height();
      var pw = $('#page').width();
      if( p.left+w+offx>pw ) {
        ox = pg.left+p.left-w;
        oy = p.top+pg.top-h/3;
      }
      lbl.css({top:oy,left:ox});
    }
    lbl.stop().show().fadeTo('fast',1.0,function(){});

  },
  mouseout: function(e) {
    $('#sttooltip').stop().fadeTo('fast',0.0,function(){$('#sttooltip').hide();});
  },
  mouseovertip: function(e) {
    $('#sttooltip').stop().show().fadeTo('fast',1.0,function(){});
  },
  mouseouttip: function(e) {
    $('#sttooltip').stop().fadeTo('fast',0.0,function(){$('#sttooltip').hide();});
  }
};

$(document).ready(function() {
  $('div.sttabs li a').click(STBeach.onTab);

  $('#primary li.menu-600').click(STSearch.showShortForm);

  $('#search-short').mouseover(STSearch.onMouseOver);
//  if( !$('#page').parent().hasClass('front') )
//    $('#search-short').mouseout(STSearch.onMouseOut);

  $('div.strating-three_state a').mouseover(STThreeState.over);
  $('div.strating-three_state a').click(STThreeState.click);
  $('div.strating-three_state').mouseout(STThreeState.out);

  $('div.strating-three_state a').each(STThreeState.init);

  STBeach._sizers = $('div.blackbox');
  $(window).resize( BlockOut.stretch );
  $(window).scroll( BlockOut.stretch );
  BlockOut.stretch();

  if($('#blockout').attr('error')=='login') {
    BM.Login(true);
  }
  else if($('#blockout').attr('ask')=='reg') {
    BM.Register();
  }
  else if($('#blockout').attr('error')=='postcard') {
    BM.Postcard(true);
  }
  else if($('#blockout').attr('error')=='register') {
    BM.Register(true);
  }

  var news = document.getElementById('front-news');
  if( news ) {
    Scroll.init();
  }

  $('div.front-tabs a').mouseover(Front.mouseover);

  STBeach._isie6 = ($.browser.msie && $.browser.version.substr(0,1)<7);

  var outp = $('#outp');
  if( outp ) {
    $('.front-map').click(dooutp);
  }
  if( $('.front-map').attr('usemap')=='#gb' ) {
    $('.front-map').maphilight();
  }

  $('#sttooltip').mouseover(STTip.mouseovertip).mouseout(STTip.mouseouttip);
  $('form span.info').mouseover(STTip.mouseover).mouseout(STTip.mouseout);
  $('#search-short area').mouseover(STTip.mouseover).mouseout(STTip.mouseout);
  $('#content-area div.beach span.info').mouseover(STTip.mouseover).mouseout(STTip.mouseout);
  $('#block-stbeach-report_pipes span.info').mouseover(STTip.mouseover).mouseout(STTip.mouseout);

  if( STBeach._isie6 ) {
    $('#sttooltip').bgiframe({opacity:false});
    $('div.blackbox').bgiframe();
  }

//  $('#stbeach-search-long-form select').bgiframe();

//  $("#search-short img").tooltip();
});

function reset_html(src) {
  var fic = $(src).parent().parent().find('div.fic');
  fic.html(fic.html());
}

var Form = {
  Reset: function(src) {
    while( src.tagName!='FORM' ) src=src.parentNode;
    $(src).find('select').each(function(i,e){
      e.selectedIndex=0;
    });
    $(src).find('input[type=text]').val('');
    return false;
  }
};

var ReportPipes = {
  onComplete:function(fid,path,src) {
    $(src).parent().children('.stfile-loaded').children('span').html(basename(path));
    $(src).parent().children('.stfile-loaded').fadeIn();
    reset_html(src);
  },
  deleteImage: function(src) {
    $(src).parent().parent().children('.stfile-loaded').fadeOut();
    $(src).parent().parent().children('.stfile').fadeIn();
    reset_html(src);
  }
};
