/*** GLOBAL HELPERS ***/

Array.prototype.in_array = function(p_val) {
	for(var i = 0, l = this.length; i < l; i++) if(this[i] == p_val) return true;
	return false;
}

// define easing functions
$.easing.easeInOutExpo = function (x, t, b, c, d) {
	if (t==0) return b;
	if (t==d) return b+c;
	if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
	return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
}

var im;

informedia = function() {
	var im = this; // for use in events
	var ajax_url;
	
	// variables
	im.loading_news_item = false;
	im.current_news_items = new Array(0, 1);
	
	//animation
	im.default_animation_duration = 600;
	
	
	// html
	im.html_loader = '<div class="loader"><img alt="" src="' + baseurl + '/wp-content/themes/informedia/images/loading.gif"/>'+ if_loading +'</div>';
	
	
	/*** INIT CONSTRUCT ***/
	
	im.construct = function() {
		im.ajax_url = baseurl + '/wp-content/plugins/informedia/ajax.php';
		
		// Initialize history plugin.
		// The callback is called at once by present location.hash. 
		$.historyInit(im.pageload);
		
		// initalize onclick event for history buttons
		im.click_history_button();
		
		// toggle sections on the site
		$('.block-header').click(function() {
			$(this).next().toggleClass('hidden');

			if(!$(this).next().hasClass('hidden'))
				$(this).removeClass('collapsed');
			else
				$(this).addClass('collapsed');
		});
		
		$('.news-list').hover(function() {
			$(this).addClass('hover');
		}, function() {
			$(this).removeClass('hover');
		});
		
		// load news on click
		$('#news-list-prev').click(function() {
			im.load_news('prev');
		});
		
		$('#news-list-next').click(function() {
			im.load_news('next');
		});
		
		check_for_object();
		
		// johannes
		
		$(".expand-panel").toggle(function(){
			$(this).parent().find('.expand-arrow').addClass("expanded");
			}, function () {
			$(this).parent().find('.expand-arrow').removeClass("expanded");
		});
		
		$('.expand-panel').click(function(e){
			e.preventDefault();
			$(this).parent().find('.slide-entry').slideToggle();		
		});

		$('.contact-link').click(function(e){
			e.preventDefault();
			$('.contact-entry').hide();
			$(this).prev().slideToggle('fast');		
		});	
		
		$('.close-button').click(function(e){
			e.preventDefault();
			$(this).parent().slideToggle('fast');		
		});
		
		$('#content-panel p:has(img.alignright)').addClass('has-image');
		
		$.post(im.ajax_url, {'blogid': blogid, 'action': 'get_twitter'}, function(data, status) {
			if(status != "success") {
				alert('Failed!');
				return;
			}
			
			// clear twitter tag
			$('#twitter li.loader').remove();
			
			for (var i = 0; data.length > i; i++) {
				var last = (i == data.length-1) ? ' class="last"' : '';
				$('#twitter').append('<li' + last + '>' + data[i].user.name_link + ': ' + data[i].text + '<div class="date">' + data[i].created_at + '</div></li>');
			}
			
		}, "json");
		
		// Click on case customer item
		$("#cases div.customers ol li").click(function () {
			
			//Remove active customer
			$("#cases div.customers ol li.active").removeClass('active');
			
			//Set this customer to active
			$(this).addClass('active');
			
			//If a case is displayed
			if ($("#case-main").css('display') == 'block') {
				// hide case-main
				$("#case-main").css('overflow', 'hidden').animate({
					height: 0
				}, im.default_animation_duration, "easeInOutExpo", function () {
						$(this).hide().html('').css({'overflow': '', 'height': ''});
					}
				);
			}
			
			// create loader
			$("#cases div.case-list").html(im.html_loader);
			
			im.load_case_list($(this).find('a:first').attr('href').split('#')[1]);
			
			return false;
		});
	}
	
	
	/*** PAGE LOAD ***/
	
	// This function is called:
	// 1. after calling $.historyInit();
	// 2. after calling $.historyLoad();
	// 3. after pushing "Go Back" button of a browser
	im.pageload = function(hash) {
		if(hash) {
			var ahash = hash.split(/\//);
			switch (ahash[0]) {
				case "case":
					if (!$('#cases').hasClass("hidden"))
						im.load_case_list_item(ahash[1]);
					break;
				case "news":
					im.load_main_article(ahash[1]);
					break;
			}
		} else {
			// start page
		}
	}
	
	
	/*** ONCLICK EVENTS ***/
	
	im.load_case_list_item = function (id) {
		
		im.load_case(id); //start loading case

		$("#cases .case-loader").height($("#case-main").height()).show(); // set height and show loader
		$("#case-main").hide();
		
		return false;
	}
	
	// onClick event function for history buttons
	im.click_history_button = function(jqHolderObject) {
		if (jqHolderObject) {
			jqHolderObject.find("a[rel='history']").click(im.history_button_function);
		}
		else {
			$("a[rel='history']").click(im.history_button_function);
		}
	}
	
	im.history_button_function = function() {
		var hash = this.href;
		hash = hash.replace(/^.*#/, '');
		$.historyLoad(hash);
		return false;
	}
	
	
	/*** LOAD DATA ***/
	
	im.load_case_list = function(id) {
		$.post(im.ajax_url, {'blogid': blogid, 'action': 'get_case_list', 'id': id}, function(data, status) {
			if(status != "success") {
				alert('Failed!');
				return;
			}
			
			$("#cases div.case-list").html(data);
			
			// reinitalize onclick event for history buttons
			im.click_history_button($('#cases div.case-list'));
			
		}, "json");
	}
	
	im.load_case = function(id) {
		$.post(im.ajax_url, {'blogid': blogid, 'action': 'get_post', 'id': id}, function(data, status) {
			if(status != "success") {
				alert('Failed!');
				return;
			}
			
			$("#case-main").html("<h1>" + data.post_title + "</h1>");
			$("#case-main").append(data.post_content);
			
			// Animate loader height
			$('#cases .case-loader').animate({
				height: parseInt($('#case-main').height()) + "px"
			}, im.default_animation_duration, "easeInOutExpo", function() {
				$("#cases .case-loader").hide();
				$('#case-main').fadeIn();
			});
			
			im.image_effects.process($('#case-main'));
			
			// Activate if holder already active
			if($('#cases').hasClass('image-effect-active'))
				im.image_effects.activate($('#case-main'));
			
		}, "json");
	}
	
	im.load_main_article = function(id) {
		
		// Set new loader height
		$('#content .news-loader').height($('#content .news-main').outerHeight());
		
		// Show loader
		$('#content .news-loader').show();
		$('#content .news-main').hide();
		
		// Start loading article
		$.post(im.ajax_url, {'blogid': blogid, 'action': 'get_post', 'id': id}, function(data, status) {
			if(status != "success") {
				alert('Failed!');
				return;
			}

			$('#current-news-main').val(data.ID);
			
			$('#content .news-main h1:first').html(data.post_title);
			$('#content .news-main div.article:first').html(data.post_content);
			
			// Animate loader height
			$('#content .news-loader').animate({
				height: parseInt($('#content .news-main').outerHeight()) + "px"
			}, im.default_animation_duration, "easeInOutExpo", function() {
				$('#content .news-loader').hide();
				$('#content .news-main').fadeIn();
			});
			
			check_for_object();
		}, "json");
		
		return false;
	}
	
	im.load_news = function(direction, load_one) {
		if(im.loading_news_item)
			return;
			
		if(!load_one)
			load_one = false;
		
		im.loading_news_item = true;
		
		if(typeof direction == "undefined" || direction != "next")
			direction = "prev";
		
		var width = $('.news-list .viewport .article:first').outerWidth();
		
		if(load_one) {
			$(load_one).find('.entry').fadeOut(
				im.default_animation_duration,
				function() {
					$(load_one).find('.inner-loader').show();
				}
			);
		}
		else {			
			if(direction == "prev") {
				width = 0 - width;
				$('.news-list .viewport .article.out').css('marginLeft', width);
				
				$('.news-list .viewport .article.out .entry').hide();
				$('.news-list .viewport .article.out .inner-loader').show();
				
				$('.news-list .viewport .article.in').removeClass('in');
				$('.news-list .viewport .article.out').addClass('in').removeClass('out');
				$(im.get_last_box()).addClass('out');
			}
			else {
				$('.news-list .viewport .article.out .entry').hide();
				$('.news-list .viewport .article.out .inner-loader').show();
				
				$('.news-list .viewport .article.in').removeClass('in');
				$('.news-list .viewport .article.out').addClass('in').removeClass('out');
				im.get_first_box().addClass('out');
			}
			
			var articles = $('.news-list .viewport .article');
			
			$(articles).each(function (key, item) {
				$(this).animate({
					marginLeft: parseInt($(this).css('marginLeft')) - width
				}, im.default_animation_duration, "easeInOutExpo", function() {
					// empty out
					$('.news-list .viewport .article.out').find('.entry .date, .entry .title, .entry .excerpt, .entry .image').html('');
					
					if(key == $(articles).length-1 && direction == "next") {
						$('.news-list .viewport .article.out').css('marginLeft', width * 2);
					}
				});
			});
		}
		
		/*console.log("Post attributes:");
		console.log('- blogid: '+ blogid);
		console.log('- current:'+ im.current_news_items.join(","));
		console.log('- direction: '+ direction);
		console.log('- skip_post: '+ $('#current-news-main').val());
		
		console.log("Posting...");*/
		// get news
		$.post(im.ajax_url, {'blogid': blogid, 'action': 'get_news', 'current': im.current_news_items.join(","), 'direction': direction, 'skip_post': $('#current-news-main').val()}, function(data, status) {
			
			//console.log(im.current_news_items);
			
			if(status != "success") {
				alert('Failed to load news.');
				return;
			}
			//console.log("Posted and recieved data successfully.");
			//console.log("News id: "+ data.post.id);
			if(load_one)
				var article = $(load_one);
			else
				var article = $('.news-list .viewport .article.in');
			
			$(article).find('.entry .date').html(data.post.post_date);
			$(article).find('.entry .title').html(data.post.post_title);
			$(article).find('.entry .excerpt').html(data.post.post_excerpt);
			
			$(article).find('.entry .read-more').attr({'href': data.post.the_permalink + '#news/' + data.post.ID});
			
			$(article).find('.entry').show();
			$(article).find('.inner-loader').hide();
			
			if(typeof data.image == "undefined") {
				$(article).find('.entry .image img').remove();
				
				im.current_news_items = data.current;
			}
			else {
				image(data.image, function(image) {
					$(article).find('.entry .image').html('<a rel="history" href="' + data.post.the_permalink + '#news/' + data.post.ID + '"><img src="' + image.src + '" alt="" /></a>');
					im.click_history_button($(article).find('.entry .image'));
					
					im.current_news_items = data.current;
				});
			}
			
			im.loading_news_item = false;
			
		}, "json");
	}
	
	
	/*** NEWS HELPERS ***/
	
	im.get_first_box = function() {
		var box;
		var box_margin = 100000;
		$('.news-list .viewport .article').each(function(key, item) {
			if(box_margin > parseInt($(this).css('margin-left'))) {
				box = $(this);
				box_margin = parseInt($(this).css('margin-left'));
			}
		});
		
		return box;
	}
	
	im.get_last_box = function() {
		var box;
		var box_margin = 0;
		$('.news-list .viewport .article').each(function(key, item) {
			if(box_margin < parseInt($(this).css('margin-left'))) {
				box = $(this);
				box_margin = parseInt($(this).css('margin-left'));
			}
		});
		
		return box;
	}
	
	
	/*** DO CONSTRUCT ***/
	
	im.construct();
}

function check_for_object() {
	var object = $('#content object');
	var align = $(object).find('param[name=align]').attr('value');

	if(align == "right") {
		$(object).parent().addClass('alignright').css('width', $(object).attr('width') +'px');
	}
}

// initialize class
$(document).ready(function() {
	/*$('.read-more').click(function(event) {
		im.load_news("next", $(this).parent().parent().parent().parent());
	});
	
	$('.news-list .image img').click(function(event) {
		im.load_news("next", $(this).parent().parent().parent().parent().parent());
	});*/

	im = new informedia();
});