/** INIT VARS **/
var hasLoadedNews = false;
var ajaxNewsUrl = "/4.67e664aa127613c40188000161.Alla.portlet";
var newsShowItem = 0;
var eventListHeight = "53em";
var exhibitionListHeight = "26em";
var eventListMaxHeight = 0;
var exhibitionListMaxHeight = 0;
var crossListHeight = "42em";
var ajaxLoaderSrc = "http://www.orebrotown.com/images/18.21e42e761278b4edfbe800055/ajax-loader_big.gif";
var ajaxLoader = new Image();
ajaxLoader.src = ajaxLoaderSrc;
var $ajaxLoader = $("<div/>").css("text-align","center").css("margin-top","2em").append(ajaxLoader);
var cookie_options = { path: '/', expires: 10000 };
/***********/

/**/
var simgsrc = "http://www.orebrotown.com/images/18.4aac857127c13f212980001933/searchtop_bg-active.png";
var simg = new Image();
simg.src = simgsrc;

var daterange = [];
var months = new Array('januari','februari','mars','april','maj','juni','juli','augusti','september','oktober','november','december');
var d = new Date();

for(var i=0;i<=150;i++)
{
	var d_string = d.getFullYear() +"-"+ (((d.getMonth()) < 10) ? "0"+ (d.getMonth()) : (d.getMonth())) +"-"+ (((d.getDate()+1) < 10) ? "0"+ (d.getDate()) : (d.getDate()));
	d.setDate(d.getDate()+1);
	daterange.push(d_string);
}

var sliderOptions = {
	animate: true,
	step: 1,
	min: 0,
	orientation: 'horizontal',
	max: daterange.length-1,
	range: true,
	slide: function(e, ui){ // while sliding
		var textval = daterange[(ui.value)];
		
		var ddate = new Date(textval.substring(0,4), textval.substring(5,7), textval.substring(8,10));
		var localdate = ddate.getDate() +" "+ months[ddate.getMonth()];
		
		$(ui.handle)
			.find('.ui-slider-tooltip .ttContent')
			.text( localdate );
		},
	stop: function(e, ui) { // stop function
		var $handle = $(ui.handle);
		var currSelect = $handle.attr('id').split('handle_')[1];
		
		//$("div.cal_events_list").html($ajaxLoader);
		
		if(currSelect == 0) $currSelect = $("select#fromDate");
		else $currSelect = $("select#toDate");
		
		$currSelect.find('option').eq(ui.value).attr('selected', 'selected');
		
		searchEventStartList();
		
		// Make nice dates for display
		var fromdatenice = gimmeNiceDate($("select#fromDate option:selected").val());
		var todatenice = gimmeNiceDate($("select#toDate option:selected").val());
		
		$("#displayFromDate").html(fromdatenice);
		$("#displayToDate").html(todatenice);
		
	},
	start: function(e, ui){
	},
	values: [0,30]
};

function loadNews(dir)
{
	if(!hasLoadedNews)
	{
		$.get(ajaxNewsUrl, function(callback){
			$holder = $("#newsHolder");
			
			$("#newsHolder > li", callback).each(function(){
				$holder.append(this);
				//console.log(this);
			});
			//$("div.news_firstpage").html(callback);
			hasLoadedNews = true;
			scrollNews(dir);
		});
	}
	else
	{
		scrollNews(dir);
	}
}

function scrollNews(dir)
{
	if(dir == "right")
		newsShowItem = newsShowItem + 3;
	else
		newsShowItem = newsShowItem - 3;
		
	if(newsShowItem <= 0) newsShowItem = 0;
	if(newsShowItem >= $("ul#newsHolder > li").length) newsShowItem = 0;

	var $target = $("div.news_firstpage").find('li:eq('+ newsShowItem +')');
	$("div.firstpage_news_holder").scrollTo($target, 1000, { axis: 'x' });
}

function searchEventStartList()
{
	var $typefilter = $("#typelist");
	$typefilter.val("");
	$(".str-checkboxes form input.cbTypes:checked").each(function(){
		$typefilter.val($typefilter.val() + "," + $(this).val());
	});
		
	var $cityfilter = $("#citylist");
	$cityfilter.val("");
	$(".str-checkboxes form input.cbCities:checked").each(function(){
		$cityfilter.val($cityfilter.val() + "," + $(this).val());
	});
	
	$.cookie("typefilter", $typefilter.val(), cookie_options);
	$.cookie("cityfilter", $cityfilter.val(), cookie_options);
	$.cookie("dateFrom", $("#dateFrom").val(), cookie_options);
	$.cookie("dateTo", $("#dateTo").val(), cookie_options);
			
	$("form input[type='submit']").attr("disabled","disabled");
	$("div.cal_events_list").html($ajaxLoader);
	$("div.cal_events_list_exhibitions").html("");
		
	if($("form#search_slider_firstpage").is("*"))
		$form = $("form#search_slider_firstpage");
	else
		$form = $("form#slider_search");
			
	var search = $form.serialize();
	
	// Get events
	$.get("/4.67e664aa127613c40188000133.Eventlist.portlet", search, function(callback){
		$("div.cal_events_list").html(callback);
		$("div.cal_events_list").animate({ height: eventListHeight }, 500);
			
		var lenDiv = $("div.cal_events_list div.calendarItem").length;
			
		if(lenDiv > 6)
			$("div.cal_events_btn").show();
		else
			$("div.cal_events_btn").hide();
				
		Cufon.refresh();
			
		eventListMaxHeight = Math.round((240 * lenDiv) / 3) + Math.round((20 * lenDiv) / 3);
		
		$("form input[type='submit']").removeAttr("disabled");
	});
	// Get exhibitions
	$.get("/4.67e664aa127613c40188000133.Exhibitions.portlet?utstallningar=1", search, function(callback){
		$("div.cal_events_list_exhibitions").html(callback);
		$("div.cal_events_list_exhibitions").animate({ height: exhibitionListHeight }, 500);
		
		var lenDiv = $("div.cal_events_list_exhibitions div.calendarItem").length;
		
		if(lenDiv > 3)
			$("div.cal_exhibitions_btn").show();
		else
			$("div.cal_exhibitions_btn").hide();
		
		Cufon.refresh();

		exhibitionListMaxHeight = Math.round((240 * lenDiv) / 3) + Math.round((20 * lenDiv) / 3);
	});
}

function searchInTheme()
{
	var url = "/4.6fb2ee80128fda884ff80001632.Tema.portlet";
	$("#themeresults").html($ajaxLoader);
	
	var frm = $("#themeform");
	var vals = frm.serialize();
	
	$.get(url, vals, function(callback){
		$("#themeresults").html(callback);
	});
}

function loadCookieForm()
{
	var $c = $.cookie("typefilter");
	var $cf = $.cookie("cityfilter");
	var $fDate = $.cookie("dateFrom");
	var $tDate = $.cookie("dateTo");
	
	if($c.length > 2)
	{
		$("#str-start-checkboxes").show();
		
		$(".type_choice input").each(function(){
			if($c.indexOf($(this).val()) > 0)
				$(this).attr("checked","checked");
			else
				$(this).attr("checked","");
		});
	}
	if($cf.length > 2)
	{
		$("#str-start-checkboxes").show();
		
		$(".city_choice input").each(function(){
			if($cf.indexOf($(this).val()) > 0)
				$(this).attr("checked","checked");
			else
				$(this).attr("checked","");
		});	
	}
	
	if($fDate && $fDate.length > 0)
		$("#dateFrom").val($fDate);
	if($tDate && $tDate.length > 0)
		$("#dateTo").val($tDate);
		
	searchEventStartList();
}

/**
	Loads a form. Add an IF if you want it to work in another way
**/
function loadFilterForm(e)
{
	$target = $(e.target);
	$parentform = $target.parents("form");

	// Check to see if its "event" list
	if($parentform.attr("id") == "slider_search")
	{
		var $typefilter = $("#typelist");
		$typefilter.val("");
		$(".str-checkboxes form input.cbTypes:checked").each(function(){
			$typefilter.val($typefilter.val() + "," + $(this).val());
		});
		
		/*$.cookie("typefilter", $typefilter.val(), cookie_options);
		$.cookie("dateFrom", $("#dateFrom").val(), cookie_options);
		$.cookie("dateTo", $("#dateTo").val(), cookie_options);*/
		
		var $cityfilter = $("#citylist");
		$cityfilter.val("");
		$(".str-checkboxes form input.cbCities:checked").each(function(){
			$cityfilter.val($cityfilter.val() + "," + $(this).val());
		});
		
		searchEventStartList();
	}
	else if($parentform.attr("id") == "themeform")
	{
		var $typefilter = $("#typelist");
		$typefilter.val("");
		$(".str-checkboxes form input.cbTypes:checked").each(function(){
			$typefilter.val($typefilter.val() + "," + $(this).val());
		});
		
		searchInTheme();
	}
	else
	{
		$("div.crossnav_holder").html($ajaxLoader).animate({ height: crossListHeight }, 500);
		
		var $typefilter = $("#typelist");
		$typefilter.val("");
		$(".str-checkboxes form input:checked").each(function(){
			$typefilter.val($typefilter.val() + "," + $(this).val());
		});
		
		var zeForm = { typelist: $typefilter.val(), query: $(".str-type-searcher-buttons input[name='query']").val(), startnode: $("input[name='startnode']").val() }
	
		$.get("/svenska/ajax/korsnavigeringlandningssida.4.736ba213127e1c00d2980003025.Mittenspalt.portlet", zeForm, function(callback){
			$(".crossnav_holder").html(callback);
	
			var totalItems = $(".crossnav_holder .calendarItem").length;
	
			if(totalItems > 8)
			{
				$(".crossnav_showmore").fadeIn("slow");	
			}
			else
			{
				$(".crossnav_showmore").fadeOut("slow");
			}
			Cufon.refresh();
		});
	}
}

/*
	Gimme XXXX-XX-XX and i'll return XX MONTH
*/
function gimmeNiceDate(d)
{
	var ddate = new Date(d.substring(0,4), (d.substring(5,7)-1), d.substring(8,10));
	var localdate = ddate.getDate() +" "+ months[ddate.getMonth()];	
	
	return localdate;
}

/*
*	Function for automagically set dates
*/
function setEventDate(e)
{
	switch(e)
	{
		case 'today':
			$("#fromDate option:selected").removeAttr("selected");
			$("#toDate option:selected").removeAttr("selected");
			$("#fromDate option:nth-child(1)").attr("selected","selected");
			$("#toDate option:nth-child(1)").attr("selected","selected");			
		break;
		default:
		break;
	}
}






$(function(){
	var zIndexNumber = 1000;
	$('.topWrapper div').each(function() {
		$(this).css('zIndex', zIndexNumber);
		zIndexNumber += 10;
	});

	// Tabs
	$('div.tab-container').svInitTab();

	/** DATE PICKER RANGE SLIDER **/
	// Hide slider
	$("form#search_slider_firstpage").hide();
	$//("form#slider_search #slider_search_content").hide();
	
	$("form#slider_search").submit(function(){
		searchEventStartList();
		return false;
	});
	
	$("#slide_search_details").show();
	$("#slide_search_details a").click(function(){
		var $checks = $("#str-start-checkboxes");
		if($checks.is(":visible"))
		{
			$checks.slideUp("slow");
			$(this).removeClass("active");
		}
		else
		{
			$checks.slideDown("slow");
			$(this).addClass("active");
		}
	});
	
	var $slideComponent = $("div#eventdaterangeslider");

	var ddate = new Date(daterange[0].substring(0,4), daterange[0].substring(5,7), daterange[0].substring(8,10));
	var firstdate = ddate.getDate() +" "+ months[ddate.getMonth()];
	
	var ddate = new Date(daterange[30].substring(0,4), daterange[30].substring(5,7), daterange[30].substring(8,10));
	var seconddate = ddate.getDate() +" "+ months[ddate.getMonth()];

	$('<a '+
		'href="#" tabindex="0" ' +
		'id="handle_0" '+
		'class="ui-slider-handle" '+
		'role="slider"> '+
		'<span class="ui-slider-tooltip ui-widget-content ui-corner-all">'+
		'<span class="ttContent">'+ firstdate +'</span>'+
		'</span></a>').appendTo($slideComponent);
			
	$('<a '+
		'href="#" tabindex="0" '+
		'id="handle_1" '+
		'class="ui-slider-handle" '+
		'role="slider"> '+
		'<span class="ui-slider-tooltip ui-widget-content ui-corner-all"><span class="ttContent">'+ seconddate +'</span>'+
		'</span></a>').appendTo($slideComponent);
	
	$("#displayFromDate").html(firstdate);
	$("#displayToDate").html(seconddate);
	
	$slideComponent
		.slider(sliderOptions);
		
	var lenDiv = $("div.cal_events_list div.calendarItem").length;
	if(window.location.pathname.indexOf("uppleva") > 0)
		eventListMaxHeight = Math.round((240 * lenDiv) / 4) + Math.round((20 * lenDiv) / 4);
	else
		eventListMaxHeight = Math.round((240 * lenDiv) / 3) + Math.round((20 * lenDiv) / 3);

//	console.log(window.location.pathname.indexOf("uppleva"))
	$("div.cal_events_btn").click(function(){
		var divh = $("div.cal_events_list div.calendarItem:first").height();
		var holderh = $("div.cal_events_list").height();
		var newheight = holderh + divh + 20;
		
		$("div.cal_events_list").animate({ height: newheight + "px" }, 1500);
		
		//$.scrollTo($(this),1500, { offset: -(divh), easing: "easeOutQuad" });
		if(newheight >= eventListMaxHeight)
		{
			$(this).fadeOut("fast");
			
			if($("input[name='numhits']").val() > 24)
			{
				var eventuri = "/sv/uppleva/evenemang.html?dateFrom="+ $("#dateFrom").val() +"&dateTo="+ $("#dateTo").val();
				$("div.more_hits a").attr("href", eventuri);
				$("div.more_hits").show();
			}
		}
	}).show();
	
	$("div.cal_exhibitions_btn").click(function(){
		var divh = $("div.cal_events_list_exhibitions div.calendarItem:first").height();
		var holderh = $("div.cal_events_list_exhibitions").height();
		var newheight = holderh + divh + 20;
		
		$("div.cal_events_list_exhibitions").animate({ height: newheight + "px" }, 1500);
		
		//$.scrollTo($(this),1500, { offset: -(divh), easing: "easeOutQuad" });
		if(newheight >= exhibitionListMaxHeight) $(this).fadeOut("fast");
	}).show();
	
	/** NEWS **/	
	$("div.news_nav_right > img").click(function(){
		loadNews("right");
	});
	$("div.news_nav_left > img").click(function(){
		loadNews("left");
	});
	
	/** MENU **/
	$("#headnavigation > ul > li").mouseenter(function(e){
		var $clicked = $(this);
		$(".activemenu").hide();
		$(".activemenu", this).show();
	});
	$(".activemenu").mouseenter(function(){
		$(this).show();
	});
	
	// Document Bind Click
	$(document).click(function(){ 
		$(".activemenu").hide(); 
	});
	
	/** EVENT LIST **/
	eventListHeight = $("div.cal_events_list").height();
	
	/** COMMENTS **/
	$("div.comment_headline").click(function(){
		$("div#disqus_thread").slideDown("slow", function(){
			$.scrollTo($("div.comment_headline"), 1500, {  });
		});
	}).css("cursor","pointer");
	
	/** SEARCH **/
	$("#topsearch input[name='query']").autocomplete({
			source: "/4.429a211d12784c58786800028/12.429a211d12784c58786800034.portlet",
			minLength: 2,
			zIndex: 2000,
			select: function(event, ui) {
			  document.location = ui.item.id;
				//Do something  - log(ui.item ? ("Selected: " + ui.item.value + " aka " + ui.item.id) : "Nothing selected, input was " + this.value);
				//var id = ui.item.id;
			},
			open: function(e){
				$(e.target).parent("div").addClass("searchactive-open");
			},
			close: function(e){
				$(e.target).parent("div").removeClass("searchactive-open");
			}
			
		});
	
	$("#topsearch input[name='query']")
		.focus(function(){
			$(this).parent("div").addClass("searchactive");
		})
		.blur(function(){
			$(this).parent("div").removeClass("searchactive");
		});
	
	/** PAKET **/	
	var num_packages = $(".package").length;
	if(num_packages > 4)
	{
		var max_rows = num_packages / 2;
		
		$(".package_showmore")
			.click(function(){
				var $list = $("#listningavpaket").parent();
				var item_height = $(".package:first", $list).height();
				var $btn = $(this);
				
				$list.animate({ "height": "+="+ item_height +"px" }, "slow", function(){
					if($list.css("height").replace("px","") >= (item_height * max_rows))
					{
						$btn.fadeOut("fast");
					}
				});

			})
			.show();
	}
	
	/** CHECKBOXES n CROSS-NAV **/
/*	if($.cookie('typefilter') != null)
	{
		$(".str-checkboxes input[type='checkbox']").attr("checked", "");
	}*/
	
	$(".str-checkboxes input[type='checkbox']")
		.checkbox({ empty: 'http://www.strategportalen.com/extern/orebrotown/js/jquery.checkbox/empty.png' });
		//.bind('check', loadFilterForm)
		//.bind('uncheck', loadFilterForm);
	
	$(".str-types input[type='checkbox'], .str-subcats input[type='checkbox']")
		.bind('check', loadFilterForm)
		.bind('uncheck', loadFilterForm);
	
/*	$(".str-checkboxes .type_choice input[type='checkbox']")
		.each(function(){
			console.log($(this).is(".str-checkboxes .type_choice input[type='checkbox']:last"));
		});*/
	
	$(".crossnav_showmore").click(function(){
		var divh = $("div.crossnav_holder div.calendarItem:first").height();
		var holderh = $("div.crossnav_holder").height();
		var newheight = holderh + divh + 20;
		var crossnavMaxHeight = divh * ($("div.crossnav_holder div.calendarItem").length / 4);

		$("div.crossnav_holder").animate({ height: newheight + "px" }, 1500);
		
		//$.scrollTo($(this),1500, { offset: -(divh) });
		if(newheight >= crossnavMaxHeight)
			$(this).fadeOut("slow");
	});
	
	var totalItemsInCross = $(".crossnav_holder .calendarItem").length;

	if(totalItemsInCross > 8)
		$(".crossnav_showmore").fadeIn("slow");	
	
	$(".str-type-searcher-buttons input[type='submit']").hide();
	
	var search_t;
	$(".str-type-searcher-buttons input").keyup(function(){
		clearTimeout(search_t);
		search_t = setTimeout("loadFilterForm(this)", 300);
	});
	
});
