/*** 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');
		});
		
		// contact popup
		$('#contact-popup .close').click(function() {
			$('#contact-popup').hide();
		});
		
		// click on contact
		$('#content .contacts .contact').click(function() {
			// position the popup
			var pos = $(this).offset();
			if(pos.left > $(document).width()/2)
				pos.left = pos.left - ($('#contact-popup').width()-100);
			
			$('#contact-popup').css({
				'left': pos.left-1,
				'top': pos.top-1
			});
			
			// clear old data
			$('#contact-popup .text h3').text("");
			$('#contact-popup .text .content').html("");
			
			// display loader and popup
			$('#contact-popup .loader').show();
			$('#contact-popup').show();
			
			// load clicked contact
			$.post(im.ajax_url, {'blogid': blogid, 'action': 'get_post', 'id': $(this).find('input[name=id]').val()}, function(data, status) {
				if(status != "success") {
					alert('Failed!');
					return;
				}
				
				$('#contact-popup .text h3').text(data.post_title);
				$('#contact-popup .text .content').html(data.post_content);
				$('#contact-popup .loader').hide();
				
			}, "json");
			
		});
		
		$.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;
		});
		
		//Init image effects
		im.image_effects.process();
		im.image_effects.bind();
	}
	
	
	/*** IMAGE EFFECTS ***/
	
	//Effects
	im.image_effect_grayscale = {
		
		construct : function (jqImgObject) {
			// default values
			blogurl =	blogurl		|| '';
			blogid =	blogid		|| '2';

			var filename = jqImgObject.attr('src').split('/');
			filename = filename[filename.length-1];
			
			//$('#debug').append("src: "+ $(jqImgObject).attr('src') +" width (jq): "+ $(jqImgObject).attr('width') +" width (js): "+ $(jqImgObject)[0].width +"<br />");
			
//			jqImgObject.attr('alt', '');
			
			jqImgObject.wrap('<span style="display: block; background: transparent url(/wp-content/blogs.dir/' + blogid + '/image-effects/grayscale/' + filename + ') no-repeat; width: ' + jqImgObject.attr('width') + 'px; height: ' + jqImgObject.attr('height') + 'px;" class="' + jqImgObject.attr('class') + '"></span>');
			
			jqImgObject.after('<!-- -->'); // IE6 needs this
			
			jqImgObject.removeAttr('class');
			
			jqImgObject.hide();
		},
		
		activate : function (jqObject) {
			jqObject.find('img').fadeIn();
		},
		
		deactivate : function (jqObject) {
			jqObject.find('img').fadeOut();
		}
		
	}
	
	// Main
	im.image_effects = {
		
		// default values
		defaults : {jqHolderObject: $('.image-effects-holder')},
		
		// first type is default
		types : ['grayscale'],
		
		// use the same order as in types
		effects : [im.image_effect_grayscale],
		
		process : function (jqHolderObject) {
			jqHolderObject = jqHolderObject || im.image_effects.defaults.jqHolderObject; // default jqHolderObject
			
			var find = 'img.image-effect.' + im.image_effects.types.join(', img.image-effect.');
			
			// loop holders
			jqHolderObject.each(function () {
				
				// process images
				$(this).find(find).each(function () {
					
					var effect = im.image_effects.getEffectFromClass($(this));
					effect.construct($(this));
					
				});
				
			});
			
		},
		
		bind : function (jqHolderObject) {
			jqHolderObject = jqHolderObject || im.image_effects.defaults.jqHolderObject; // default jqHolderObject
			
			jqHolderObject.bind('mouseover', function () {
				
				// if not active holder
				if (!$(this).hasClass('image-effect-active')) {
					// deactivate current active holder
					im.image_effects.deactivate($('.image-effect-active'));
					$('.image-effect-active').removeClass('image-effect-active');
					
					// activate this holder
					im.image_effects.activate($(this));
					$(this).addClass('image-effect-active');
				}
			});
		},
		
		activate : function (jqHolderObject) {
			jqHolderObject.find('.image-effect').each(function () {
				var effect = im.image_effects.getEffectFromClass($(this));
				effect.activate($(this));
			});
		},
		
		deactivate : function (jqHolderObject) {
			jqHolderObject.find('.image-effect').each(function () {
				var effect = im.image_effects.getEffectFromClass($(this));
				effect.deactivate($(this));
			});
		},
		
		getEffectFromClass : function (jqObject) {
			
			var classes = jqObject.attr('class').split(' ');
			
			for(var i = 0; i < im.image_effects.types.length; i++)
				if (classes.in_array(im.image_effects.types[i]))
					return im.image_effects.effects[i];
			return im.image_effects.effects[0];
		}
		
	}
	
	
	/*** 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
		
		// scroll window
		$.scrollTo($('#cases').offset().top-40, {duration: im.default_animation_duration, easing: "easeInOutExpo"}); //############# offset() funkar inte som den ska i ie6

		$("#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) {
		
		$.scrollTo($('#top .info').offset().top - 15, {duration: im.default_animation_duration, easing: "easeInOutExpo"});
		
		// Set new loader height
		$('#content .news-loader').height($('#content .news-main').outerHeight()-1); //1 px border
		
		// 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())-1 + "px" //1 px border
			}, im.default_animation_duration, "easeInOutExpo", function() {
				$('#content .news-loader').hide();
				$('#content .news-main').fadeIn();
			});
			
			im.image_effects.process($('#content .news-main div.article:first'));
			
		}, "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) {
					var imgClass = data.hasGrayscaleImage ? ' class="image-effect grayscale"' : '';
					$(article).find('.entry .image').html('<a rel="history" href="' + data.post.the_permalink + '#news/' + data.post.ID + '"><img src="' + image.src + '" width="148" height="104" alt=""' + imgClass + ' /></a>');
					im.click_history_button($(article).find('.entry .image'));
					
					if (imgClass != '')
						im.image_effects.process(article);
					
					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();
}

// 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();
});