/**
 * 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 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;};


/**
 * 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 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 
	    });
	});

	checkDepartment(window.location.href, sBaseHRef);
}


/**
 * 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 loadPortfolioAccordionNavigation(piCurrentPanel)
{
	var oGalleryAccordion = $('#gallery-menu').accordion({ 
		header: '.gallery-menu-title', 
		alwaysOpen: true, 
		animated: false, 
		autoheight: false
	});
	// call the current panel
	oGalleryAccordion.activate(piCurrentPanel);

}


function checkDepartment(psHash, psBaseHref)
{
	sHash = psHash.slice(psHash.indexOf('#')+1);
	aName = sHash.split('/');
	sName = aName[2];
	sDepartmentHref = '';


	if((('bitexpert' == sName) || ('' == sName)) && (1 == $('#content #top #logo #subtext').length))
	{
		clearSubtext();
	}
	else if((('media-technologies' == sName) || ('software-technologies' == sName)) && (0 == $('#content #top #logo #subtext').length))
	{
		if('media-technologies' == sName)
		{
			sDepartmentHref = aName[0] + '/' + aName[1] + '/media-technologies/';
		}
		else if('software-technologies' == sName)
		{
			sDepartmentHref = aName[0] + '/' + aName[1] + '/software-technologies/';
		}

		sName = sName.replace('-', ' ').toUpperCase();
		setSubtext(sName, sDepartmentHref);
	}
}


function clearSubtext()
{
	// 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 = getBaseHref();
			});
		});
	});
	return;
}

function setSubtext(psSubText, psDepartmentHref)
{
	// create div to insert the subtext
	var oSubtextDiv  = document.createElement('div');
	var $oSubtextDiv = $(oSubtextDiv);
 	$oSubtextDiv.attr('id','subtext');
	$oSubtextDiv.text(psSubText);
		
	global_deptId = getDeptId(psSubText);
		
	$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(){
			clearSubtext();
		});
	});
}


function getBaseHref()
{
	var sBaseHref = '';

	if(1 == $('base').length)
	{
		sBaseHref = $('base').attr('href');
		if(1 + sBaseHref.lastIndexOf('/') != sBaseHref.length)
		{
			sBaseHref = sBaseHref + '/';
		}
	}

	return sBaseHref;
}

function asToggleGallery(piGalleryId)
{
    // to be defined...
}

/**
*
*/
$(document).ready(function() {
	if('edit' != $('body').attr('id'))
	{
		// pre-work: extract the html content of the mainmenu and identify
		// current active mainmenu entry
		var sMainMenuContent = $('#mainmenu').html();
		iActiveMainMenuPos = sMainMenuContent.indexOf('class="current"');

		$.historyInit(loadAjaxContent);
		initAjaxContent($(document));
	}
});


