﻿// ************ RICH PAGE MANAGER ************
var RichPageManager = function(postsData, stopsData, direction, showPlan, map, enableAutoresize) {
	this.postsData = postsData;
	this.stopsData = stopsData;
	this.direction = direction;
	this.showPlan = showPlan;
	this.map = map;
	this.enableAutoresize = enableAutoresize;
	
	this.focusedPostID = null;
}
RichPageManager.prototype.setPageLayout = function() {
	if (!this.enableAutoresize)
		return;

	var mabBannerHeight = 0;
	if ($('div.bannerMap').length != 0 && $('div.bannerMap').data('allreadyUsedToResize') == null ) {
		mabBannerHeight = $('div.bannerMap').height();
		$('div.bannerMap').data('allreadyUsedToResize', true);
	}

	var windowHeight = $(window).height();

	if (windowHeight < 500)
		windowHeight = 500;

	var sizeDif = windowHeight - $('#page').outerHeight(true) + mabBannerHeight;

	var contentLeftHeight = $('div.contentLeftWindow').height() + sizeDif - mabBannerHeight;
	var contentRightHeight = $('div.contentRightWindow').height() + sizeDif;
	var dividerHeight = $('a.contentDivider').height() + sizeDif;

	$('div.contentLeftWindow').height(contentLeftHeight);
	$('div.contentRightWindow').height(contentRightHeight);
	$('a.contentDivider').height(dividerHeight);
}
RichPageManager.prototype.init = function() {
	this.map.loadPosts(this.postsData);
	this.map.loadPlan(this.stopsData, this.showPlan);
	
	var numPosts = this.postsData.length;
	
	if (numPosts == 0)
		return;

	var pathLength = this.timeLine_CalculatePathLength();
	this.timeLine_InitPaths(pathLength, this.postsData[numPosts - 1]);
	
	var postMarkers = $('#timeline_path').children('div.-sel-marker');
	var posts = $('#postList').children('div.-sel-post');
	
	for (var i = 0; i < numPosts; i++) {
		var postInfo = this.postsData[i];
		var postIdx = this.direction == 0 ? numPosts - (i + 1) : i;
		
		this.timeLine_InitPostMarker(postMarkers.eq(i), postInfo, pathLength);
		this.postList_InitPost(posts.eq(postIdx), postInfo);
	}
	
	this.timeLine_InitControls();
	this.map_InitControls();
	
	var actualPost = this.direction == 0 ? this.postsData[numPosts - 1] : this.postsData[0];
	
	this.postList_SetPostFocus(actualPost.id);
	this.timeline_SetPostFocus(actualPost.id);
	this.map_SetPostFocus(actualPost.id);
	this.focusedPostID = actualPost.id;
}
RichPageManager.prototype.timeLine_PostFocusChanged = function(postID) {
	this.postList_SetPostFocus(postID);
	this.map_SetPostFocus(postID);
	this.focusedPostID = postID;
}
RichPageManager.prototype.timeline_SetPostFocus = function(postID) {
	var pinPosition = $('#timeline_post_' + postID).position();

	$('#timeline_slider')
		.css({ 'left': pinPosition.left - 5 + 'px' })
		.show();
}
RichPageManager.prototype.timeLine_InitPostMarker = function(postMarker, postInfo, pathLength) {
	var offsetUnit = pathLength / 100;
	var markerOffset = offsetUnit * postInfo.offset;

	var that = this;
	postMarker
		.css('left', markerOffset + 'px')
		.show()
		.children().bind('click', { postID: postInfo.id }, function(event) {
			that.timeline_SetPostFocus(event.data.postID);
			that.timeLine_PostFocusChanged(event.data.postID);
			event.preventDefault();
		});
}
RichPageManager.prototype.timeLine_CalculatePathLength = function() {
	return $('#timeline_path').innerWidth() - 10;
}
RichPageManager.prototype.timeLine_InitPaths = function(pathLength, activePost) {
	var offsetUnit = pathLength / 100;
	var completedPathLength;

	if (activePost != null) {
		completedPathLength = offsetUnit * activePost.offset;
	} else {
		completedPathLength = pathLength;
	}

	$('#timeline_path_line')
		.css({
			'left': '5px',
			'width': completedPathLength + 'px'
		})
		.show();

	$('#timeline_path_linePlanned')
		.css({
			'left': (completedPathLength) + 'px',
			'width': (pathLength - completedPathLength) + 'px'
		})
		.show();

	$('#timeline_labels').width(pathLength + 10).show();
}
RichPageManager.prototype.timeLine_InitControls = function() {
	var that = this;

	$('#timeline_control_previous')
		.bind('click', function(event) {
			var previousPost = _getPost(that.focusedPostID, -1);
			if (previousPost != null) {
				that.timeline_SetPostFocus(previousPost.id);
				that.timeLine_PostFocusChanged(previousPost.id);
			}

			event.preventDefault();
		});

	$('#timeline_control_next')
		.bind('click', function(event) {
			var nextPost = _getPost(that.focusedPostID, 1);
			if (nextPost != null) {
				that.timeline_SetPostFocus(nextPost.id);
				that.timeLine_PostFocusChanged(nextPost.id);
			}

			event.preventDefault();
		});
}
RichPageManager.prototype.map_PostFocusChanged = function(postID) {
	this.postList_SetPostFocus(postID);
	this.timeline_SetPostFocus(postID);
	this.focusedPostID = postID;
}
RichPageManager.prototype.map_SetPostFocus = function(postID) {
	this.map.setPostFocus(postID);
}
RichPageManager.prototype.map_FocusPosts = function() {
	this.map.focusAllPosts();
}
RichPageManager.prototype.map_InitControls = function() {
	var that = this;
	$('#tripMap_control_focusAll').bind('click', function(event) {
		that.map_FocusPosts();
		event.preventDefault();
	});
	
	$('#tripMap_control_togglePlan').bind('click', function(event) {
		that.map.togglePlan($(this).is(':checked'));
	});
}
RichPageManager.prototype.postList_PostFocusChanged = function(postID) {
	this.map_SetPostFocus(postID);
	this.timeline_SetPostFocus(postID);
	this.focusedPostID = postID;
}
RichPageManager.prototype.postList_SetPostFocus = function(postID) {
	$('#postList').scrollTo($('#post_' + postID), 500);

	if (this.focusedPostID != null)
		$('#post_' + this.focusedPostID).removeClass('postReleased');

	$('#post_' + postID).addClass('postReleased');
}
RichPageManager.prototype.postList_InitPost = function(post, postInfo) {
	var that = this;
	
	post.bind('click', { postID: postInfo.id }, function(event) {
		that.postList_SetPostFocus(event.data.postID);
		that.postList_PostFocusChanged(event.data.postID);
	});

	post.find('a, input').bind('click', function(event) {
		event.stopPropagation();
	});
	
	post.find('a.-sel-post-control-related').bind('click', function(event) {
		var postID = $(this).attr('rel');
		postID = postID.substring(12, postID.length - 1);
		
		relatedContent_Load(postID);
		event.preventDefault();
	});
}

// ************ MOBILE PAGE MANAGER ************
var MobilePageManager = function(postsData, stopsData, direction, showPlan, map) {
	this.postsData = postsData;
	this.stopsData = stopsData;
	this.direction = direction;
	this.showPlan = showPlan;
	this.map = map;
	
	this.focusedPostID = null;
}
MobilePageManager.prototype.setPageLayout = function() {
	$('#page_timeline').hide();
	
	$('div.contentRightWindow').css({
		'overflow': 'none',
		'height': 'auto'
	});
}
MobilePageManager.prototype.init = function() {
	this.map_InitControls();
	
	this.map.loadPosts(this.postsData);
	this.map.loadPlan(this.stopsData, this.showPlan);
	
	this.postList_InitPost();
}
MobilePageManager.prototype.map_InitControls = function() {
	var that = this;
	$('#tripMap_control_focusAll').bind('click', function(event) {
		that.map.focusAllPosts();
		event.preventDefault();
	});
	
	$('#tripMap_control_togglePlan').bind('click', function(event) {
		that.map.togglePlan($(this).is(':checked'));
	});
}
MobilePageManager.prototype.map_PostFocusChanged = function(postID) {}
MobilePageManager.prototype.postList_InitPost = function() {
	$('a.-sel-post-control-related').bind('click', function(event) {
		var postID = $(this).attr('rel');
		postID = postID.substring(12, postID.length - 1);
		
		relatedContent_Load(postID);
		event.preventDefault();
	});
}

// ************ FLASH MAP ************
var FlashMap = function(containerID, apiKey) {
	this.containerID = containerID;
	this.apiKey = apiKey;
	
	this.getFlashObject = function() {
		if (navigator.appName.indexOf('Microsoft') != -1) {
			return document.forms[0]['TripMap'];
		} else {
			return document['TripMap'];
		}
	};
}
FlashMap.prototype.loadMap = function(callback) {
	var params = {
		wmode: 'transparent',
		bgcolor: '#ffffff'
	};

	var attributes = {  
		id: 'TripMap',  
		name: 'TripMap'
	};

	var flashvars = {
		mapkey: this.apiKey,
		mapMode: 'trip',
		showPath: true
	};

	swfobject.embedSWF('/res/skins/TripMap.swf?v=1.7', this.containerID, '100%', '100%', '9.0.0',
		'/res/editarticle/expressInstall.swf', flashvars, params, attributes
	);
}
FlashMap.prototype.loadPosts = function(posts) {
	this.getFlashObject().loadPosts(posts);
}
FlashMap.prototype.loadPlan = function(plan, isVisible) {
	this.getFlashObject().loadPlan(plan, isVisible);
}
FlashMap.prototype.setPostFocus = function(postID) {
	this.getFlashObject().setPostFocus(postID);
}
FlashMap.prototype.focusAllPosts = function() {
	this.getFlashObject().focusAllPosts();
}
FlashMap.prototype.togglePlan = function(isVisible) {
	this.getFlashObject().togglePlan(isVisible);
}

// ************ JAVASCRIPT MAP ************
var JSMap = function(containerID) {
	this.containerID = containerID;
	
	this.map = null;
	this.bounds = new google.maps.LatLngBounds();
	this.plannedPoints = new Array();
	this.plannedPath = null;
	this.plannedPathOutline = null;
}
JSMap.prototype.loadMap = function(callback) {
	var that = this;
	$(window).load(function() {
		var mapHolder = document.getElementById(that.containerID);
		
		var mapOptions = {
			zoom: 8,
			center: new google.maps.LatLng(-34.397, 150.644),
			navigationControl: true,
			navigationControlOptions: { 
				style: google.maps.NavigationControlStyle.DEFAULT 
			}, 
			scaleControl: true,
			mapTypeControl: true,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		
		that.map = new google.maps.Map(mapHolder, mapOptions);
		
		if (typeof callback == 'function')
			callback();
	});
}
JSMap.prototype.loadPosts = function(posts) {
	var pathPoints = new Array();
	
	var image = new google.maps.MarkerImage(
		'/res/skins/default/stop.png',
		new google.maps.Size(22, 22),
		new google.maps.Point(0, 0),
		new google.maps.Point(11, 11)
	);
	
	for (var i = 0; i < posts.length; i++) {
		var post = posts[i];
		
		if (post.lat == null || post.lng == null)
			continue;
			
		var latLng = new google.maps.LatLng(post.lat, post.lng);

		pathPoints.push(latLng);
		this.bounds.extend(latLng);
		
		var marker = new google.maps.Marker({
			position: latLng,
			map: this.map,
			icon: image
		});
	}

	var pathOutline = new google.maps.Polyline({
		path: pathPoints,
		strokeColor: "#FFFFFF",
		strokeOpacity: 1.0,
		strokeWeight: 4
	});
	pathOutline.setMap(this.map);
	var path = new google.maps.Polyline({
		path: pathPoints,
		strokeColor: "#1282C0",
		strokeOpacity: 1.0,
		strokeWeight: 2
	});
	path.setMap(this.map);

	this.map.fitBounds(this.bounds);
}
JSMap.prototype.loadPlan = function(plan, isVisible) {
	var pathPoints = new Array();
	
	var image = new google.maps.MarkerImage(
		'/res/skins/default/stopPlan.png',
		new google.maps.Size(15, 15),
		new google.maps.Point(0, 0),
		new google.maps.Point(7, 7)
	);
	
	for (var i = 0; i < plan.length; i++) {
		var post = plan[i];
		
		if (post.lat == null || post.lng == null)
			continue;
			
		var latLng = new google.maps.LatLng(post.lat, post.lng);

		pathPoints.push(latLng);
		
		var marker = new google.maps.Marker({
			position: latLng,
			map: isVisible ? this.map : null,
			icon: image
		});
		this.plannedPoints.push(marker);
	}

	this.plannedPathOutline = new google.maps.Polyline({
		path: pathPoints,
		strokeColor: "#FFFFFF",
		strokeOpacity: 1.0,
		strokeWeight: 4
	});
	this.plannedPathOutline.setMap(isVisible ? this.map : null);
	this.plannedPath = new google.maps.Polyline({
		path: pathPoints,
		strokeColor: "#A1D64C",
		strokeOpacity: 1.0,
		strokeWeight: 2
	});
	this.plannedPath.setMap(isVisible ? this.map : null);
}
JSMap.prototype.setPostFocus = function(postID) {}
JSMap.prototype.focusAllPosts = function() {
	this.map.fitBounds(this.bounds);
}
JSMap.prototype.togglePlan = function(isVisible) {
	for (var i = 0; i < this.plannedPoints.length; i++) {
		this.plannedPoints[i].setMap(isVisible ? this.map : null);
	}
	
	this.plannedPathOutline.setMap(isVisible ? this.map : null);
	this.plannedPath.setMap(isVisible ? this.map : null);
}

// ************ UTILITIES ************
function _getPost(postID, shift) {
	for (var i = 0; i < POSTS_DATA.length; i++) {
		if (POSTS_DATA[i].id == postID) {
			if (shift == 0)
				return POSTS_DATA[i];
			else if (shift > 0 && shift + i <= POSTS_DATA.length)
				return POSTS_DATA[i + shift];
			else if (shift < 0 && shift + i >= 0)
				return POSTS_DATA[i + shift];
			else
				return null;
		}
	}
	return null;
}

// ************ POST STATUS CHECKER ************
var PROCESSED_POSTS = new Array();
function initPostCheckingProcess(postIDs){
	$(document).ready(function() {
		PROCESSED_POSTS = postIDs;
		checkPostsStatus();
	});
}

function checkPostsStatus() {
	if (PROCESSED_POSTS.length == 0)
		return;
	
	$.getJSON('/CheckPostsStatus.ashx?data=' + PROCESSED_POSTS.join(), function(stats){
		if (stats != null) {
			$.each(stats, function(i, stat) {
				if (stat.isProcessed) {
					PROCESSED_POSTS = $.grep(PROCESSED_POSTS, function(value){
						return value != stat.postID;
					});
					
					var processingPost = $('#post_' + stat.postID);
					var processedPost = $(stat.data);
					
					if (processingPost.find('li.date').hasClass('actual'))
						processedPost.find('li.date').addClass('actual');
					
					processingPost.replaceWith(processedPost);
					initMediaGallery();
				}
			});
			
			setTimeout('checkPostsStatus();', 5000);
		}
	});
}