﻿$(document).ready(init);

var webservices = [
      {
         'name' : 'larskiesow.de',
         'url' : './service/',
         'key' : 'ugcIoiY9cz8PJf8aVuMk'
      }
   ];
var postsPerPage = 4;
var currCatData = null;

loadingHTML = '<div style="width: 100px; margin-left: auto; margin-right: auto;">'
    + '<img src="gfx/loading.gif" alt="loading..." />'
    + '</div>';
   
function init() {
   requestWebservices( {"cmd" : "getCategories"},
      function(data) {
         if (handleError(data)) {
            for ( navigation_id in data.data ) {
               if (navigation_id == 0) {
                  for ( category_id in data.data[navigation_id] ) {
                     $('#categories_top').append('<div class="cat"><a href="javascript: loadCategory('
                        + category_id + ', \'' + data.data[navigation_id][category_id].name + '\');">'
                        + data.data[navigation_id][category_id].name + '</a></div>');
                  }
               } else if (navigation_id == 1) {
                  for ( category_id in data.data[navigation_id] ) {
                     $('#categories_bottom').append('<div class="cat"><a href="javascript: loadCategory(' + category_id + ');">'
                        + data.data[navigation_id][category_id].name + '</a></div>');
                  }
               } // dont show other categories
            }
         }
      });

	// check if post_id is set
	var paramPairs = window.location.hash.replace(/^#/, '').split(';');
	var param = { };
	for ( id in paramPairs ) {
		var attr = paramPairs[id].split('=');
		if (attr.length == 2)
			param[attr[0]] = attr[1];
	}
	if ( param.id ) {
		loadPost( param.id );
	// otherwise load news page
	} else if ( param.cat ) {
		loadCategory( param.cat );
	} else if ( param.search ) {
		search( unescape( param.search ), param.searchall );
	} else {
		loadCategory( null );
	}
}

function requestWebservices(request, onSuccess, onError) {
   /* TODO: Combine the  results */
   for ( key in webservices ) {
      request.key = webservices[key].key;
      $.ajax({
         type: 'POST',
         url: webservices[key].url,
         dataType: 'json',
         data   : ({'request' : $.toJSON(request) }),
         success: onSuccess,
         error: onError
      });
   }
}

function handleError(data) {
   if (data.type === 'undefined') {
      alert('ERROR: No datatype defined.');
      return false;
   }
   if (data.type == 'error') {
      var add_info = '';
      if (data.errtype == 'sql_error')
         add_info = '\n\nsql query: ' + data.sql_statement;
         
      alert('ERROR:\n\ntype: ' + data.errtype + '\n\nmessage: ' + data.errmsg + add_info);
      return false;
   }

   if (data.type == 'result') {
      return true;
   }

   return false
}

function lexCompare(a, b) {
	return a < b ? -1 : ( a > b ? 1 : 0);
}

function loadPost(post_id) {
	$('#content').html(loadingHTML);
	var request = { 
			'cmd'  : 'getPost',
			'args' : {'post_id' : post_id}
		};
	requestWebservices( request,
		function(data) {
			if (handleError(data)) {
				currCatData = { };
				currCatData.count = 1;
				currCatData.data = new Array();
				currCatData.data.push( data.data );

				document.title = 'larskiesow.de::post' + data.data.id + ': ' + data.data.title;
				$('#content').html('');
				count = 0;
				for ( id in currCatData.data ) {
					addPost( currCatData.data[id] );
					count++;
					if (count >= postsPerPage)
						break;
				}
				onContentLoaded();

				setPager(1);
			}
		});
}

function loadCategory(category_id, category_name) {
	$('#content').html(loadingHTML);
	var request = { "cmd" : "getPosts" };
	if (category_id)
		request.args = {'category' : category_id};
	requestWebservices( request,
		function(data) {
			if (handleError(data)) {
				// alert($.toJSON(data));
				if ( window.location.hash || category_id )
					window.location.hash = category_id ? 'cat=' + category_id : '';
				currCatData = { };
				currCatData.count = data.count;
				currCatData.data = new Array();
				for ( post_id in data.data ) {
					// secure post_id in object
					var obj = data.data[post_id];
					obj.id = post_id;
					currCatData.data.push( obj );
				}
				// nach lastedit absteigend sortieren
				currCatData.data.sort( function(a, b) { return lexCompare(b.lastedit, a.lastedit); } );

				document.title = 'larskiesow.de::' + (category_name ? category_name.toLowerCase() : 'main');
				$('#content').html('');
				count = 0;
				for ( id in currCatData.data ) {
					addPost( currCatData.data[id] );
					count++;
					if (count >= postsPerPage)
						break;
				}
				onContentLoaded();

				setPager(1);
			}
		});
}

function addPost( obj ) {
	$('#content').append('<div class="post"><div class="datetime" title="Erstellt: '
		+ obj.created + '">'  + obj.lastedit + '</div>\n<h1>'
		+ obj.title + '</h1>' + obj.content
		+ '<div class="staticlink"><a onclick="loadPost(' + obj.id + ');" href="#id=' + obj.id + '">static link</a> </div> </div>');
}

function goToPage(page) {
	if (currCatData) {
		setPager(page);
		$('#content').html('');
		count = 0;
		stop = page * postsPerPage;
		start = stop - postsPerPage;
		for ( id in currCatData.data ) {
			if (count >= start) {
				addPost( currCatData.data[id] );
			}
			count++;
			if (count >= stop)
				break;
		}
		onContentLoaded();
	}
}

function setPager(page) {
   if (currCatData) {
      $('#pager').html('');
      pagecnt = Math.ceil(currCatData.count / postsPerPage);
      if (pagecnt <= 1)
         return;
      start = Math.max(1, page - 2);
      stop  = Math.min(page + 2, pagecnt);
      if (page > 1) {
         $('#pager').append('<div class="pagelink" onclick="goToPage(' + (page - 1) + ')" id="prevpage">&larr;</div> ');
         if (page > 3) {
            $('#pager').append('<div class="pagelink" onclick="goToPage(1)" id="pagelink_1">1</div> ');
            if (page > 4) {
               $('#pager').append('<div class="pagedots">&hellip;</div> ');
            }
         }
      }
      for (var i = start; i <= stop; i++) {
         $('#pager').append('<div class="pagelink" onclick="goToPage(' + i + ')" id="pagelink_' + i + '">' + i + '</div> ');
      }
      if (page < pagecnt) {
         if (page < pagecnt - 2) {
            if (page < pagecnt - 3) {
               $('#pager').append('<div class="pagedots">&hellip;</div> ');
            }
            $('#pager').append('<div class="pagelink" onclick="goToPage(' + pagecnt + ')" id="pagelink_' + pagecnt + '">' + pagecnt + '</div> ');
         }
         $('#pager').append('<div class="pagelink" onclick="goToPage(' + (page + 1) + ')" id="nextpage" title="Nächste Seite">&rarr;</div>');
      }
      $('#pagelink_' + page).css('background-color', '#666666');
   }
}

function search( str, searchall ) {
	$('#content').html(loadingHTML);
	var request = { 
			'cmd' : 'getPosts', 
			'args' : { 'search' : str } 
		};
	if (searchall == 1)
		request.args.searchall = true;

	requestWebservices( request,
		function(data) {
			if (handleError(data)) {
				window.location.hash = 'search=' + escape(str) + ';searchall=' + searchall;
				document.title = 'larskiesow.de::search::' + str;
				currCatData = { };
				currCatData.count = data.count;
				currCatData.data = new Array();
				for ( post_id in data.data ) {
					// secure post_id in object
					var obj = data.data[post_id];
					obj.id = post_id;
					currCatData.data.push( obj );
				}
				// nach lastedit absteigend sortieren
				currCatData.data.sort( function(a, b) { return lexCompare(b.lastedit, a.lastedit); } );
				$('#content').html('');
				count = 0;
				for ( id in currCatData.data ) {
					addPost( currCatData.data[id] );
					count++;
					if (count >= postsPerPage)
						break;
				}
				onContentLoaded();

				setPager(1);
			}
		});
}

function openSearchBox() {
	showCustomDialog(
		'<form id="search" action="#">' + 
		'	<p><input name="searchbox" id="searchbox" type="text" /></p>' +
		'	<p><select id="searchallselector">' +
		'		<option value="0">search in title only</option>' +
		'		<option value="1">search in title and description</option>' +
		'	</select></p>' +
		'	<p><button id="searchbutton" type="button">search</button></p></form>',
		function() { $('#searchbutton').click( function() { 
				search( $('#searchbox').val(), $('#searchallselector').val() );
				$.fancybox.close();
			} );
			$('#search').submit( function() { 
				search( $('#searchbox').val(), $('#searchallselector').val() );
				$.fancybox.close();
				return false;
			} );
			$('#searchbox').focus();
			});
}

