/**
 * jQuery base functions
 * 
 * @author ProTom
 */

var protom = {};

protom.logEnabled = false;

protom.log = function(message)
{
	 if(protom.logEnabled && window.console)
	 {
		 console.debug(message);
	 }

}

//***************************
// toggles the boxes between visible and invisible, also toggles the box header class
//***************************
protom.toggleBoxes = function()
{
	$j(this).parent('.rounded').children('.boxContent').slideToggle();

	var label = $j(this).children().children('h4');
	if($j(label).hasClass('colapsible'))
	{
		$j(label).removeClass('colapsible');
		$j(label).addClass('expandable');
	}
	else
	{
		$j(label).addClass('colapsible');
		$j(label).removeClass('expandable');
	}
};

//***************************
// initially sets up toggle boxes
//***************************
protom.setupToggleBoxes = function()
{
	// hide all default hidden boxes
	$j('.rounded:has(.expandable) .boxContent').hide();

	// add click listener for box headers
	$j('.rounded:has(.colapsible) .top').bind('click', protom.toggleBoxes).css('cursor', 'pointer');
	$j('.rounded:has(.expandable) .top').bind('click', protom.toggleBoxes).css('cursor', 'pointer');

};

//***************************
// opens a link in a new window
//***************************
protom.newWindow = function(url)
{
	window.open(url);
};

//***************************
// opens a banner link with click count
//***************************
protom.openBannerLink = function()
{
	$j.get('/tools/banner/registerclick/format/json/banner/'+this.id);
	protom.newWindow(this.href);
	return false;
};

//***************************
// opens a external link
//***************************
protom.openExternalLink = function()
{
	protom.newWindow(this.href);
	return false;
}

//***************************
// initially sets up banner links
//***************************
protom.setupBannerLinks = function()
{
	$j('.bannerLink').bind('click', protom.openBannerLink);
};

//***************************
// initially sets up external links
//***************************
protom.setupExternalLinks = function()
{
	$j('.externalLink').bind('click', protom.openExternalLink);
};

/*
 * handels center column xhr functions
 * including paged navigation and display type
 */

protom.centerColumn = {
	'params' : {
		'href' : location.href,
		'area' : 'center',
		'format' : 'xhr',
		'display': 'list',

		getString	: function()
		{
			var result = '';
			for(name in protom.centerColumn.params)
			{
				if(typeof protom.centerColumn.params[name] != 'function' && protom.centerColumn.params[name] != '' && name != 'href')
				{
					if(result != '')
					{
						result = result + '&';
					}
					result = result + name + '=' + protom.centerColumn.params[name];
				}
			}
			return result;
		},
		getUrl: function()
		{
			var base = protom.centerColumn.params.href;
			if(base.indexOf('#') !== -1)
			{
				base = base.substring(0, base.indexOf('#'));
			}

			if(base.indexOf('?') === -1)
			{
				return base + '?' + protom.centerColumn.params.getString();
			}
			else
			{
				return base + '&' + protom.centerColumn.params.getString();
			}
		}
	}
};

// load the center column with the given url parameters as xhr
protom.centerColumn.load = function()
{
	$j('#content').load(protom.centerColumn.params.getUrl(), null, function(result){
		protom.centerColumn.setup();
	});
};

// setup elements in the center column
protom.centerColumn.setup = function()
{
	protom.centerColumn.paginator.setup();
	protom.centerColumn.countryFilter.init();
};

//***************************
// paginator functions
//***************************
protom.centerColumn.paginator = {
	'setup' : function()
	{
		$j('.paginator a').bind('click', function(event)
		{
			var href = $j(this).attr('href');
			var page = href.substring(href.indexOf('page=')+5);

			if(href.indexOf('area=right') != -1)
			{
				protom.centerColumn.params.area = 'right';
			}

			protom.centerColumn.params.page = page;
			protom.centerColumn.load();

			if($j.address.value == '/')
			{
				$j.address.value('listpage_1');
			}

			$j.address.value('listpage_'+page);
			return false;
		});
	},

	'showPage' : function(page)
	{
		var href = $j($j('.paginator a')[0]).attr('href');
		if(href.indexOf('area=right') != -1)
		{
			protom.centerColumn.params.area = 'right';
		}
		protom.centerColumn.params.page = page;
		protom.centerColumn.load();
	}
};

//***************************
// country and alphabetical filter for companies
//***************************
protom.centerColumn.countryFilter =
{
	init : function()
	{
		$j('.alphabeticalFilter a').bind('click', function(){
			if(this.text !== 'alle')
			{
				protom.centerColumn.params.filter = true;
				protom.centerColumn.params.character = this.text;
			}
			else
			{
				if(!protom.centerColumn.params.country)
				{
					delete(protom.centerColumn.params.filter);
				}
				delete(protom.centerColumn.params.character);
			}
			protom.centerColumn.load();
			return false;
		});

		$j('.countryFilter select').bind('change', function(){
			if(this.value != 0)
			{
				protom.centerColumn.params.filter = true;
				protom.centerColumn.params.country = this.value;
			}
			else
			{
				if(!protom.centerColumn.params.character)
				{
					delete(protom.centerColumn.params.filter);
				}
				delete(protom.centerColumn.params.country);
			}
			protom.centerColumn.load();
			return false;
		});
	}


}


//***************************
// content chooser functions
//***************************
protom.centerColumn.contentChooser = {
	'setup' : function()
	{
		$j('.displayswitch').bind('click', function(event)
		{
			var value = $j(this).attr('href');
			value = value.substring(value.indexOf('#')+1);

			if(value == 'default')
			{
				$j('.list_inactive').removeClass('list_inactive').addClass('list_active');
				$j('.gallery_active').removeClass('gallery_active').addClass('gallery_inactive');
			}
			else if (value == 'gallery')
			{
				$j('.gallery_inactive').removeClass('gallery_inactive').addClass('gallery_active');
				$j('.list_active').removeClass('list_active').addClass('list_inactive');
			}

			protom.centerColumn.params.display = value;
			protom.centerColumn.load();
			return false;
		});
	}
};

//***************************
// setup searchform
//***************************
protom.searchForm = {};

// setup basic events
protom.searchForm.setup = function()
{
	$j('#searchTerm').bind('focus', protom.searchForm.activate);
	$j('#searchTerm').bind('blur', protom.searchForm.deactivate);
};

// if input text is clicked
protom.searchForm.activate = function()
{
	if($j('#searchTerm').val() == 'suchen nach')
	{
		$j('#searchTerm').val('').css('color', 'black');
	}
};

// if input text looses focus
protom.searchForm.deactivate = function()
{
	if($j('#searchTerm').val() == '')
	{
		protom.searchForm.clear();
	}
};

// set input text to initial state
protom.searchForm.clear = function()
{
	$j('#searchTerm').val('suchen nach').css('color', '#9c9e9f');
	protom.loadParams.searchTerm = '';
};

//***************************
// setup newsletter storno form
//***************************
protom.newsletter = {};
protom.newsletter.stornoForm = {
	'setup' : function()
	{
		$j('#newsletterStorno .magazineHidden').hide();
		$j('#newsletterStorno .platformHidden').hide();
		$j('#newsletterStorno .otherHidden').hide();
		$j('#newsletterStorno #abbestellen').hide();

		$j('#newsletterStorno #reason1').bind('change', function(){
			protom.newsletter.stornoForm.toggleSubmit();
		});

		$j('#newsletterStorno #reason2').bind('change', function(){
			$j('#newsletterStorno .magazineHidden').toggle('medium');
			protom.newsletter.stornoForm.toggleSubmit();
		});

		$j('#newsletterStorno #reason3').bind('change', function(){
			$j('#newsletterStorno .platformHidden').toggle('medium');
			protom.newsletter.stornoForm.toggleSubmit();
		});

		$j('#newsletterStorno #reason4').bind('change', function(){
			$j('#newsletterStorno .otherHidden').toggle('medium');
			protom.newsletter.stornoForm.toggleSubmit();
		});
	},

	'toggleSubmit' : function()
	{
		var checked = false;
		$j.each($j('#newsletterStorno input[type=checkbox]'), function()
		{
			if(this.checked)
			{
				checked = true;
			}
		});

		if(checked)
		{
			$j('#newsletterStorno #abbestellen').show();
		}
		else
		{
			$j('#newsletterStorno #abbestellen').hide();
		}
	}
};

//***************************
// setup article slideshow
//***************************
protom.articleSlideshow = {
	'currentPage' : 0,
	'totalPages' : 0,
	'timer' : '',
	'setup' : function()
	{
		var slideshow = this;
		$j('.slideButtons a').bind('click', function(event){
			slideshow.showPage(Number($j(this).text())-1);
			slideshow.stop();
			return false;
		}).each(function(){slideshow.totalPages++;});

		slideshow.showPage(0);
		slideshow.run();
	},

	'showPage' : function(page)
	{
		page = page%protom.articleSlideshow.totalPages;
		$j($j('#articleSlides li').hide()[page]).fadeIn('slow');
		$j($j('.slideButtons a').removeClass('active')[page]).addClass('active');
		protom.articleSlideshow.currentPage = page;
	},

	'run' : function()
	{
		protom.articleSlideshow.timer = setInterval('protom.articleSlideshow.showPage(protom.articleSlideshow.currentPage+1)', 4000);
	},

	'stop': function()
	{
		clearInterval(protom.articleSlideshow.timer);
	}

};

//***************************
// setup article paging
//***************************
protom.articlePaging = {

	'currentPage' : 0,
	'totalPages'  : 0,

	'setup' : function()
	{
		var pager = this;
		$j('.articlenav a').bind('click', function(event)
		{
			var href = $j(this).attr('href');
			pager.currentPage = pager.getRequestedPage(href);
			pager.showPage(pager.currentPage);
			pager.setupPreviousNextButtons();
			return false;
		});

		$j('.articlenav .articlePage').each(function(){pager.totalPages++});
		if(pager.totalPages > 1)
		{
			$j('.articlenav').show();
		}
		pager.showPage(1);
	},

	'setPage' : function(page)
	{
		var pager = this;
		pager.currentPage = page;
		pager.showPage(page);
		pager.setupPreviousNextButtons();
	},

	'setupPreviousNextButtons' : function()
	{
		var pager = this;

		if(pager.currentPage > 1){
			$j('.articlenav .articlePrevious').removeClass('inactive').attr('href', 'articlepage_'+(pager.currentPage-1));
		}
		else{
			$j('.articlenav .articlePrevious').addClass('inactive').attr('href', 'articlepage_1');
		}

		if(pager.totalPages >= pager.currentPage+1){
			$j('.articlenav .articleNext').removeClass('inactive').attr('href', 'articlepage_'+(pager.currentPage+1));
		}
		else{
			$j('.articlenav .articleNext').addClass('inactive').attr('href', 'articlepage_'+pager.totalPages);
		}
	},

	'getRequestedPage' : function(href)
	{
		var pager = this;
		var page = 1;

		page = Number(href.substring(href.indexOf('_')+1));

		if(page < 1)
		{
			page = 1;
		}
		else if(page > pager.totalPages)
		{
			page = pager.totalPages;
		}

		return page;
	},

	'showPage' : function(page)
	{
		page = page-1;
		if(page === 0){$j('.intro').removeClass('hidden');}
		else{$j('.intro').addClass('hidden');}

		$j('.subpage').addClass('hidden');
		$j($j('.subpage')[page]).removeClass('hidden');

		$j('.articlenav .articlePage').removeClass('thispage');
		$j($j('.articlenav .articlePage')[page]).addClass('thispage');

	}
};

protom.platformChooser = {
	'setup' : function()
	{
		$j('.platformchooser').hide();
		$j('#platformChooserToggle').bind('click', function(){
			$j('.platformchooser').slideToggle('medium');
			return false;
		});
	}
};

protom.specialTabs = function(){

	var setup = function()
	{
		setupTabButtons();
		showTab(0);
	}

	var showTab = function(index)
	{
		$j($j('.specialtab').hide()[index]).show();
		$j($j('.specialheader a').removeClass('active')[index]).addClass('active');
	}

	var setupTabButtons = function()
	{
		$j('.specialheader a').bind('click', function(){
			var index = $j(this).attr('href');
			index = Number(index.substring(index.indexOf('_')+1));
			showTab(index-1);
			return false;
		});
	}

	setup();
};

protom.companySearchForm = function()
{
	var baseUrl = '/default/datacomponent/getchildcategories/category/';
	var init = function()
	{
		$j('#category_1').bind('change', function(){
			loadOptions('category_2', this.value);
			loadOptions('category_3', 0);
		});
		$j('#category_2').bind('change', function(){
			loadOptions('category_3', this.value);
		});
	};

	var loadOptions = function(selectId, categoryId)
	{
		$j('#'+selectId).load(baseUrl + categoryId);
	};

	init();
};

//***************************
// setup deep linking
//***************************
$j.address.externalChange(function(){

	var deeplink = $j.address.value();

	// if deeplink to process
	if(deeplink && deeplink != '/')
	{
		if(deeplink.indexOf('articlepage') != -1)
		{
			// init article paging
			protom.articlePaging.setPage(protom.articlePaging.getRequestedPage(deeplink));
		}
		else if(deeplink.indexOf('listpage') != -1)
		{
			// init list paging
			protom.centerColumn.paginator.showPage(Number(deeplink.substring(deeplink.indexOf('_')+1)));
		}

	}
	else
	{
		// init standard views
		protom.articlePaging.setPage(1);
	}

});

//***************************
// banner rotator
//***************************
protom.bannerRotator =
{
	// configuration
	intervall : 5000,
	limit : 4,
	animSpeed : 1000,
	containerWidth: 720,
	// end configuration

	animTimer : '',
	items : '',
	timer : '',
	itemCount : 0,
	animating: false,

	load : function(url)
	{
		 $j('.hersteller .banneritems .items').load(url, null, protom.bannerRotator.init);
	},

	init : function()
	{
		protom.bannerRotator.items = $j('.hersteller .banneritems .items a').clone();
		protom.bannerRotator.setItems();

		if(protom.bannerRotator.items.length > protom.bannerRotator.limit && protom.bannerRotator.timer==='')
		{
			protom.bannerRotator.timer = setInterval('protom.bannerRotator.rotate()', protom.bannerRotator.intervall);
		}
	},

	rotate : function()
	{
		if(!protom.bannerRotator.animating)
		{
			var animIntervall = Math.ceil(protom.bannerRotator.animSpeed / 24);
			var speed = Math.ceil(protom.bannerRotator.containerWidth / animIntervall);
			protom.bannerRotator.animating = true;
			protom.bannerRotator.animTimer = setInterval('protom.bannerRotator.animate('+speed+')', animIntervall);
		}
	},

	animate : function(speed)
	{
		var pos = $j('.banneritems .items').css('left');
		pos = pos.substring(0, pos.indexOf('px'));
		var nextPos = Number(pos)-speed;

		if((nextPos * -1) < protom.bannerRotator.containerWidth )
		{
			$j('.banneritems .items').css('left', nextPos);
		}
		else
		{
			// hide old
			$j('.banneritems .items').css('left', 0);
			clearInterval(protom.bannerRotator.animTimer);
			protom.bannerRotator.animTimer = '';
			protom.bannerRotator.animating = false;
			protom.bannerRotator.setItems();
		}

	},

	setItems : function()
	{
		var total = (protom.bannerRotator.limit * 2);
		var count = 0;
		$j('.banneritems .items').empty();

		while(count < total)
		{
			var curitem = $j(protom.bannerRotator.items[protom.bannerRotator.itemCount%protom.bannerRotator.items.length]).clone();
			$j(curitem).attr('id', $j(curitem).attr('id') + protom.bannerRotator.itemCount);
			$j('.banneritems .items').append(curitem);
			protom.bannerRotator.itemCount ++;
			count++;
		}
		protom.bannerRotator.itemCount -= protom.bannerRotator.limit;
		$j('.hersteller .bannerLink').bind('click', protom.openBannerLink);
	}

};

//***************************
// special pager
//***************************
protom.specialPager =
{
	limit : 4,
	animSpeed : 1000,
	containerWidth: 680,
	specialObjects : {},

	/**
	 * initial setup on page load
	 */
	setup : function()
	{
		if(protom.specialPager.specialObjects)
		{
			for(var pane in protom.specialPager.specialObjects)
			{
				protom.specialPager.setupPane(pane);
			}
		}

	},

	/**
	 * setup a single pane
	 */
	setupPane : function(pane)
	{
		var containerId = pane + 'Pane';
		var paneObject = protom.specialPager.specialObjects[pane];

		paneObject.prevButton = $j('<p class="scrollbutton prevscroll"></p>').bind('click', function(){
			protom.specialPager.prevPage(pane);
		});
		$j('#'+containerId).parent().prepend(paneObject.prevButton);

		paneObject.nextButton = $j('<p class="scrollbutton nextscroll"></p>').bind('click', function(){
			protom.specialPager.nextPage(pane);
		});
		$j('#'+containerId).parent().prepend(paneObject.nextButton);

		protom.specialPager.setupButtons(paneObject);

	},

	setupButtons : function(paneObject)
	{
		if(paneObject.nextpage === '')
		{
			$j(paneObject.nextButton).removeClass('active');
		}
		else
		{
			$j(paneObject.nextButton).addClass('active');
		}
		if(paneObject.prevpage === '')
		{
			$j(paneObject.prevButton).removeClass('active');
		}
		else
		{
			$j(paneObject.prevButton).addClass('active');
		}

	},

	/**
	 * move to the next page, load it if it is currently not loaded
	 */
	nextPage :function(pane)
	{
		var paneObject = protom.specialPager.specialObjects[pane];
		if(paneObject.nextpage !== '')
		{
			$j('#'+pane+'Pane').load(paneObject.nextpage, function(){
				protom.specialPager.setupButtons(paneObject);
				$j('#specialLoader').hide();
			});
			$j('#specialLoader').show();
		}
	},

	/**
	 * move to the previous page if one exists
	 */
	prevPage :function(pane)
	{
		var paneObject = protom.specialPager.specialObjects[pane];
		if(paneObject.prevpage !== '')
		{
			$j('#'+pane+'Pane').load(paneObject.prevpage, function(){
				protom.specialPager.setupButtons(paneObject);
				$j('#specialLoader').hide();
			});
			$j('#specialLoader').show();
		}
	}
};

if($j)
{
	$j(document).ready(function()
	{
		
		
		protom.setupBannerLinks();
		protom.setupExternalLinks();
		protom.setupToggleBoxes();
		protom.centerColumn.setup();
		protom.centerColumn.contentChooser.setup();
		protom.searchForm.setup();
		
		protom.platformChooser.setup();
		protom.articlePaging.setup();
		
		protom.companySearchForm();
		protom.specialPager.setup();
	});
	
}