$(document).ready(function () {
/*
 * global ajax settings
 */
	
	$('#langmenu').mouseover(function (e) {
		if (!$(this).data('hover'))
		{
			$(this).data('hover',$(this).clone().appendTo('body').addClass('langmenu').css({ position: 'absolute', top: $(this).offset().top, left: $(this).offset().left }));
			$(this).data('hover').find('li:not(.active) a').css({opacity:0});
			$(this).data('hover').find('li:not(.active)').slideDown(120,function() { $(this).children().animate({ opacity: 1},200); });
		}
		var o = $(this).data('hover').clearTimeout();
		$(this).one('mouseleave',function () {
			o.setTimeout(function () {
				var h = $('#langmenu').data('hover');
				h.queue(function () {
					h.find('li:not(.active) a').animate({opacity:0},200,function() {
						h.find('li:not(.active)').slideUp(200,function () {
							h.dequeue();
						});
					});
				});
				h.queue(function () {
					h.remove();
					h.dequeue();
				});
				$('#langmenu').data('hover',false);
			}, 400);
		});
		o.mouseenter(function() {
			o.clearTimeout();
		});
		o.mouseleave(function () {
			o.setTimeout(function () {
				var h = $('#langmenu').data('hover');
				h.queue(function () {
					h.find('li:not(.active) a').animate({opacity:0},200,function() {
						h.find('li:not(.active)').slideUp(200,function () {
							h.dequeue();
						});
					});
				});
				h.queue(function () {
					h.remove();
					h.dequeue();
				});
				$('#langmenu').data('hover',false);
			}, 400);
		});
	});
	

	$('#menu a.active').bubbleClass('highlight','#menu');
});


$.fn.bubbleClass = function (cl,until) {
	$(this).parentsUntil(until).addClass(cl);
}

// ajax stuff
var popups = [];

	
$('.actions').live('mouseenter',function () {
  $(this).clearTimeout();

  if ($(this).relCheck('dropdown'))
  {
    var o = ($(this).restore('hover')) ? $(this).restore('hover') : $(this).next().clone().children(':not(:first)').css({opacity:0}).parent().appendTo('body').slideDown(100,function () { $(this).children().animate({opacity:1},100);});
    var t = $(this).offset().top;
    var l = $(this).offset().left;
    o.width($(this).outerWidth());
  }
  else
  {
    var o = ($(this).restore('hover')) ? $(this).restore('hover') : $(this).next().clone().appendTo('body').fadeIn(100);
    var t = $(this).offset().top - o.outerHeight() - 3;
    var l = $(this).offset().left + $(this).outerWidth()/2 - o.outerWidth()/2;
  }

  o.css({top: t, left: l});
  o.store('origin',$(this));
  $(this).store('hover',o);
  o.mouseenter(function () {
    $(this).restore('origin').clearTimeout();
  }).mouseleave(function () {
    $(this).restore('origin').setTimeout(function () { o.restore('origin').store('hover',null); o.fadeOut(100,function () { $(this).remove(); }); },200);
  });
  $(this).one('mouseleave',function () {
    $(this).setTimeout(function () { o.restore('origin').store('hover',null); o.fadeOut(100,function () { $(this).remove(); }) },200);
  });
  
}).live('click',function (e) { e.preventDefault(); });

/*
 * livelink class replaces object specified with the target 
 * attribute of given element with anything it 
 * loads with an ajax request
 */
$('.livelink').live('click',function (e) {
  e.preventDefault();
  var _this = $(this);
  var url = _this.attr('href');
  var target = _this.attr('target');
  if (typeof(target) == 'undefined' || $(target).size() == 0 || typeof(url) == 'undefined' || $(this).relCheck('clicked'))
    return;
  _this.relAdd('clicked');
  
  
  $.ajax({
    url: url,
    async: false,
    dataType: 'html',
    data: {_ajax:true},
    cache: false,
    type: 'post',
    success: function (data) {
      _this.relRemove('clicked');
      if (_this.relCheck('replace'))
        $(target).replaceWith(data);
      else
        $(target).html(data);
    },
    error : function (a,b,c) {
      _this.relRemove('clicked');
      modalAlert('Communication error ('+b+')');
    }
  });
});

$('.popclose').live('click',function (e) {
  e.preventDefault();
  var keys = [];
  for (i in popups)
    keys[keys.length] = i;
  var obj = $(this).parentsUntil(keys.join(',')).parent(); 
  var id = obj.attr('id');
  for (i in popups)
  {
    if (i.indexOf(id) >= 0)
      popups[i].close();
  }
});

/*
 * poplink class loads data using ajax and wraps it in a popup container
 * with id specified in target attribute
 */
$('.poplink').live('click',function (e) {
  e.preventDefault();
  
  var wi = $(this).attr('target');
  var href = $(this).attr('href');
  var fixed = ($(this).relCheck('absolute')) ? false : true;
  
  if (!href || !wi || $(this).relCheck('clicked'))
    return;
  var t = $(this);
  t.relAdd('clicked');
  // object
  var o;
  if ($('#'+wi).size() > 0)
    o = $('#'+wi);
  else
    o = $('<div id="'+wi+'" />').appendTo('body');
    
  $.ajax({
    url: href,
    async: true,
    type: 'post',
    data: [{name:'_ajax',value:true}],
    success: function (html) {
      o.html(html).show().hide().overlay({
        top: '10%',
        mask: {
          color: '#000000',
          loadSpeed: 200,
          opacity: 0.3
        },
        closeOnClick : true,
        load: true,
        fixed: fixed,
        onLoad: function () {
          _this = this;
          popups['#'+wi] = this;
          o.find('input[type=text]').focus();
        },
        onClose : function () {
        	o.fadeOut(function () { $(this).remove(); });
        }
      }).load();
      t.relRemove('clicked');
    },
    error: function () {
      modalAlert('Error loading '+href,2000);
      t.relRemove('clicked');
    }
  });
});

/*
 * form submit triggering
 * 
 */

/*
 * 
 * comment form
 * 
 */

$('#comment-submit').live('submit',function () {
  setTimeout(function () { $('.comment-textarea').val(''); },50);
  if ($('#comments').parent().offset().top < $(window).scrollTop())
    $('html, body').animate({
      scrollTop: $('#comments').parent().offset().top
    }, 1500);
});

/*
 * liveform class submits a form and expects an ajax request, 
 * given the return data it decides what to do later on :-)
 */
$('form.liveform').live('submit',function (e) {
  e.preventDefault();
  var _this = $(this);
  if (_this.relCheck('submitted'))
    return;
  // ^^ to prevent multiple submissions vv
  _this.relAdd('submitted');
  var fdata = _this.serializeArray();
  fdata[fdata.length] = {name:'_ajax',value:true};
  var once = _this.relCheck('once');
  var url = _this.attr('action');
  var method = (_this.attr('method')) ? _this.attr('method') : 'post';
  $.ajax({
    url: url,
    async: false,
    dataType: 'json',
    data: fdata,
    cache: false,
    type: method,
    success: function (data) {
      _this.relRemove('submitted');
      if (exists(data,'errors'))
      {
        var html = '';
        $.each(data.errors,function (i,e) {
          html += '<h3>'+e+'</h3>';
        });
        modalAlert(html,2000);
        
      }
      else if (exists(data,'ajaxload') && exists(data,'ajaxtarget'))
        $(data.ajaxtarget).load(data.ajaxload,{_ajax:true});
      else if (exists(data,'reload'))
        window.location.reload();
      else if (exists(data,'goto'))
        location.href = data['goto'];
      else if (exists(data,'exec'))
        eval(data.exec);
    },
    error : function (a,b,c) {
      _this.relRemove('submitted');
      modalAlert('Communication error ('+b+')');
    }
  });
});


$('.listingViewChange').live('click',function (e) {
	e.preventDefault();
	var v = ($(this).attr('target') != 'tiles') ? '.listingRows' : '.listingTiles';
	$(this).parent().children().removeClass('on');
	$(this).addClass('on');
	$('.listingRows,.listingTiles').hide();
	$(v).show();
	var post = {
		view : ($(this).attr('target') != 'tiles') ? 'rows' : 'tiles',
		_ajax: true
	}
	var url = $(this).attr('href');
	ajaxLoaderSuppress = true;
	$.post(url,post);
});

/*
 * modalAlert, a modal alert
 */
 
function modalAlert(html,closetime) {
  if (typeof(html) == 'undefined')
    return;
  $('#modalAlert').remove();
  popups['#modalAlert'] = $('<div id="modalAlert" class="shadow-d"></div>').append(html).appendTo('body').show().hide().overlay({
      top: 200,
      mask: {
        color: '#000',
        loadSpeed: 200,
        opacity: 0.5
      },
      closeOnClick : true,
      load: true,
      onLoad: function () {
        var _this = this;
        if (typeof(closetime) == 'number')
          setTimeout(function () { _this.close(); },closetime);
      }
    }).load();
    
}


/*
 * helper functions
 */
 
function exists(o,str) {
  var path = str.split('.');
  while (path.length > 0)
  {
    var i = path.shift();
    var found = false;
    for (p in o)
      if (p == i)
        found = true;
    if (found && path.length == 0)
      return true;
    else if (found)
      o = o[i];
    else
      return false;
  }
  return false;
}

var ajaxLoaderSuppress = false;

function showLoading() {
  var a = parseInt($('#ajaxLoader').attr('active'))+1;
  if (ajaxLoaderSuppress)
    $('#ajaxLoader').hide().attr('active',a);
  else
    $('#ajaxLoader').show().attr('active',a);
  setTimeout(function () { ajaxLoaderSuppress = false; },50);
}

function hideLoading() {
  var a = parseInt($('#ajaxLoader').attr('active'))-1;
  $('#ajaxLoader').attr('active',a);
  if (a <= 0){
    $('#ajaxLoader').hide();
  }
}



$.fn.relCheck = function (an) {
  var rel = $(this).attr('rel');
  rel = (typeof(rel) == 'undefined') ? '' : rel;
  return rel.indexOf(an) != -1;
}

$.fn.relAdd = function (an) {
  if (!$(this).attr('rel')) $(this).attr('rel','');
  if (!$(this).attr('rel').indexOf(an) != -1) {
    var r = $(this).attr('rel').split(' ');
    r[r.length] = an;
    $(this).attr('rel',r.filter(function (a) { return a != an; }).join(' '));
  }
}

$.fn.relRemove = function (an) {
  if (!$(this).attr('rel')) $(this).attr('rel','');
  $(this).attr('rel',$(this).attr('rel').replace(an,'').split(' ').filter(function (a) { return a != an; }).join(' '));
}

if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var res = new Array();
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
      {
        var val = this[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, this))
          res.push(val);
      }
    }

    return res;
  };
}

function updateComments(firstpage) {
  firstpage = (firstpage === true) ? true : false;
  var ts = $('#comments').attr('timestamp');
  var url = $('#comments').attr('source');
  var page = parseInt($('#comments').attr('page'));
  if (firstpage && page > 1)
    $('#comments').parent().find('.pg-container a[title=1]').click();
  else
  {
    ajaxLoaderSuppress = true;
    $.ajax({
      url: url,
      async: true,
      dataType: 'html',
      data: { timestamp : ts, exec: 'updateComments', pn: page},
      cache: false,
      type: 'post',
      timeout: 10000,
      success: function (data) {
        var d = $(data);
        d.prependTo('#comments');
        var o = d.find('.comment-box');
        if (o.size() > 0)
        {
          if (page <= 1)
            o.hide().css({ opacity: 0 }).slideDown(200,function () { o.animate({opacity:1},200); });
          else
            o.remove();
        }
        else
          d.remove();
      }
    });
  }
}

function refreshObjects()
{
  if ($('[refresh][target]').size() == 0)
    return;
  $('[refresh][target]').each(function (i,e) {
    ajaxLoaderSuppress = true;
    $($(this).attr('target')).load($(this).attr('refresh'),{_ajax:true});
  });
  
}

function hashString(arr) {
	var parts = [];
	for (i in arr)
		if (arr[i])
			parts[parts.length] = escape(i)+'='+escape(arr[i]);
	return '/'+parts.join('/');
}

function parseHash() {
	var hash = location.hash;
	if (hash.indexOf('#') >= 0)
		hash = hash.split('#')[1];
	hash = $.trim(hash).substr(1);
	if (hash.length > 0)
	{	
		hash = hash.split('/');
		var out = {};
		for (i in hash)
		{
			var sp = hash[i].split('=');
			out[unescape(sp[0])] = unescape(sp[1]);
		}
		return out;
	}
	return {};
}

// jQuery helpers by kfrankiewicz

$.fn.setTimeout = function (fn,tm) {
  var t = $(this)[0];
  jQuery.data(t,'timeout', setTimeout(fn,tm) );
  return this;
}

$.fn.clearTimeout = function () {
  var t = $(this)[0];
  clearTimeout(jQuery.data(t,'timeout'));
  return this;
}


$.fn.store = function (n,o) {
  jQuery.data($(this)[0],n,o);
  return $(this);
}

$.fn.restore = function (n) {
  return jQuery.data($(this)[0],n);
}



$('#newsletter').live('submit',function (e) {
	e.preventDefault();
	var url = $(this).attr('action');
	$.ajax(url,{
		data : { mode : 'json', email: $('#newsletter input[name=nsemail]').val() },
		type : 'POST',
		success : function (data) {
			if (exists(data,'response'))
				alert(data.response);
			else
				alert('Response error.');
		},
		error : function (a,b,c)
		{
			alert(b);
		}
	});
	
});

$('a[href^="submit"]').live('click',function (e) {
	e.preventDefault();
	var t = $(this).attr('href').substr(6);
	$(t).submit();
});

$('#menu li').live('mouseenter',function (e) {
	if ($(this).find('.submenu').size() > 0)
	{
		var t = $(this).addClass('active');
		var o = $(this).find('.submenu').clone().appendTo('body');
		o.css({ top: t.offset().top+t.outerHeight(), left: t.offset().left });
		o.show();
		t.store('menu',o);
		o.store('parent',t);
		t.mouseleave(function () {
			o.setTimeout(function () {
				if (typeof(o.restore('parent')) != 'undefined' )
					o.restore('parent').removeClass('active');
					o.remove();
			},300);
		});
		o.mouseenter(function () {
			o.clearTimeout();
		});
		o.mouseleave(function () {
			o.setTimeout(function () { if (typeof(o.restore('parent')) != 'undefined' ) o.restore('parent').removeClass('active'); o.remove(); },300);
		});
	}
	else if ($(this).hasClass('active'))
		$(this).restore('menu').clearTimeout();
});

$('#search').live('submit',function (e) {
	e.preventDefault();
	var tag = $(this).find('input').val();
	var url = $(this).attr('action');
	location.href = url+'#'+tag;
});


$(document).ready(function() {
	Shadowbox.init();
  // set up all anchor elements with a "movie" class to work with Shadowbox
  Shadowbox.setup("a.zoom", {
  });

});

