/* Cufon */

Cufon.replace('.section .header h1');
Cufon.replace('#multimedia h1');
Cufon.replace('.jutarnjionline h1');
Cufon.replace('.sectionhead h1');
Cufon.replace('.redbg');
Cufon.replace('.horoskop-box-content h3');
Cufon.replace('#article.kolumna .author h2');
Cufon.replace('#komentari h2');
Cufon.replace('#arhiva-kolumna h2');
Cufon.replace('.archive-sidebar h2');
Cufon.replace('#kolumne h2');
Cufon.replace('#arhiva-komentari h2');
Cufon.replace('#ex-kolumne h2');
Cufon.replace('.userprofile .info h1');
Cufon.replace('#osobetjedna h1');
Cufon.replace('#osobetjedna h2');
Cufon.replace('.weather-header h2');
Cufon.replace('#dnevnaarhiva .section h2');
Cufon.replace('#sveteme h2');
Cufon.replace('#mail-article h1');
Cufon.replace('#contentbox h1');
Cufon.replace('#report-story h1');
Cufon.replace('.errorpage h1');
Cufon.replace('.specijalhead h1');

/* Brightcove */

var player, video, modExp, modCon;

function onTemplateLoaded(pPlayer) {
	player = bcPlayer.getPlayer(pPlayer);
	video = player.getModule(APIModules.VIDEO_PLAYER);
	modExp = player.getModule(APIModules.EXPERIENCE);
    modCon = player.getModule(APIModules.CONTENT);
    modExp.addEventListener(BCExperienceEvent.TEMPLATE_READY, onTemplateReady);
    modCon.addEventListener(BCContentEvent.MEDIA_LOAD, onMediaLoad);
}

function onTemplateReady(e) {
    $("a[name='video_thumb'] img").each(
        	function() {
        		var element = $(this);
        		modCon.getMediaAsynch(element.attr('id'));
        	});
    $("a[name='youtube_thumb'] img").each(
    		function() {
        		var element = $(this);
        		var thumb = getScreen(element.attr('id'), 'small');
        		element.attr('src', thumb);
        	});
}

function onMediaLoad(e) {
	if(e == null) {
		// This means there was no media returned
	} else {
		if (e.media.thumbnailURL != null) {
			$("a[name='video_thumb'] #" + e.media.id).attr('src', e.media.thumbnailURL);
		} else {
			$("a[name='video_thumb'] #" + e.media.id).attr('src', 'template/images/slika-placeholder.png');
		}
	}
}

function loadDifferentVideo(videoId) {
	video.loadVideo(videoId);
}

function getScreen(url, size) {
	if(url === null){ return ""; }

	size = (size === null) ? "big" : size;
	var vid;
	var results;

	results = url.match("[\\?&]v=([^&#]*)");

	vid = ( results === null ) ? url : results[1];

	if(size == "small"){
		return "http://img.youtube.com/vi/"+vid+"/2.jpg";
	} else {
		return "http://img.youtube.com/vi/"+vid+"/0.jpg";
	}
}

(function($) {
$.fn.newsTicker = $.fn.newsticker = function(delay)
{
	delay = delay || 4000;
	initTicker = function(el)
	{
		$(el).show();
		stopTicker(el);
		el.items = $("li", el);
		// hide all items (except first one)
		el.items.not(":eq(0)").hide().end();
		// current item
		el.currentitem = 0;
		startTicker(el);
	};
	startTicker = function(el)
	{
		el.tickfn = setInterval(function() { doTick(el) }, delay)
	};
	stopTicker = function(el)
	{
		clearInterval(el.tickfn);
	};
	pauseTicker = function(el)
	{
		el.pause = true;
	};
	resumeTicker = function(el)
	{
		el.pause = false;
	};
	doTick = function(el)
	{
		// don't run if paused
		if(el.pause) return;
		// pause until animation has finished
		el.pause = true;
		// hide current item
		$(el.items[el.currentitem]).fadeOut("slow",
			function()
			{
				$(this).hide();
				// move to next item and show
				el.currentitem = ++el.currentitem % (el.items.size());
				$(el.items[el.currentitem]).fadeIn("slow",
					function()
					{
						el.pause = false;
					}
				);
			}
		);
	};
	this.each(
		function()
		{
			if(this.nodeName.toLowerCase()!= "ul") return;
			initTicker(this);
		}
	)
	.addClass("newsticker")
	.hover(
		function()
		{
			// pause if hovered over
			pauseTicker(this);
		},
		function()
		{
			// resume when not hovered over
			resumeTicker(this);
		}
	);
	return this;
};

})(jQuery);

/* Carousel */
(function($){$.fn.jCarouselLite=function(o){o=$.extend({btnPrev:null,btnNext:null,btnGo:null,mouseWheel:false,auto:null,speed:200,easing:null,vertical:false,circular:true,visible:3,start:0,scroll:1,beforeStart:null,afterEnd:null},o||{});return this.each(function(){var b=false,animCss=o.vertical?"top":"left",sizeCss=o.vertical?"height":"width";var c=$(this),ul=$("ul",c),tLi=$("li",ul),tl=tLi.size(),v=o.visible;if(o.circular){ul.prepend(tLi.slice(tl-v-1+1).clone()).append(tLi.slice(0,v).clone());o.start+=v}var f=$("li",ul),itemLength=f.size(),curr=o.start;c.css("visibility","visible");f.css({overflow:"hidden",float:o.vertical?"none":"left"});ul.css({margin:"0",padding:"0",position:"relative","list-style-type":"none","z-index":"1"});c.css({overflow:"hidden",position:"relative","z-index":"2",left:"0px"});var g=o.vertical?height(f):width(f);var h=g*itemLength;var j=g*v;f.css({width:"237px",height:"154px"});ul.css(sizeCss,h+"px").css(animCss,-(curr*g));c.css(sizeCss,j+"px");if(o.btnPrev)$(o.btnPrev).click(function(){return go(curr-o.scroll)});if(o.btnNext)$(o.btnNext).click(function(){return go(curr+o.scroll)});if(o.btnGo)$.each(o.btnGo,function(i,a){$(a).click(function(){return go(o.circular?o.visible+i:i)})});if(o.mouseWheel&&c.mousewheel)c.mousewheel(function(e,d){return d>0?go(curr-o.scroll):go(curr+o.scroll)});if(o.auto)setInterval(function(){go(curr+o.scroll)},o.auto+o.speed);function vis(){return f.slice(curr).slice(0,v)};function go(a){if(!b){if(o.beforeStart)o.beforeStart.call(this,vis());if(o.circular){if(a<=o.start-v-1){ul.css(animCss,-((itemLength-(v*2))*g)+"px");curr=a==o.start-v-1?itemLength-(v*2)-1:itemLength-(v*2)-o.scroll}else if(a>=itemLength-v+1){ul.css(animCss,-((v)*g)+"px");curr=a==itemLength-v+1?v+1:v+o.scroll}else curr=a}else{if(a<0||a>itemLength-v)return;else curr=a}b=true;ul.animate(animCss=="left"?{left:-(curr*g)}:{top:-(curr*g)},o.speed,o.easing,function(){if(o.afterEnd)o.afterEnd.call(this,vis());b=false});if(!o.circular){$(o.btnPrev+","+o.btnNext).removeClass("disabled");$((curr-o.scroll<0&&o.btnPrev)||(curr+o.scroll>itemLength-v&&o.btnNext)||[]).addClass("disabled")}}return false}})};function css(a,b){return parseInt($.css(a[0],b))||0};function width(a){return 244};function height(a){return a[0].offsetHeight+css(a,'marginTop')+css(a,'marginBottom')}})(jQuery);

/* Default value */
(function($){$.fn.defaultvalue=function(){var elements=this;var args=arguments;var c=0;return(elements.each(function(){var el=$(this);var def=args[c++];el.val(def).focus(function(){if(el.val()==def){el.val("")}el.blur(function(){if(el.val()==""){el.val(def)}})})}))}})(jQuery);

/* Tabify */
(function($){$.fn.extend({tabify:function(){return this.each(function(){$(this).find("li").each(function(){if($(this).hasClass("active")){$("#"+$(this).attr("rel")).show();}else{$("#"+$(this).attr("rel")).hide();}
$(this).click(function(){$(this).parent().find("li").each(function(){$(this).removeClass("active");$("#"+$(this).attr("rel")).hide();});$("#"+$(this).attr("rel")).show();$(this).addClass("active");});});});}});})(jQuery);

/* Article gallery */
(function($){$.fn.jArticleGallery=function(o){o=$.extend({btnPrev:null,btnNext:null,btnGo:null,mouseWheel:false,auto:null,speed:200,easing:null,vertical:false,circular:false,visible:3,start:0,scroll:1,beforeStart:null,afterEnd:null},o||{});return this.each(function(){var running=false,animCss=o.vertical?"top":"left",sizeCss=o.vertical?"height":"width";var div=$(this),ul=$("ul",div),tLi=$("li",ul),tl=tLi.size(),v=o.visible;if(o.circular){ul.prepend(tLi.slice(tl-v-1+1).clone()).append(tLi.slice(0,v).clone());o.start+=v}var li=$("li",ul),itemLength=li.size(),curr=o.start;div.css("visibility","visible");$("#count span").text('('+(curr+1)+'/'+itemLength+')');li.css({overflow:"hidden",float:o.vertical?"none":"left"});ul.css({margin:"0",padding:"0",position:"relative","list-style-type":"none","z-index":"1"});div.css({overflow:"hidden",position:"relative","z-index":"2",left:"0px"});var liSize=o.vertical?height(li):width(li);var ulSize=liSize*itemLength;var divSize=liSize*v;
var maxHeight = 0;
ul.children().each(
  function(){
    if ($(this).height() > maxHeight) maxHeight = $(this).height();
    $(this).css("display", "block");
  }
);
li.css({width:"652px",height: maxHeight});ul.css(sizeCss,ulSize+"px").css(animCss,-(curr*liSize));div.css(sizeCss,divSize+"px");if(o.btnPrev)$(o.btnPrev).click(function(){return go(curr-o.scroll)});if(o.btnNext)$(o.btnNext).click(function(){return go(curr+o.scroll)});if(o.btnGo)$.each(o.btnGo,function(i,val){$(val).click(function(){return go(o.circular?o.visible+i:i)})});if(o.mouseWheel&&div.mousewheel)div.mousewheel(function(e,d){return d>0?go(curr-o.scroll):go(curr+o.scroll)});if(o.auto)setInterval(function(){go(curr+o.scroll)},o.auto+o.speed);function vis(){return li.slice(curr).slice(0,v)};function go(to){if(!running){if(o.beforeStart)o.beforeStart.call(this,vis());if(o.circular){if(to<=o.start-v-1){ul.css(animCss,-((itemLength-(v*2))*liSize)+"px");curr=to==o.start-v-1?itemLength-(v*2)-1:itemLength-(v*2)-o.scroll}else if(to>=itemLength-v+1){ul.css(animCss,-((v)*liSize)+"px");curr=to==itemLength-v+1?v+1:v+o.scroll}else curr=to}else{if(to<0||to>itemLength-v)return;else curr=to}running=true;ul.animate(animCss=="left"?{left:-(curr*liSize)}:{top:-(curr*liSize)},o.speed,o.easing,function(){if(o.afterEnd)o.afterEnd.call(this,vis());running=false});if(!o.circular){$(o.btnPrev+","+o.btnNext).removeClass("disabled");$((curr-o.scroll<0&&o.btnPrev)||(curr+o.scroll>itemLength-v&&o.btnNext)||[]).addClass("disabled")}$("#count span").text('('+(curr+1)+'/'+itemLength+')')}return false}})};function css(el,prop){return parseInt($.css(el[0],prop))||0};function width(el){return el[0].offsetWidth+css(el,'marginLeft')+css(el,'marginRight')};function height(el){return el[0].offsetHeight+css(el,'marginTop')+css(el,'marginBottom')}})(jQuery);

/*
Date Input 1.1.8
*/

DateInput = (function($) { // Localise the $ function

function DateInput(el, opts) {
  if (typeof(opts) != "object") opts = {};
  $.extend(this, DateInput.DEFAULT_OPTS, opts);

  this.input = $(el);
  this.bindMethodsToObj("show", "hide", "hideIfClickOutside", "hideOnEsc", "selectDate", "prevMonth", "nextMonth");

  this.build();
  this.selectDate();
  this.hide();
};
DateInput.DEFAULT_OPTS = {
  month_names: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
  short_month_names: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
  short_day_names: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
  start_of_week: 1
};
DateInput.prototype = {
  build: function() {
    this.monthNameSpan = $('<span class="month_name"></span>');
    var monthNav = $('<p class="month_nav"></p>').append(
      $('<a href="#" class="prev">&laquo;</a> ').click(this.prevMonth),
      this.monthNameSpan,
      $(' <a href="#" class="next">&raquo;</a>').click(this.nextMonth)
    );

    var tableShell = "<table><thead><tr>";
    $(this.adjustDays(this.short_day_names)).each(function() {
      tableShell += "<th>" + this + "</th>";
    });
    tableShell += "</tr></thead><tbody></tbody></table>";

    this.dateSelector = this.rootLayers = $('<div class="date_selector"></div>').append(monthNav, tableShell).insertAfter(this.input);

    if ($.browser.msie && $.browser.version < 7) {
      this.ieframe = $('<iframe class="date_selector_ieframe" frameborder="0" src="#"></iframe>').insertBefore(this.dateSelector);
      this.rootLayers = this.rootLayers.add(this.ieframe);
    };

    this.tbody = $("tbody", this.dateSelector);

    // The anon function ensures the event is discarded
    this.input.change(this.bindToObj(function() { this.selectDate(); }));
  },

  selectMonth: function(date) {
    this.currentMonth = new Date(date.getFullYear(), date.getMonth(), 1);

    var rangeStart = this.rangeStart(date), rangeEnd = this.rangeEnd(date);
    var numDays = this.daysBetween(rangeStart, rangeEnd);
    var dayCells = "";

    for (var i = 0; i <= numDays; i++) {
      var currentDay = new Date(rangeStart.getFullYear(), rangeStart.getMonth(), rangeStart.getDate() + i, 12, 00);

      if (this.isFirstDayOfWeek(currentDay)) dayCells += "<tr>";

      if (currentDay.getMonth() == date.getMonth()) {
        dayCells += '<td date="' + this.dateToString(currentDay) + '"><a href="#">' + currentDay.getDate() + '</a></td>';
      } else {
        dayCells += '<td class="unselected_month" date="' + this.dateToString(currentDay) + '">' + currentDay.getDate() + '</td>';
      };

      if (this.isLastDayOfWeek(currentDay)) dayCells += "</tr>";
    };

    this.monthNameSpan.empty().append(this.monthName(date) + " " + date.getFullYear());
    this.tbody.empty().append(dayCells);

    $("a", this.tbody).click(this.bindToObj(function(event) {
      this.selectDate(this.stringToDate($(event.target).parent().attr("date")));
      this.hide();
      return false;
    }));

    $("td[date=" + this.dateToString(new Date()) + "]", this.tbody).addClass("today");
  },

  selectDate: function(date) {
    if (typeof(date) == "undefined") {
      date = this.stringToDate(this.input.val());
    };

    if (date) {
      this.selectedDate = date;
      this.selectMonth(date);
      var stringDate = this.dateToString(date);
      $('td[date=' + stringDate + ']', this.tbody).addClass("selected");

      if (this.input.val() != stringDate) {
        this.input.val(stringDate).change();
      };
    } else {
      this.selectMonth(new Date());
    };
  },

  show: function() {
    this.rootLayers.css("display", "block");
    this.setPosition();
    this.input.unbind("focus", this.show);
    $("a:last", this.dateSelector).blur(this.hide);
    $([window, document.body]).click(this.hideIfClickOutside).keyup(this.hideOnEsc);
  },

  hide: function() {
    this.rootLayers.css("display", "none");
    $([window, document.body]).unbind("click", this.hideIfClickOutside).unbind("keyup", this.hideOnEsc);
    $("a:last", this.dateSelector).unbind("blur", this.hide);
    this.input.focus(this.show);
  },

  hideIfClickOutside: function(event) {
    if (event.target != this.input[0] && !this.insideSelector(event)) {
      this.hide();
    };
  },

  hideOnEsc: function(event) {
    if (event.keyCode == 27) {
      this.hide();
    };
  },

  stringToDate: function(string) {
    var matches;
    if (matches = string.match(/^(\d{1,2}) ([^\s]+) (\d{4,4})$/)) {
      return new Date(matches[3], this.shortMonthNum(matches[2]), matches[1], 12, 00);
    } else {
      return null;
    };
  },

  dateToString: function(date) {
    return date.getDate() + " " + this.short_month_names[date.getMonth()] + " " + date.getFullYear();
  },

  setPosition: function() {
    var offset = this.input.offset();
    this.rootLayers.css({
      top: offset.top + this.input.outerHeight(),
      left: offset.left
    });

    if (this.ieframe) {
      this.ieframe.css({
        width: this.dateSelector.outerWidth(),
        height: this.dateSelector.outerHeight()
      });
    };
  },

  moveMonthBy: function(amount) {
    this.selectMonth(new Date(this.currentMonth.setMonth(this.currentMonth.getMonth() + amount)));
  },

  prevMonth: function() {
    this.moveMonthBy(-1);
    return false;
  },

  nextMonth: function() {
    this.moveMonthBy(1);
    return false;
  },

  monthName: function(date) {
    return this.month_names[date.getMonth()];
  },

  insideSelector: function(event) {
    var offset = this.dateSelector.offset();
    offset.right = offset.left + this.dateSelector.outerWidth();
    offset.bottom = offset.top + this.dateSelector.outerHeight();

    return event.pageY < offset.bottom &&
           event.pageY > offset.top &&
           event.pageX < offset.right &&
           event.pageX > offset.left;
  },

  bindToObj: function(fn) {
    var self = this;
    return function() { return fn.apply(self, arguments) };
  },

  bindMethodsToObj: function() {
    for (var i = 0; i < arguments.length; i++) {
      this[arguments[i]] = this.bindToObj(this[arguments[i]]);
    };
  },

  indexFor: function(array, value) {
    for (var i = 0; i < array.length; i++) {
      if (value == array[i]) return i;
    };
  },

  monthNum: function(month_name) {
    return this.indexFor(this.month_names, month_name);
  },

  shortMonthNum: function(month_name) {
    return this.indexFor(this.short_month_names, month_name);
  },

  shortDayNum: function(day_name) {
    return this.indexFor(this.short_day_names, day_name);
  },

  daysBetween: function(start, end) {
    start = Date.UTC(start.getFullYear(), start.getMonth(), start.getDate());
    end = Date.UTC(end.getFullYear(), end.getMonth(), end.getDate());
    return (end - start) / 86400000;
  },

  changeDayTo: function(to, date, direction) {
    var difference = direction * (Math.abs(date.getDay() - to - (direction * 7)) % 7);
    return new Date(date.getFullYear(), date.getMonth(), date.getDate() + difference);
  },

  rangeStart: function(date) {
    return this.changeDayTo(this.start_of_week, new Date(date.getFullYear(), date.getMonth()), -1);
  },

  rangeEnd: function(date) {
    return this.changeDayTo((this.start_of_week - 1) % 7, new Date(date.getFullYear(), date.getMonth() + 1, 0), 1);
  },

  isFirstDayOfWeek: function(date) {
    return date.getDay() == this.start_of_week;
  },

  isLastDayOfWeek: function(date) {
    return date.getDay() == (this.start_of_week - 1) % 7;
  },

  adjustDays: function(days) {
    var newDays = [];
    for (var i = 0; i < days.length; i++) {
      newDays[i] = days[(i + this.start_of_week) % 7];
    };
    return newDays;
  }
};

$.fn.date_input = function(opts) {
  return this.each(function() { new DateInput(this, opts); });
};
$.date_input = { initialize: function(opts) {
  $("input.date_input").date_input(opts);
} };

return DateInput;
})(jQuery); // End localisation of the $ function

jQuery.extend(DateInput.DEFAULT_OPTS, {
  month_names: ["Siječanj", "Veljača", "Ožujak", "Travanj", "Svibanj", "Lipanj", "Srpanj", "Kolovoz", "Rujan", "Listopad", "Studeni", "Prosinac"],
  short_month_names: ["Sij", "Velj", "Ožu", "Trav", "Svi", "Lip", "Srp", "Kol", "Ruj", "Lis", "Stu", "Pro"],
  short_day_names: ["Ned", "Pon", "Uto", "Sri", "Čet", "Pet", "Sub"]
});

$.extend(DateInput.DEFAULT_OPTS, {
  stringToDate: function(string) {
    var matches;
    if (matches = string.match(/^(\d{4,4})-(\d{2,2})-(\d{2,2})$/)) {
      return new Date(matches[1], matches[2] - 1, matches[3]);
    } else {
      return null;
    };
  },

  dateToString: function(date) {
    var month = (date.getMonth() + 1).toString();
    var dom = date.getDate().toString();
    if (month.length == 1) month = "0" + month;
    if (dom.length == 1) dom = "0" + dom;
    return date.getFullYear() + "-" + month + "-" + dom;
  }
});

/* ColorBox */

/*
	ColorBox v1.1.5 - a full featured, light-weight, customizable lightbox based on jQuery 1.3
	(c) 2009 Jack Moore - www.colorpowered.com - jack@colorpowered.com
	Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
*/

(function($){
var clone, loadedWidth, loadedHeight, interfaceHeight, interfaceWidth, index, related, closeModal, loadingElement, modal, modalWrap, modalOverlay, modalLoadingOverlay, modalContent, loaded, modalClose, btc, bml, bmr, bbc;
function setModalOverlay(){
	$([modalOverlay]).css({"position":"absolute", width:$(window).width(), height:$(window).height(), top:$(window).scrollTop(), left:$(window).scrollLeft()});
}
function keypressEvents(e){
	if(e.keyCode == 37){
		$(document).unbind('keydown.colorKeys');
		$("a#contentPrevious").click();
	} else if(e.keyCode == 39){
		$(document).unbind('keydown.colorKeys');
		$("a#contentNext").click();
	}
}
function clearLoading(){
	if($("#colorboxInlineTemp").length > 0){
		$(loaded).children().insertAfter("#colorboxInlineTemp");
	}
	if(loadingElement){$(loadingElement).remove();}
}

closeModal = function(){
	clearLoading();
	$(modalOverlay).css({cursor:"auto"}).fadeOut("fast");
	$(modal).stop(true, false).removeData("open").fadeOut("fast", function(){
		$(loaded).remove();
	});
	$(document).unbind('keydown.colorKeys');
	$(window).unbind('resize scroll', setModalOverlay);
};

// Convert % values to pixels
function setSize(size, dimension){
	return (typeof size == 'string') ? (size.match(/%/) ? (dimension/100)*parseInt(size, 10) : parseInt(size, 10)) : size;
}

//Initialize the modal: store common calculations, preload the interface graphics, append the html.
$(function(){
	$("body").append(
		$([
			modalOverlay = $('<div id="modalBackgroundOverlay" />')[0],
			modal = $('<div id="colorbox" />')[0]
		]).hide()
	);
	$(modal).append(
		$([
			modalWrap = $('<div id="modalWrap" />')[0]
		])
	).css("opacity", 0).show();
	$(modalWrap).append(
		$([
			$('<div><div id="borderTopLeft"></div><div id="borderTopCenter"></div><div id="borderTopRight"></div></div>')[0],
			bml = $('<div id="borderMiddleLeft" />')[0],
			modalContent = $('<div id="modalContent" />')[0],
			bmr = $('<div id="borderMiddleRight" />')[0],
			$('<div><div id="borderBottomLeft"></div><div id="borderBottomCenter"></div><div id="borderBottomRight"></div></div>')[0]
		])
	);
	$(modalContent).append(
		$([
			loaded = $('<div id="modalLoadedContent"><a id="contentPrevious" href="#"></a><a id="contentNext" href="#"></a><span id="contentCurrent"></span><br id="modalInfoBr"/><span id="contentTitle"></span><div id="preloadPrevious"></div><div id="preloadNext"></div><div id="preloadClose"></div></div>')[0],
			modalLoadingOverlay = $('<div id="modalLoadingOverlay" />')[0],
			modalClose = $('<a id="modalClose" href="#"></a>')[0]
		])
	);

	$(document).bind("keydown.colorClose", function(e){
		if (e.keyCode == 27) { closeModal(); }
	});

	$(modalClose).click(function(){
		closeModal();
		return false;
	});

	btc = $("#borderTopCenter")[0];
	bbc = $("#borderBottomCenter")[0];

	interfaceHeight = $(btc).height()+$(bbc).height()+$(modalContent).outerHeight(true) - $(modalContent).height();//Subtraction needed for IE6
	interfaceWidth = $(bml).width()+$(bmr).width()+$(modalContent).outerWidth(true) - $(modalContent).width();

	loadedHeight = $(loaded).outerHeight(true);
	loadedWidth = $(loaded).outerWidth(true);

	$(loaded).empty();
	$(modal).css({"padding-bottom":interfaceHeight,"padding-right":interfaceWidth}).hide();//the padding removes the need to do size conversions during the animation step.

	//Archaic rollover code because IE8 is a piece of shit.  Hopefully they'll fix their css-rollover bug so the following code can be removed.
	$("#contentPrevious, #contentNext, #modalClose").live('mouseover', function(){$(this).addClass("hover");});
	$("#contentPrevious, #contentNext, #modalClose").live('mouseout', function(){$(this).removeClass("hover");});
});

$.fn.colorbox = function(settings, callback) {

	function modalPosition(mWidth, mHeight, speed, loadedCallback){

		var winHeight = document.documentElement.clientHeight;
		var posTop = winHeight/2 - mHeight/2 + $(window).scrollTop();
		var posLeft = document.documentElement.clientWidth/2 - mWidth/2 + $(window).scrollLeft();
		//keeps the box from expanding to an inaccessible area offscreen.
		if(mHeight > winHeight){posTop -=(mHeight - winHeight);}
		if(posTop < 0){posTop = 0;}
		if(posLeft < 0){posLeft = 0;}

		mWidth = mWidth - interfaceWidth;
		mHeight = mHeight - interfaceHeight;

		function modalDimensions(that){
			modalContent.style.width = btc.style.width = bbc.style.width = that.style.width;
			modalContent.style.height = bml.style.height = bmr.style.height = that.style.height;
		}

		$(modal).animate({height:mHeight, width:mWidth, top:posTop, left:posLeft}, {duration: speed,
			complete: function(){
				if (loadedCallback) {loadedCallback();}
				modalDimensions(this);
				if ($.browser.msie && $.browser.version < 7) {setModalOverlay();}
			},
			step: function(){
				modalDimensions(this);
			}
		});
	}
	var preloads = [];
	function preload(){
		if(settings.preloading !== false && related.length>1 && related[index].href.match(/\.(gif|png|jpg|jpeg|bmp)(?:\?([^#]*))?(?:#(.*))?$/i)){
			var previous, next;
			previous = index > 0 ? related[index-1].href : related[related.length-1].href;
			next = index < related.length-1 ? related[index+1].href : related[0].href;
			return [$("<img />").attr("src", next), $("<img />").attr("src", previous)];
		}
		return false;
	}

	function contentNav(){
		$(modalLoadingOverlay).show();
		if($(this).attr("id") == "contentPrevious"){
			index = index > 0 ? index-1 : related.length-1;
		} else {
			index = index < related.length-1 ? index+1 : 0;
		}
		loadModal(related[index].href, related[index].title);
	}

	function centerModal (object, contentInfo){
		if($(modal).data("open")!==true){ return false; }

		var speed = settings.transition=="none" ? 0 : settings.transitionSpeed;
		$(loaded).remove();
		loaded = $(object)[0];

		$(loaded).hide()
		.appendTo('body')
		.css({width:(settings.fixedWidth)?settings.fixedWidth - loadedWidth - interfaceWidth:$(loaded).width()}).css({height:(settings.fixedHeight)?settings.fixedHeight - loadedHeight - interfaceHeight:$(loaded).height()})
		.attr({id:"modalLoadedContent"})
		.append(contentInfo)
		.prependTo($(modalContent));

		if($("#modalPhoto").length > 0 && settings.fixedHeight){
			var topMargin = (parseInt($(loaded)[0].style.height, 10) - parseInt($("#modalPhoto")[0].style.height, 10))/2;
			$("#modalPhoto").css({marginTop:(topMargin > 0?topMargin:0)});
		}

		function setPosition(s){
			modalPosition(parseInt(loaded.style.width, 10)+loadedWidth+interfaceWidth, parseInt(loaded.style.height, 10)+loadedHeight+interfaceHeight, s, function(){
				if($(modal).data("open")!==true){
					return false;
				}
				$(loaded).show();
				$(modalLoadingOverlay).hide();
				$(document).bind('keydown.colorKeys', keypressEvents);
				if (callback) {
					callback();
				}
				if (settings.transition === "fade"){
					$(modal).animate({"opacity":1}, speed);
				}
				return true;
			});
		}
		if (settings.transition == "fade") {
			$(modal).animate({"opacity":0}, speed, function(){setPosition(0);});
		} else {
			setPosition(speed);
		}
		var preloads = preload();
		return true;
	}

	function loadModal(href, title){
		clearLoading();
		var contentInfo = "<p id='contentTitle'>"+title+"</p>";
		if(related.length>1){
			contentInfo += "<span id='contentCurrent'> " + settings.contentCurrent + "</span>";
			contentInfo = contentInfo.replace(/\{current\}/, index+1).replace(/\{total\}/, related.length);
			contentInfo += "<a id='contentPrevious' href='#'>"+settings.contentPrevious+"</a><a id='contentNext' href='#'>"+settings.contentNext+"</a> ";
		}
		if (settings.inline) {
			loadingElement = $('<div id="colorboxInlineTemp" />').hide().insertBefore($(href)[0]);
			clone = $(href).clone(true);
			centerModal($(href).wrapAll("<div />").parent(), contentInfo);
		} else if (settings.iframe) {
			centerModal($("<div><iframe name='iframe_"+new Date().getTime()+" 'frameborder=0 src =" + href + "></iframe></div>"), contentInfo);//timestamp to prevent caching.
		} else if (href.match(/\.(gif|png|jpg|jpeg|bmp)(?:\?([^#]*))?(?:#(.*))?$/i)){
			loadingElement = new Image();
			loadingElement.onload = function(){
				loadingElement.onload = null;
				centerModal($("<div />").css({width:this.width, height:this.height}).append($(this).css({width:this.width, height:this.height, display:"block", margin:"auto"}).attr('id', 'modalPhoto')), contentInfo);
				if(related.length > 1){
					$(this).css({cursor:'pointer'}).click(contentNav);
				}
			};
			loadingElement.src = href;
		}else {
			loadingElement = $('<div />').load(href, function(data, textStatus){
				if(textStatus == "success"){
					centerModal($(this), contentInfo);
				} else {
					centerModal($("<p>Request unsuccessful.</p>"));
				}
			});
		}
	}

	settings = $.extend({}, $.fn.colorbox.settings, settings);

	$(this).unbind("click.colorbox").bind("click.colorbox", function () {
		if(settings.fixedWidth){ settings.fixedWidth = setSize(settings.fixedWidth, document.documentElement.clientWidth);}
		if(settings.fixedHeight){ settings.fixedHeight = setSize(settings.fixedHeight, document.documentElement.clientHeight);}
		if (this.rel && 'nofollow' != this.rel) {
			related = $("a[rel='" + this.rel + "']");
			index = $(related).index(this);
		}
		else {
			related = $(this);
			index = 0;
		}

		if ($(modal).data("open") !== true) {
			$(document).bind('keydown.colorKeys', keypressEvents);
			$(modalClose).html(settings.modalClose);
			$(modalOverlay).css({"opacity": settings.bgOpacity});
			$(modal).data("open", true).css({"opacity":1});
			$([modal, modalLoadingOverlay, modalOverlay]).show();

			modalPosition(setSize(settings.initialWidth, document.documentElement.clientWidth), setSize(settings.initialHeight, document.documentElement.clientHeight), 0);

			if ($.browser.msie && $.browser.version < 7) {
				$(window).bind("resize scroll", setModalOverlay);
			}
		}

		loadModal(settings.href ? settings.href : related[index].href, settings.title ? settings.title : related[index].title);
		$("a#contentPrevious, a#contentNext").die().live("click", contentNav);

		if(settings.overlayClose!==false){
			$(modalOverlay).css({"cursor":"pointer"}).click(function(){closeModal();});
		}
		return false;
	});

	if(settings.open!==false && $(modal).data("open")!==true){
		$(this).triggerHandler('click.colorbox');
	}

	return this.each(function() {
	});
};

/*
	ColorBox Default Settings.

	The colorbox() function takes one argument, an object of key/value pairs, that are used to initialize the modal.

	Please do not change these settings here, instead overwrite these settings when attaching the colorbox() event to your anchors.
	Example (Global)	: $.fn.colorbox.settings.transition = "fade"; //changes the transition to fade for all colorBox() events proceeding it's declaration.
	Example (Specific)	: $("a[href='http://www.google.com']").colorbox({fixedWidth:"90%", fixedHeight:"450px", iframe:true});
*/
$.fn.colorbox.settings = {
	transition : "elastic", // Transition types: "elastic", "fade", or "none".
	transitionSpeed : 0, // Sets the speed of the fade and elastic transitions, in milliseconds.
	initialWidth : "400", // Set the initial width of the modal, prior to any content being loaded.
	initialHeight : "400", // Set the initial height of the modal, prior to any content being loaded.
	fixedWidth : false, // Set a fixed width for div#loaded.  Example: "500px"
	fixedHeight : false, // Set a fixed height for div#modalLoadedContent.  Example: "500px"
	inline : false, // Set this to the selector of inline content to be displayed.  Example "#myHiddenDiv" or "body p".
	iframe : false, // If 'true' specifies that content should be displayed in an iFrame.
	href : false, // This can be used as an alternate anchor URL for ColorBox to use, or can be used to assign a URL for non-anchor elments such as images or form buttons.
	title : false, // This can be used as an alternate anchor title.
	bgOpacity : 1, // The modalBackgroundOverlay opacity level. Range: 0 to 1.
	preloading : true, // Allows for preloading of 'Next' and 'Previous' content in a shared relation group (same values for the 'rel' attribute), after the current content has finished loading.  Set to 'false' to disable.
	contentCurrent : "image {current} of {total}", // the format of the contentCurrent information
	contentPrevious : "previous", // the anchor text for the previous link in a shared relation group (same values for 'rel').
	contentNext : "next", // the anchor text for the next link in a shared relation group (same 'rel' attribute').
	modalClose : "close", // the anchor text for the close link.  Esc will also close the modal.
	open : false, //Automatically opens ColorBox. (fires the click.colorbox event without waiting for user input).
	overlayClose : true  //If true, enables closing ColorBox by clicking on the background overlay.
};

})(jQuery);


(function($) {

$.jScrollPane = {
	active : []
};
$.fn.jScrollPane = function(settings)
{
	settings = $.extend({}, $.fn.jScrollPane.defaults, settings);

	var rf = function() { return false; };

	return this.each(
		function()
		{
			var $this = $(this);
			// Switch the element's overflow to hidden to ensure we get the size of the element without the scrollbars [http://plugins.jquery.com/node/1208]
			$this.css('overflow', 'hidden');
			var paneEle = this;

			if ($(this).parent().is('.jScrollPaneContainer')) {
				var currentScrollPosition = settings.maintainPosition ? $this.position().top : 0;
				var $c = $(this).parent();
				var paneWidth = $c.innerWidth();
				var paneHeight = $c.outerHeight();
				var trackHeight = paneHeight;
				$('>.jScrollPaneTrack, >.jScrollArrowUp, >.jScrollArrowDown', $c).remove();
				$this.css({'top':0});
			} else {
				var currentScrollPosition = 0;
				this.originalPadding = $this.css('paddingTop') + ' ' + $this.css('paddingRight') + ' ' + $this.css('paddingBottom') + ' ' + $this.css('paddingLeft');
				this.originalSidePaddingTotal = (parseInt($this.css('paddingLeft')) || 0) + (parseInt($this.css('paddingRight')) || 0);
				var paneWidth = $this.innerWidth();
				var paneHeight = $this.innerHeight();
				var trackHeight = paneHeight;
				$this.wrap(
					$('<div></div>').attr(
						{'className':'jScrollPaneContainer'}
					).css(
						{
							'height':paneHeight+'px',
							'width':paneWidth+'px'
						}
					)
				);
				// deal with text size changes (if the jquery.em plugin is included)
				// and re-initialise the scrollPane so the track maintains the
				// correct size
				$(document).bind(
					'emchange',
					function(e, cur, prev)
					{
						$this.jScrollPane(settings);
					}
				);

			}

			if (settings.reinitialiseOnImageLoad) {
				// code inspired by jquery.onImagesLoad: http://plugins.jquery.com/project/onImagesLoad
				// except we re-initialise the scroll pane when each image loads so that the scroll pane is always up to size...
				// TODO: Do I even need to store it in $.data? Is a local variable here the same since I don't pass the reinitialiseOnImageLoad when I re-initialise?
				var $imagesToLoad = $.data(paneEle, 'jScrollPaneImagesToLoad') || $('img', $this);
				var loadedImages = [];

				if ($imagesToLoad.length) {
					$imagesToLoad.each(function(i, val)	{
						$(this).bind('load', function() {
							if($.inArray(i, loadedImages) == -1){ //don't double count images
								loadedImages.push(val); //keep a record of images we've seen
								$imagesToLoad = $.grep($imagesToLoad, function(n, i) {
									return n != val;
								});
								$.data(paneEle, 'jScrollPaneImagesToLoad', $imagesToLoad);
								settings.reinitialiseOnImageLoad = false;
								$this.jScrollPane(settings); // re-initialise
							}
						}).each(function(i, val) {
							if(this.complete || this.complete===undefined) {
								//needed for potential cached images
								this.src = this.src;
							}
						});
					});
				};
			}

			var p = this.originalSidePaddingTotal;

			var cssToApply = {
				'height':'auto',
				'width':paneWidth - settings.scrollbarWidth - settings.scrollbarMargin - p + 'px'
			}

			if(settings.scrollbarOnLeft) {
				cssToApply.paddingLeft = settings.scrollbarMargin + settings.scrollbarWidth + 'px';
			} else {
				cssToApply.paddingRight = settings.scrollbarMargin + 'px';
			}

			$this.css(cssToApply);

			var contentHeight = $this.outerHeight();
			var percentInView = paneHeight / contentHeight;

			if (percentInView < .99) {
				var $container = $this.parent();
				$container.append(
					$('<div></div>').attr({'className':'jScrollPaneTrack'}).css({'width':settings.scrollbarWidth+'px'}).append(
						$('<div></div>').attr({'className':'jScrollPaneDrag'}).css({'width':settings.scrollbarWidth+'px'}).append(
							$('<div></div>').attr({'className':'jScrollPaneDragTop'}).css({'width':settings.scrollbarWidth+'px'}),
							$('<div></div>').attr({'className':'jScrollPaneDragBottom'}).css({'width':settings.scrollbarWidth+'px'})
						)
					)
				);

				var $track = $('>.jScrollPaneTrack', $container);
				var $drag = $('>.jScrollPaneTrack .jScrollPaneDrag', $container);

				if (settings.showArrows) {

					var currentArrowButton;
					var currentArrowDirection;
					var currentArrowInterval;
					var currentArrowInc;
					var whileArrowButtonDown = function()
					{
						if (currentArrowInc > 4 || currentArrowInc%4==0) {
							positionDrag(dragPosition + currentArrowDirection * mouseWheelMultiplier);
						}
						currentArrowInc ++;
					};
					var onArrowMouseUp = function(event)
					{
						$('html').unbind('mouseup', onArrowMouseUp);
						currentArrowButton.removeClass('jScrollActiveArrowButton');
						clearInterval(currentArrowInterval);
					};
					var onArrowMouseDown = function() {
						$('html').bind('mouseup', onArrowMouseUp);
						currentArrowButton.addClass('jScrollActiveArrowButton');
						currentArrowInc = 0;
						whileArrowButtonDown();
						currentArrowInterval = setInterval(whileArrowButtonDown, 100);
					};
					$container
						.append(
							$('<a></a>')
								.attr({'href':'javascript:;', 'className':'jScrollArrowUp'})
								.css({'width':settings.scrollbarWidth+'px'})
								.html('Scroll up')
								.bind('mousedown', function()
								{
									currentArrowButton = $(this);
									currentArrowDirection = -1;
									onArrowMouseDown();
									this.blur();
									return false;
								})
								.bind('click', rf),
							$('<a></a>')
								.attr({'href':'javascript:;', 'className':'jScrollArrowDown'})
								.css({'width':settings.scrollbarWidth+'px'})
								.html('Scroll down')
								.bind('mousedown', function()
								{
									currentArrowButton = $(this);
									currentArrowDirection = 1;
									onArrowMouseDown();
									this.blur();
									return false;
								})
								.bind('click', rf)
						);
					var $upArrow = $('>.jScrollArrowUp', $container);
					var $downArrow = $('>.jScrollArrowDown', $container);
					if (settings.arrowSize) {
						trackHeight = paneHeight - settings.arrowSize - settings.arrowSize;
						$track
							.css({'height': trackHeight+'px', top:settings.arrowSize+'px'})
					} else {
						var topArrowHeight = $upArrow.height();
						settings.arrowSize = topArrowHeight;
						trackHeight = paneHeight - topArrowHeight - $downArrow.height();
						$track
							.css({'height': trackHeight+'px', top:topArrowHeight+'px'})
					}
				}

				var $pane = $(this).css({'position':'absolute', 'overflow':'visible'});

				var currentOffset;
				var maxY;
				var mouseWheelMultiplier;
				// store this in a seperate variable so we can keep track more accurately than just updating the css property..
				var dragPosition = 0;
				var dragMiddle = percentInView*paneHeight/2;

				// pos function borrowed from tooltip plugin and adapted...
				var getPos = function (event, c) {
					var p = c == 'X' ? 'Left' : 'Top';
					return event['page' + c] || (event['client' + c] + (document.documentElement['scroll' + p] || document.body['scroll' + p])) || 0;
				};

				var ignoreNativeDrag = function() {	return false; };

				var initDrag = function()
				{
					ceaseAnimation();
					currentOffset = $drag.offset(false);
					currentOffset.top -= dragPosition;
					maxY = trackHeight - $drag[0].offsetHeight;
					mouseWheelMultiplier = 2 * settings.wheelSpeed * maxY / contentHeight;
				};

				var onStartDrag = function(event)
				{
					initDrag();
					dragMiddle = getPos(event, 'Y') - dragPosition - currentOffset.top;
					$('html').bind('mouseup', onStopDrag).bind('mousemove', updateScroll);
					if ($.browser.msie) {
						$('html').bind('dragstart', ignoreNativeDrag).bind('selectstart', ignoreNativeDrag);
					}
					return false;
				};
				var onStopDrag = function()
				{
					$('html').unbind('mouseup', onStopDrag).unbind('mousemove', updateScroll);
					dragMiddle = percentInView*paneHeight/2;
					if ($.browser.msie) {
						$('html').unbind('dragstart', ignoreNativeDrag).unbind('selectstart', ignoreNativeDrag);
					}
				};
				var positionDrag = function(destY)
				{
					destY = destY < 0 ? 0 : (destY > maxY ? maxY : destY);
					dragPosition = destY;
					$drag.css({'top':destY+'px'});
					var p = destY / maxY;
					$pane.css({'top':((paneHeight-contentHeight)*p) + 'px'});
					$this.trigger('scroll');
					if (settings.showArrows) {
						$upArrow[destY == 0 ? 'addClass' : 'removeClass']('disabled');
						$downArrow[destY == maxY ? 'addClass' : 'removeClass']('disabled');
					}
				};
				var updateScroll = function(e)
				{
					positionDrag(getPos(e, 'Y') - currentOffset.top - dragMiddle);
				};

				var dragH = Math.max(Math.min(percentInView*(paneHeight-settings.arrowSize*2), settings.dragMaxHeight), settings.dragMinHeight);

				$drag.css(
					{'height':dragH+'px'}
				).bind('mousedown', onStartDrag);

				var trackScrollInterval;
				var trackScrollInc;
				var trackScrollMousePos;
				var doTrackScroll = function()
				{
					if (trackScrollInc > 8 || trackScrollInc%4==0) {
						positionDrag((dragPosition - ((dragPosition - trackScrollMousePos) / 2)));
					}
					trackScrollInc ++;
				};
				var onStopTrackClick = function()
				{
					clearInterval(trackScrollInterval);
					$('html').unbind('mouseup', onStopTrackClick).unbind('mousemove', onTrackMouseMove);
				};
				var onTrackMouseMove = function(event)
				{
					trackScrollMousePos = getPos(event, 'Y') - currentOffset.top - dragMiddle;
				};
				var onTrackClick = function(event)
				{
					initDrag();
					onTrackMouseMove(event);
					trackScrollInc = 0;
					$('html').bind('mouseup', onStopTrackClick).bind('mousemove', onTrackMouseMove);
					trackScrollInterval = setInterval(doTrackScroll, 100);
					doTrackScroll();
				};

				$track.bind('mousedown', onTrackClick);

				$container.bind(
					'mousewheel',
					function (event, delta) {
						initDrag();
						ceaseAnimation();
						var d = dragPosition;
						positionDrag(dragPosition - delta * mouseWheelMultiplier);
						var dragOccured = d != dragPosition;
						return !dragOccured;
					}
				);

				var _animateToPosition;
				var _animateToInterval;
				function animateToPosition()
				{
					var diff = (_animateToPosition - dragPosition) / settings.animateStep;
					if (diff > 1 || diff < -1) {
						positionDrag(dragPosition + diff);
					} else {
						positionDrag(_animateToPosition);
						ceaseAnimation();
					}
				}
				var ceaseAnimation = function()
				{
					if (_animateToInterval) {
						clearInterval(_animateToInterval);
						delete _animateToPosition;
					}
				};
				var scrollTo = function(pos, preventAni)
				{
					if (typeof pos == "string") {
						$e = $(pos, $this);
						if (!$e.length) return;
						pos = $e.offset().top - $this.offset().top;
					}
					$container.scrollTop(0);
					ceaseAnimation();
					var destDragPosition = -pos/(paneHeight-contentHeight) * maxY;
					if (preventAni || !settings.animateTo) {
						positionDrag(destDragPosition);
					} else {
						_animateToPosition = destDragPosition;
						_animateToInterval = setInterval(animateToPosition, settings.animateInterval);
					}
				};
				$this[0].scrollTo = scrollTo;

				$this[0].scrollBy = function(delta)
				{
					var currentPos = -parseInt($pane.css('top')) || 0;
					scrollTo(currentPos + delta);
				};

				initDrag();

				scrollTo(-currentScrollPosition, true);

				// Deal with it when the user tabs to a link or form element within this scrollpane
				$('*', this).bind(
					'focus',
					function(event)
					{
						var $e = $(this);

						// loop through parents adding the offset top of any elements that are relatively positioned between
						// the focused element and the jScrollPaneContainer so we can get the true distance from the top
						// of the focused element to the top of the scrollpane...
						var eleTop = 0;

						while ($e[0] != $this[0]) {
							eleTop += $e.position().top;
							$e = $e.offsetParent();
						}

						var viewportTop = -parseInt($pane.css('top')) || 0;
						var maxVisibleEleTop = viewportTop + paneHeight;
						var eleInView = eleTop > viewportTop && eleTop < maxVisibleEleTop;
						if (!eleInView) {
							var destPos = eleTop - settings.scrollbarMargin;
							if (eleTop > viewportTop) { // element is below viewport - scroll so it is at bottom.
								destPos += $(this).height() + 15 + settings.scrollbarMargin - paneHeight;
							}
							scrollTo(destPos);
						}
					}
				)


				if (location.hash) {
					scrollTo(location.hash);
				}

				// use event delegation to listen for all clicks on links and hijack them if they are links to
				// anchors within our content...
				$(document).bind(
					'click',
					function(e)
					{
						$target = $(e.target);
						if ($target.is('a')) {
							var h = $target.attr('href');
							if (h.substr(0, 1) == '#') {
								scrollTo(h);
							}
						}
					}
				);

				$.jScrollPane.active.push($this[0]);

			} else {
				$this.css(
					{
						'height':paneHeight+'px',
						'width':paneWidth-this.originalSidePaddingTotal+'px',
						'padding':this.originalPadding
					}
				);
				// remove from active list?
				$this.parent().unbind('mousewheel');
			}

		}
	)
};

$.fn.jScrollPane.defaults = {
	scrollbarWidth : 10,
	scrollbarMargin : 5,
	wheelSpeed : 18,
	showArrows : false,
	arrowSize : 0,
	animateTo : false,
	dragMinHeight : 1,
	dragMaxHeight : 99999,
	animateInterval : 100,
	animateStep: 3,
	maintainPosition: true,
	scrollbarOnLeft: false,
	reinitialiseOnImageLoad: false
};

// clean up the scrollTo expandos
$(window)
	.bind('unload', function() {
		var els = $.jScrollPane.active;
		for (var i=0; i<els.length; i++) {
			els[i].scrollTo = els[i].scrollBy = null;
		}
	}
);

})(jQuery);


/* Copyright (c) 2006 Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 *
 * $LastChangedDate: 2007-12-20 09:02:08 -0600 (Thu, 20 Dec 2007) $
 * $Rev: 4265 $
 *
 * Version: 3.0
 *
 * Requires: $ 1.2.2+
 */

(function($) {

$.event.special.mousewheel = {
	setup: function() {
		var handler = $.event.special.mousewheel.handler;

		// Fix pageX, pageY, clientX and clientY for mozilla
		if ( $.browser.mozilla )
			$(this).bind('mousemove.mousewheel', function(event) {
				$.data(this, 'mwcursorposdata', {
					pageX: event.pageX,
					pageY: event.pageY,
					clientX: event.clientX,
					clientY: event.clientY
				});
			});

		if ( this.addEventListener )
			this.addEventListener( ($.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel'), handler, false);
		else
			this.onmousewheel = handler;
	},

	teardown: function() {
		var handler = $.event.special.mousewheel.handler;

		$(this).unbind('mousemove.mousewheel');

		if ( this.removeEventListener )
			this.removeEventListener( ($.browser.mozilla ? 'DOMMouseScroll' : 'mousewheel'), handler, false);
		else
			this.onmousewheel = function(){};

		$.removeData(this, 'mwcursorposdata');
	},

	handler: function(event) {
		var args = Array.prototype.slice.call( arguments, 1 );

		event = $.event.fix(event || window.event);
		// Get correct pageX, pageY, clientX and clientY for mozilla
		$.extend( event, $.data(this, 'mwcursorposdata') || {} );
		var delta = 0, returnValue = true;

		if ( event.wheelDelta ) delta = event.wheelDelta/120;
		if ( event.detail     ) delta = -event.detail/3;
//		if ( $.browser.opera  ) delta = -event.wheelDelta;

		event.data  = event.data || {};
		event.type  = "mousewheel";

		// Add delta to the front of the arguments
		args.unshift(delta);
		// Add event to the front of the arguments
		args.unshift(event);

		return $.event.handle.apply(this, args);
	}
};

$.fn.extend({
	mousewheel: function(fn) {
		return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel");
	},

	unmousewheel: function(fn) {
		return this.unbind("mousewheel", fn);
	}
});

})(jQuery);


$(document).ready(function(){
    $("div.lastchild div:last-child").css('margin-right', '0');
    $("div.archive-sidebar ul li:not(:last-child)").css('border-right', '1px solid #c7c3b4');
    $('.scroll-pane').jScrollPane({showArrows:true, scrollbarWidth: 12});
    $('.mostcomments div.labels ul').tabify();
    $("#kolumne-section div.block-head-a6:first").css('background', 'none');
    $("#komentari-section div.block-head-a6:first").css('background', 'none');
    $("div.dionice table tr:not(:last-child)").css('background', 'url(template/images/dot.gif) bottom repeat-x');
    $("div.horoskop-box-select li:not(:last-child)").css('background', 'url(template/images/dot.gif) bottom repeat-x');
    $('div.horoskop-box-select ul').tabify();
    $('#najcitanije-large div.labels ul').tabify();
    $('#najcitanije-footer div.labels ul').tabify();
    $('#najcitanije-sidebar div.labels ul').tabify();
    $('#sectionmore div.labels ul').tabify();
    $('div.weather-header ul').tabify();
    $('div.weathermap ul').tabify();
    $('#horoskop .tabbar ul').tabify();
    $('#weather .tabbar ul').tabify();
    $('#fotovideo div.tabs ul').tabify();
    $("div.topics li:not(:first-child)").prepend("&nbsp;|&nbsp;");
    $("#ticker-naslovnica-content").newsticker(6000);
    $("#ticker-content").newsticker(6000);
    $('#showall a').click(function() { $('#allcomments').toggle(); return false; });
  	$(".carousel").jCarouselLite({btnNext: ".next", btnPrev: ".prev", visible: 4, scroll: 4, speed: 1500});
  	$("#fotovideo #foto").jArticleGallery({btnNext: ".next", btnPrev: ".prev", visible: 1, scroll: 1, speed: 300});
    $(".querystring input").defaultvalue("Pretraži Jutarnji.hr");
    $("#osobetjedna-link").colorbox({fixedWidth:"530px", fixedHeight:"420px", iframe:true});
    $("div.tools li.mail a").colorbox({fixedWidth:"365px", fixedHeight:"390px", iframe:true});
    $("div.tools li.contribute a").colorbox({fixedWidth:"365px", fixedHeight:"495px", iframe:true});
    $("a.complain").colorbox({fixedWidth:"385px", fixedHeight:"495px", iframe:true});
    $("#impressum a.contentbox").colorbox({fixedWidth:"528px", fixedHeight:"430px", iframe:true});
    $("#yourcomment a.contentbox").colorbox({fixedWidth:"528px", fixedHeight:"430px", iframe:true});
    $($.date_input.initialize);
});

//Provide a default path to dwr.engine
if (typeof this['dwr'] == 'undefined') this.dwr = {};
if (typeof dwr['engine'] == 'undefined') dwr.engine = {};
if (typeof dwr.engine['_mappedClasses'] == 'undefined') dwr.engine._mappedClasses = {};

if (window['dojo']) dojo.provide('dwr.interface.EphSubmitVoteAjax');

if (typeof this['EphSubmitVoteAjax'] == 'undefined') EphSubmitVoteAjax = {};

EphSubmitVoteAjax._path = '/dwr';

EphSubmitVoteAjax.submitVote = function(p0, p1, p2, callback) {
  return dwr.engine._execute(EphSubmitVoteAjax._path, 'EphSubmitVoteAjax', 'submitVote', arguments);
};

if (window['dojo']) dojo.provide('dwr.interface.EphSubmitFlaggingAjax');

if (typeof this['EphSubmitFlaggingAjax'] == 'undefined') EphSubmitFlaggingAjax = {};

EphSubmitFlaggingAjax._path = '/dwr';

EphSubmitFlaggingAjax.submitFlag = function(p0, p1, callback) {
  return dwr.engine._execute(EphSubmitFlaggingAjax._path, 'EphSubmitFlaggingAjax', 'submitFlag', arguments);
};

if (window['dojo']) dojo.provide('dwr.interface.GetForecastAjax');

if (typeof this['GetForecastAjax'] == 'undefined') GetForecastAjax = {};

GetForecastAjax._path = '/dwr';

GetForecastAjax.getForecast = function(p0, p1, callback) {
  return dwr.engine._execute(GetForecastAjax._path, 'GetForecastAjax', 'getForecast', arguments);
};

function getForecast (url, city, secUrl) {
	var cityName = $(city).html();
	city = $(city).val();
	GetForecastAjax.getForecast(url, city, {
						callback:function(str) {
							$("#weather_r").html(str);
							$("#vremenska_url").attr("href", secUrl + city + "/danas");
						}
					});
}

//track outgoing links
//v1; 15.12.2009.
$(document).ready(function() {
   $("a[href^='http://']:not([href^='http://www.jutarnji.hr/']):not(.noOutgoing)").addClass("outgoing").attr('target', '_blank').bind('click keypress', function(event) {
     var code = event.charCode || event.keyCode;
     if(!code || (code && code == 13)) {
       var fixedLink = this.href;
       fixedLink = '/outgoing/' + fixedLink.replace(/https?:\/\/(.*)/,"$1");
       if(jutarnjinovi) {
         jutarnjinovi._trackPageview(fixedLink);
       };
       if(jutarnjistari) {
         jutarnjistari._trackPageview(fixedLink);
       };
     };
});
});

//Copyright (c) 2006 Klaus Hartl (stilbuero.de)
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

// Copyright (c) 2010 JL & WT
function smartRefresh(seconds, times) {
  setTimeout('tryRefresh(' + times + ')', seconds * 1000);
}
function tryRefresh(times) {
  if (location.href.indexOf('refresh=1') != -1 && $.cookie('refresh') != null) {
    if (parseInt($.cookie('refresh')) < times) {
      $.cookie('refresh', parseInt($.cookie('refresh')) + 1);
      location.href = location.href;
    }
  } else {
    $.cookie('refresh', 1);
    if (location.href.indexOf('?') != -1) {
      location.href = location.href + '&refresh=1';
    } else {
      location.href = location.href + '?refresh=1';
    }
  }
}

function track_img(sljed) {
	var pathname = location.pathname;
	if (pathname.charAt(pathname.length-1) != '/') {
	  pathname += '/';
	}
	if (sljed) {
	  pathname += 'sljedeca/';
	} else {
	  pathname += 'prethodna/';
	}
	 
	if(jutarnjinovi) {
	  jutarnjinovi._trackPageview(pathname);
	};
	if(jutarnjistari) {
	  jutarnjistari._trackPageview(pathname);
	};
	
	var d = document;
	var href = new String(d.location.href);
	if (sljed) {
		if (href.charAt(href.length - 1) == '/') {
			href = href +  "sljedeca/";
		} else {
			href = href +  "/sljedeca/";
		}
	} else {
		if (href.charAt(href.length - 1) == '/') {
			href = href +  "prethodna/";
		} else {
			href = href +  "/prethodna/";
		}
	}
		        
	var ref;
	var f=0;
	var fv='-';
	if (d.referrer) { ref=new String(d.referrer); } else { ref=''; }
	if (typeof Error!='undefined') {
    	var fo;
    	eval('try { f=(d==top.document)?1:2; if (typeof top.document.referrer=="string") { ref=top.document.referrer } } catch(e) {f=3;}');
    	eval('try { fv=navigator.plugins["Shockwave Flash"].description; } catch (e) {}');
    	eval('if (typeof ActiveXObject!="undefined") { try { fo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7"); } catch(e) { try { fo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6"); fv="X"; fo.AllowScriptAccess="always"; } catch(e) { if (fv=="X") { fv="WIN 6,0,20,0"; }} try { fo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash"); } catch(e) {} } if ((fv=="-" || fv=="X") && fo) { fv=fo.GetVariable("$version"); }}');
	}
	var url='&fr='+f+'&fv='+escape(fv)+'&tz='+(new Date()).getTimezoneOffset()+'&href='+escape(href.substring(0,499))+'&ref='+escape(ref.substring(0,499));
	if (screen) {
    	var s=screen;
    	if (s.width) url+='&screen='+s.width+'x'+s.height;
    	if (s.colorDepth) url+='&col='+s.colorDepth;
	}
	
	$(document.createElement("img")).attr({ "src": pp_gemius_host+(new Date()).getTime()+'/rexdot.gif?l=30&id='+pp_gemius_identifier+url }).appendTo($(document.body));	

	return true;
}
