/**
 * basic functions mostly for ajax / animation purposes
 *
 * @version	$Revision: 125 $
 * @date	$Date: 2008-02-22 12:31:03 +0100 (Fr, 22 Feb 2008) $
 * @author bitExpert AG <info@bitExpert.de>
 */

var iCurrentPlayground = 0;
var iActiveMainMenuPos = 0;
var iActiveMainMenuLength = 0;
var global_iCatId = 0;
var global_deptId = 0;


// disable alert boxes in FF and IE (due to jCarousel alert boxes)
//window.alert = function(){return null;};

/**
 * The logo animation for switching to the individual department sites
 *
 * @param jQuery object (the jquery link object)
 */
function animateDeparmentSwitch(poParent, psDepartmentHref)
{
	// read base href attribute to construct an absolute url
	var sBaseHref   = '';
	// read the link title to construct the logo subtext
	var sSubText    = $(poParent).attr('title');
	// read href of link needed for ajax content reloading
	var sTargetHref = $(poParent).attr('href');

	// unset href attribute to not allow the click action to ge triggerd
	$(poParent).attr('href', '#');

	if(1 == $('base').length)
	{
		sBaseHref = $('base').attr('href');
		if(1 + sBaseHref.lastIndexOf('/') != sBaseHref.length)
		{
			sBaseHref = sBaseHref + '/';
		}
	}

	// switch back to bitExpert startmenu
	if((undefined == sSubText) || ('' == sSubText))
	{
		// create img element for the color logo
		var oSubImg  = document.createElement('img');
		var $oSubImg = $(oSubImg);
		$oSubImg.css('display', 'none');
		$oSubImg.attr('class', 'link');
		$oSubImg.attr('src', 'images/bitExpert.jpg');
		$oSubImg.appendTo('#content #top #logo');

		// do the animation work
		$('#content #top #logo #subtext').fadeOut('slow', function() {
			$('#logo img, #logo img.sub').animate({bottom: '0px'}, 1000);
			$('#logo img').fadeIn('slow', function() {
				$('#logo img.sub').fadeOut('slow', function() {
					window.location.href = sBaseHref;
					});
			});
		});
		return;
	}

	// Logo animation
	if(1 == $('#content #top #logo #subtext').length)
	{
		// animation already done. change subtext only
		$('#content #top #logo #subtext').fadeOut('slow', function() {
			$(this).text(sSubText);

			global_deptId = getDeptId(sSubText);

			$(this).fadeIn('slow');

			$(this).click(function(){
				$.historyLoad(psDepartmentHref);
			});

			// reload the complete content
			loadAjaxContent(sTargetHref);
		});
	}
	else
	{
		// create div to insert the subtext
		var oSubtextDiv  = document.createElement('div');
		var $oSubtextDiv = $(oSubtextDiv);
		$oSubtextDiv.attr('id','subtext');
		$oSubtextDiv.text(sSubText);

		global_deptId = getDeptId(sSubText);

		$oSubtextDiv.appendTo('#content #top #logo');

		// create img element for the grey logo
		var oSubImg  = document.createElement('img');
		var $oSubImg = $(oSubImg);
		$oSubImg.css('display', 'none');
		$oSubImg.attr('class', 'sub');
		$oSubImg.attr('src', 'images/bitExpert_sub.jpg');
		$oSubImg.appendTo('#content #top #logo');

		$('#logo img, #logo img.sub').animate({bottom:'15px'},1000);
		$('#logo img:not(.sub)').animate({opacity: 0.0});
		$oSubImg.fadeIn('slow', function() {
			$oSubtextDiv.show();
			$oSubtextDiv.animate({bottom: '-2px'}, 1000);

			// add link to subtext
			$oSubtextDiv.click(function(){
				$.historyLoad(psDepartmentHref);
			});

			// remove the colorful logo. not needed anymore
			$('#logo img:not(.sub)').remove();
			// add "switch back" event onto the logo
			$(this).click(function(){
				animateDeparmentSwitch("#logo a.external");
			});

			// reload the complete content
			loadAjaxContent(sTargetHref);
		});
	}
}


/**
 * Get the department ID based on its name
 *
 * @param String name of the department
 * @return Number ID of the department
 */
function getDeptId(psName) {

	switch(psName) {
		default: return 0;
		case 'SOFTWARE TECHNOLOGIES': return 1;
		case 'MEDIA TECHNOLOGIES': return 2;
	}

}


/**
 * Initialize the content to use the ajax content loading routines
 *
 * @param jQuery object
 */
function initAjaxContent(poParent)
{
	var sBaseHRef = $('base').attr('href');

	// apply ajax functionality to each not-external link that is found
	$('a:not(.external)', poParent).each(function (i) {
			// read href attribute and check if the link is an relative one
			var sHRef    = $(this).attr('href');
		var bReplace = false;

		// catch some errors that occured
		if(undefined == sHRef)
		{
						return;
		}

		if((-1 != sHRef.indexOf('http://')) && (-1 !=  sHRef.indexOf(sBaseHRef)))
		{
			// Bugfix for IE: Within the process of the ajax content loading
			// somehow all relative links get replaced with their absolute
			// counterparts. In that case check via the defined base href path
			// if we are still on the same server. In that case trigger the link
			// replacement
			bReplace = true;
		}
		else if(-1 == sHRef.indexOf('http://'))
		{
			bReplace = true;

			// In case these non-http protocols are found do not allow link
			// replacement
			if((-1 != sHRef.indexOf('ftp://')) || (-1 != sHRef.indexOf('news://')) ||
				(-1 != sHRef.indexOf('mailto:')) || (-1 != sHRef.indexOf('skype:')))
			{
				bReplace = false;
			}
		}

		if(true == bReplace)
		{
			// unset href attribute to make sure clicking the links does not work
			$(this).attr('href', '#');

			// add new click handler for ajax content loading
			if('#' != sHRef)
			{
				$(this).click(function() {
					// add link to browser history and execute the loadAjaxContent
					// function
					$.historyLoad(sHRef);
					return false;
				});
			}

			// add department switch animation to any link with the animate class
			if($(this).hasClass('animate'))
			{
				$(this).click(function(){
					animateDeparmentSwitch($(this), sHRef);
					return false;
				});
			}

			// add gallery action to any link with the gallery class
			if($(this).hasClass('gallery'))
			{
				$(this).click(function(){
					global_iCatId = $(this).attr('id');
					$('#playground').toggleAndLoad(global_iCatId);
					return false;
				});
			}
		}
	});

	// bind any form that is not expicitly marked as external form to the ajax
	// form plugin
	$('form:not(.external)', poParent).each(function (i) {
		// change action string to get json response from server
		var sAction    = $(this).attr('action');
		var sNewAction = sAction + ((-1 == sAction.indexOf('?')) ? '?' : '&') + 'ajax=1';
		$(this).attr('action', sNewAction);

		$('table#contact input#contactbtn', $(this)).hover(function(){
					$(this).attr('src', $(this).attr('src').replace('.jpg', '_hover.jpg'));
				},
				function(){
					$(this).attr('src', $(this).attr('src').replace('_hover.jpg', '.jpg'));
				});

		// ajaxify the form
			$(this).ajaxForm({
					dataType: 'json',
					success: processJSONResponse
			});
	});
}


/**
 * Transfering the JSON response from the server into the html representation
 *
 * @param json object the json answer that the server returend
 */
function processJSONResponse(paData, pbSlideGalleryOut)
{
	// load main menu content
	var sMainMenuContent = paData.main;
	var sSubMenuContent = paData.sub;
	$('#mainmenu').html(sMainMenuContent);
	initAjaxContent('#mainmenu');

	// to decide if a reload of the submenu is needed check the length of
	// the current main menu. In case it is
	// different from the last saved length refresh submenu

	var iNewMainMenuLength = sMainMenuContent.length;
	var iNewMainMenuPos = sMainMenuContent.indexOf('class="current"');

	if((iNewMainMenuLength != iActiveMainMenuLength) || (iNewMainMenuPos != iActiveMainMenuPos))
	{
		iActiveMainMenuPos = iNewMainMenuPos;
		iActiveMainMenuLength = iNewMainMenuLength;
		// submenu contains elements?
		if(0 != $('#playground #submenu ul').children().length)
		{
			$('#playground').slideIn(function() {
				// load submenu content after slide in
				$('#playground').loadSubmenu(paData.sub, function() {
					$('#playground').slideOut(pbSlideGalleryOut);
				});
			});
		}
		else
		{
			// load submenu content
			$('#playground').loadSubmenu(paData.sub, function() {
				$('#playground').slideOut(pbSlideGalleryOut);
			});
		}
	}
	else
	{
		// exchange the submenu content. no animation required!
		$('#submenu').html(paData.sub);
		initAjaxContent('#submenu');
	}

	// load ajax content
	$('#ajax').html(paData.content);
	document.title = extractPageTitle(paData.title);
	initAjaxContent('#ajax');
	// check if it is necessary to exchange the background image or trigger
	// the flash action
	if(paData.playground)
	{
		var sFilename = paData.playground;
		if(-1 == sFilename.indexOf('.swf'))
		{
			// add some basic image preloading
			var oImage = new Image ();
			oImage.src = sFilename;

			$('#playground #background').fadeOut('slow', function() {
				$(this).attr('style', 'background-image: url("'+ sFilename+'");');
				$(this).fadeIn('slow');
			});
		}
	}
}


/**
 * function to extract the text between the <code>title</code>-Tags in a given
 * string
 *
 * @param string the string to be examinated
 * @return the extracted text
 */
function extractPageTitle(psString)
{
	var sRegEx = /<title>(.)*<\/title>/;
	var aResult = sRegEx.exec(psString);
	var iStartIndex = 7;
	var iEndIndex = aResult[0].length - 8;
	return aResult[0].substring(iStartIndex, iEndIndex);
}

/**
 * Callback function to be used by the history plugin to load the correct
 * content
 *
 * @param string the ajax content to load
 */
function loadAjaxContent(psCommand)
{
	if('' == psCommand)
	{
		return;
	}

	// load content
	var sCommand = psCommand + ((-1 == psCommand.indexOf('?')) ? '?' : '&') + 'ajax=1';
	$.getJSON(sCommand, function(paData){
		processJSONResponse(paData);
	});
}

/**
*
*/
function asToggleGallery(piGalleryId)
{
	global_iCatId = piGalleryId;
	$('#playground').toggleAndLoad(global_iCatId);
}


function print_r(poObject)
{
	var sResult = '';

	if(!typeof poObject == "object" || !(poObject instanceof Object))
	{
		sResult += '[type] => ' + typeof poObject + '\n\n';
		sResult += !(typeof poObject == "string") ? '[value] => ' + poObject + '\n\n' : '';
	}

		for(var key in poObject)
		{
			if('innerHTML' == key)
			{
				sResult += poObject[key].toString();
			}

			sResult += '[' + key + '] => ' + poObject[key] + '\n\n';
		}

		//document.body.innerHTML = '<pre>' + sResult + '</pre>';
		console.log('<pre>' + sResult + '</pre>');
}


function fadePlayground()
{
	$.getJSON(
		'playground.php',
		function(paData) {
			if(countElements(paData) != iCurrentPlayground)
			{
				// image preloading
				var oImage = new Image();
				oImage.src = paData[iCurrentPlayground].path;

				$('#background').fadeOut('slow', function() {
					$(this).attr('style', 'background-image: url("'+ paData[iCurrentPlayground].path +'");');
					$(this).fadeIn('slow');
				});
				iCurrentPlayground++;
			}
			else
			{
				iCurrentPlayground = 0;
			}
		});
}


function countElements(paData)
{
	var iCurrentCounter = 0;

	for(var key in paData)
	{
		iCurrentCounter++;
	}

	return iCurrentCounter;
}


function pushContent(paData)
{
	if('-1' != paData)
	{
		$('#ajax').empty();
		$('#ajax').append(paData);
	}
	else
	{
		alert('Es wurde kein passender Content zu diesem Bild gefunden!');
	}
}


$(document).ready(function() {
	if('edit' != $('body').attr('id'))
	{
		$.historyInit(loadAjaxContent);
		initAjaxContent($(document));

		$('#playground').toggleAndLoad(112);
		window.setInterval("fadePlayground()", 27500);
	}
});

