/**
 * General Functions
 *
 * @copyright       Copyright 2009, Deutscher Ring
 * @link            http://www.deutscherring.de
 * @project         Internet
 * @author         	mediaman technology GmbH (http://www.mediaman.de)
 * @version         1.0
 * @revision        $Rev: 436 $
 * @lastmodified    $Date: 2009-09-21 15:42:22 +0200 (Mo, 21. Sep 2009) $
 */

var drJsEnabled = swfobject.getFlashPlayerVersion().major>=9;

//tb_pathToImage = $("link#drLbImageLoadingTb","head").attr("href");

//document ready methods
$(document).ready(function(){
	/***************** IE 6 - Ausnahmefunktionen ******************************/
	if ($.browser.msie && $.browser.version == 6) {
		$(".drPNG").remove();
		$(".drGIF").removeClass("drGIF").css("display","");
		// Fixing PNG Support for IE 5.5 + 6
		$(document).pngFix();
		
		// fixing hover bug for main navigation flyouts in IE6
		// by adding a table around each flyout
		var tableStart = '<table class="drBlindTable"><tr><td>';
		var tableEnd = '</td></tr></table>';
		if($('.drMainNavFlyout').get(0)){
			$('.drMainNavFlyout').each(function(){
				$(this).html(tableStart + $(this).html() + tableEnd);
			});
		}
		if($(".drHomeRingtones").get(0)){
			$(".drHomeRingtones > *").each(function(){
				$(this).html(tableStart + $(this).html() + tableEnd);
			});
		}
	} else {
		$(".drGIF").remove();
	}
	
	// hide flash fallback if no flash
	if (drJsEnabled){
		$(".drNoFlashFallback").remove();
		$(".drFlash").show();
	}

	
	// lightbox initializiation for content images
	$('a[rel~=lightbox]').lightBox({
		imageLoading:	$('#drLbImageLoading', 'head').attr('href'),
		imageBtnClose:	$('#drLbImageBtnClose', 'head').attr('href'),
		imageBtnPrev:	'',
		imageBtnNext:	'',
		imageBlank:		''
	});
	
	// hover effect for close button in lightbox
	$('#lightbox-secNav-btnClose').live('mouseover', function(){
		drImgSwitch($('img', $(this)), 'over');
	});
	$('#lightbox-secNav-btnClose').live('mouseout', function(){
		drImgSwitch($('img', $(this)), 'out');
	});

	// image switcher for ringwelt visual
	if($('div.drRwArticleBox').get(0))
	{
		$('div.drButton','div.drRwArticleBox').mouseover(function(){
			if(!$(this).hasClass('drActive'))
			{
				var selectedClass = $(this).attr('class').match(/\b(drItem[0-9]+)\b/)[1];
				$('div.drButton','div.drRwArticleBox').removeClass('drActive');
				$('div.drImage','div.drRwArticleBox').removeClass('drActive');
				
				$('.' + selectedClass,'div.drRwArticleBox').addClass('drActive');
			}
			return false;
		});
	}
	
	// Rollover for i.e. arrow buttons and link arrows
	if ($(".drImageMouseover").get(0))
	{
		$(".drImageMouseover").mouseover(function(){
			drImgSwitch($("img",this),"over");
		});
		$(".drImageMouseover").mouseout(function(){
			drImgSwitch($("img",this),"out");
		});
	}
	
	if($(".drFlashAudio").get(0))
	{
		var flashBoxId="#drHomeFlashBox";
		var audioOn=".drFlashAudio .drAudioOn";
		var audioOff=".drFlashAudio .drAudioOff";
		var audioAjaxRequest='/application/preferences/save.html?soundState=';

		if($(flashBoxId).get(0)){
			$(audioOff).toggleClass("drHide",drHomeFlashStartSound);
			$(audioOn).toggleClass("drHide",!drHomeFlashStartSound);
		} else {
			$(audioOff).addClass("drHide");
			$(audioOn).addClass("drHide");
		}
		function getFlashBoxSoundState(flashBoxId){
			if($(flashBoxId).get(0)){
				return $(flashBoxId).get(0).soundStatus();
			} else {
				return false;
			}
		}
		function drFlashAudioUpdate(flashBoxId) {
			var soundeStatus=getFlashBoxSoundState(flashBoxId);
			$.get(audioAjaxRequest+ (soundeStatus?'true':'false'));
			if ($(audioOff).get(0))	{	$(audioOff).toggleClass("drHide",soundeStatus);	}
			if ($(audioOn).get(0))	{	$(audioOn).toggleClass("drHide",!soundeStatus);	}
		}
		$(audioOff+" a").click(function(){
			$(flashBoxId).get(0).playSound(true);
			drFlashAudioUpdate(flashBoxId);
			return false;
		})
		$(audioOn+" a").click(function(){
			getFlashBoxSoundState(flashBoxId);
			$(flashBoxId).get(0).playSound(false);
			drFlashAudioUpdate(flashBoxId);
			return false;
		})
	}
	
	if($(".drHomeProfileSwitcher .drProfileSwitch a").get(0))
	{	
		$(".drHomeProfileSwitcher .drProfileSwitch a").click(function(){
			$(".drHomeProfiles > div").removeClass("drSel");
			$("."+$(this).attr("rel")+" > div").addClass("drSel");
			return false;
		});
	}
	
	//header main navigation rollovers and flyout

	// Timer Construct for Flyouts and closing etc.
	var tmr=0;
	var flyOutObj;
	var menuObj;
	function activateTimer(obj,state,obj2,state2)
	{
		tmr=window.setTimeout(function()
		{
			if (state==0) obj.hide();
			else if (state==1) obj.show();
			if (state2==0) obj2.removeClass('drOver');
			else if (state2==1) obj2.addClass('drOver');
		},100);
	}
	function eliminateTimer()
	{
        window.clearTimeout(tmr);
        tmr=null;
	}
	
	
	if ($(".drMainNavigation a").get(0))
	{
		$(".drMainNavigation a").mouseenter(function(){
			var rightEnd=$("body").width();

			flyObj="#drNavFlyout"+($(".drMainNavigation a").index(this)+1);
			fontSize=$("body").css("font-size").match(/[0-9.]*/);
			$(flyObj).css("top",(($(this).offset().top/fontSize)+2)+"em");
			$(flyObj).css("left",($(this).offset().left/fontSize)+"em");
			
			
			// min width for flyout is the width of the hovered menu item
			if($(flyObj).outerWidth() < $(this).width())
			{
				$(flyObj+" > ul").css('width', $(this).width()+"px");
				
				// is there a table appended to the flyout
				// i.e. are we browsing the website in IE6?
				if($('table', $(flyObj)).get(0))
				{
					$('table', $(flyObj)).css('width', $(this).width()+"px");
				}
			}
			
			flyOutWidth=$(flyObj).outerWidth();
			
			flyOutLeftDistance=$(this).offset().left;
			flyOutRightEnd=flyOutWidth+flyOutLeftDistance;
			
			if (flyOutRightEnd>rightEnd)
			{
				flyDiff=$(this).offset().left+$(this).outerWidth()-flyOutWidth;
				$(flyObj).css("left",((flyDiff)/fontSize)+"em");
			}
			flyOutObj=$(flyObj);
			menuObj=$(this);
			activateTimer(flyOutObj,1,menuObj,1);
		});
		$(".drMainNavFlyout, .drMainNavigation a").mouseleave(function(){
			flyObj="#drNavFlyout"+($(".drMainNavigation a").index(this)+1);
			activateTimer(flyOutObj,0,menuObj,0);
		});
	}

	if ($(".drMainNavFlyout").get(0))
	{
		$(".drMainNavFlyout").mouseover(function(){
			eliminateTimer();											 
		});
		$(".drMainNavFlyout").mouseleave(function(){
			activateTimer(flyOutObj,0,menuObj,0);
		});
	}
	
	//notepad link
	if ($("#drLnkHdrNotePad,#drLnkToolboxNotePad").get(0))
	{
		$("#drLnkHdrNotePad,#drLnkToolboxNotePad").click(function(){
			drOpenPopup($(this).attr("href"), "NotepadPopup", 550, 450, "top=300,left=400,resizable=no,toolbar=no,dependent=no,menubar=no,location=no,status=no,scrollbars=yes,resizable=yes");
			return false;
		});
	}
	
	if($('div.drScroller').get(0))
	{
		var $awards = $('div.drScroller');
		$awards.smoothDivScroll({
			scrollingSpeed: 2,
			scrollingHotSpotLeft: "a.prevPage",
			scrollingHotSpotRight: "a.nextPage",
			scrollableArea: "div.items",
			scrollWrapper: "div.scrollable",
			autoScroll: "",
			visibleHotSpots: "always",
			autoScrollSpeed: 1,
			mouseDownSpeedBooster: 3
		});
		
		$("#infinite div.items img").hover(
			function(){ $(this).fadeTo("fast", 1); },
			function(){ $(this).fadeTo("fast", 0.5); }
		);
		
		$(".drScroller .prevPage,.drScroller .nextPage").hover(
			function(){ drImgSwitch($("img",this),"over"); },
			function(){ drImgSwitch($("img",this),"out"); }
		);
	}
	
	
	//product switch list
	if ($(".drSwitchList > .drSwitchListItem .drSwitchListHeadline").get(0))
	{
		$(".drSwitchList > .drSwitchListItem .drSwitchListHeadline").click(function(){
			if ($(this).parents(".drSwitchListItem").hasClass("opened"))
			{
				$("div.drSwitchListContent",$(this).parents(".drSwitchListItem")).slideUp("fast");
				$(this).parents(".drSwitchListItem").removeClass("opened");											
			}
			else
			{
				$(".drSwitchList > .drSwitchListItem .drSwitchListHeadline").each(function(){
					$("div.drSwitchListContent",$(this).parents(".drSwitchListItem")).slideUp("fast");
					$(this).parents(".drSwitchListItem").removeClass("opened");
				});
				$("div.drSwitchListContent",$(this).parents(".drSwitchListItem")).slideDown("fast");
				$(this).parents(".drSwitchListItem").addClass("opened");														
			}
		});
	}
	
	//drRwFrequentReadForm
	if ($("#drRwToolsForm .drSubmitButton").get(0) && $("#drRwToolsFormSelTool").get(0))
	{
		$("#drRwToolsForm .drSubmitButton").click(function(){
			if($("#drRwToolsFormSelTool").val().match(/(\/.*)/)){
				$(this).attr("href",$("#drRwToolsFormSelTool").val());
			} else {
				return false;
			}
		});
	}
	
	//Ringtones-Flyout Homepage
	if($(".drHomeRingtones").get(0)){
		$(".drHomeRingtones").mouseenter(function(){
			$(".drHomeRingtones > div").toggle();
		});
		$(".drHomeRingtones").mouseleave(function(){
			$(".drHomeRingtones > div").toggle();
		});
	}
	
	//Text in Suchfeldern beim auswÃƒÂ¤hlen selektieren
	if($("input.drInputSelectText").get(0)){
		$("input.drInputSelectText").focus(function(){
				$(this).select();
		})
		$("input.drInputSelectText").blur(function(){
			if($(this).val()=="" && $("label[for="+$(this).attr('id')+"]")){
				$(this).val($("label[for="+$(this).attr('id')+"]").html());
			}
		})
	}
	
	// find tracking links and register a click event on them
	if($('a[rel=tracking]').get(0))
	{
		$('a[rel=tracking]').click(function(){
			var linkName = $(this).attr('name');
			TrackingManager.sendLinkEvent(linkName);
		});
	}
	
	// Emergengy Layer Close Buttons
	if($(".drCloseEmergency").get(0)){
		$(".drCloseEmergency").click(function(){
			$("#drEmergencyBG").remove();
			$("#drEmergencyBox").remove();
			return false;
		})
	}
	
	// Tooltip functions
	if($("a[title!='']").get(0)){
			$("a[title!='']").each(function(){
				$(this)
					.html($(this).html()+'<span class="drTooltipText">'+$(this).attr("title")+'</span>')
					.attr("title","")
					.addClass("drTooltip")
				;
			});
	}
	if($(".drTooltip").get(0)){
		function getTooltipText(obj){
			if($("span#"+obj.attr('id')+"Tooltip").get(0)){
				return $("span#"+obj.attr('id')+"Tooltip").html();
			}else if($(".drTooltipText",obj).get(0)){
				return $(".drTooltipText",obj).html();
			}else{
				return "";
			}
		}
		$(".drTooltip").mouseenter(function(e){
			var tooltipText=getTooltipText($(this));
			if(tooltipText!=""){
				$("#drTooltip .drText").html(tooltipText);
				$("#drTooltip")
					.css("top",0)
					.css("left",0)
					.hide()
				;
				offsetX=10;
				offsetY=10;
				additionalX=50;
				additionalY=10;
				tooltipX=$("#drTooltip").width();
				tooltipY=$("#drTooltip").height();
				htmlX=$("html").width();
				htmlY=$("html").height();
				if(e.pageX+tooltipX+additionalX>htmlX){
					posLeft=(e.pageX-tooltipX)+"px";
				}else{
					posLeft=(e.pageX+offsetX)+"px";
				}
				if(e.pageY+tooltipY+additionalY>htmlY){
					posTop=(e.pageY-tooltipY)+"px";
				}else{
					posTop=(e.pageY+offsetY)+"px";
				}
				$("#drTooltip")
					.css("top",posTop)
					.css("left",posLeft)
					.show()
				;
			}
		});
		$(".drTooltip").mouseleave(function(){
			$("#drTooltip").hide();
		});
	}
	
	
	// Tracking functionality
	// ring tone downloads
	if($('table.drHomeRingtonesTable', 'div.drHomeRingtones').get(0))
	{
		$('a.drLnkArr', 'table.drHomeRingtonesTable').each(function(){
			$(this).mousedown(function(){
				if('undefined' !== typeof drTrackingManager)
				{
					drTrackingManager.callAction('download', $(this).attr('rel') + '-Klingelton', 'Klingeltöne');
				}
				return false;
			});
		});
	}
	
	// Ringwelten area - main navigation
	if($('img.drNavImg[alt=RingWelten]').get(0))
	{
		$('img.drNavImg[alt=RingWelten]').parent().mousedown(function(){
			if('undefined' !== typeof drTrackingManager)
			{
				drTrackingManager.callAction('link', 'Navi - Ringwelten', 'Hauptnavigation');
			}
		});
	}
	
	
	// Ringwelten area - subnavigation
	if($('#drNavFlyout4').get(0))
	{
		$('ul', '#drNavFlyout4').find('a').each(function(){
			if('MeineRingWelt' !== $.trim($(this).text()))
			{
				$(this).mousedown(function(){
					if('undefined' !== typeof drTrackingManager)
					{
						drTrackingManager.callAction('link', 'Navi - ' + $.trim($(this).text()), 'Unternavigation');
					}
				});
			}
		});
	}
});


//modular rollover functions
function drImgSwitch($obj,state)
{
	if ($obj.attr("src") && (-1 == $obj.attr("src").indexOf('_i.')))
	{
		src=$obj.attr("src");
		var pathComponents= src.split('/');
		if(state == "over"){
			pathComponents[pathComponents.length-1] = pathComponents[pathComponents.length-1].replace(/\./, "_o.");
		}else{
			pathComponents[pathComponents.length-1] = pathComponents[pathComponents.length-1].replace(/_o\./, ".");
		}
		src = pathComponents.join('/');
		$obj.attr("src", src);
	}
}

//font size changer
function drFontSizeChange(mode)
{
	var sizeUnit="px";
	var sizeMin=0;
	var sizeDefault=16;
	var sizeMax=10000;
	var sizeStep=2;
	var sizeCurrent;
	var sizeAjaxRequest='/application/preferences/save.html?baseFontSize=';

	if($("body").css("font-size"))	{sizeCurrent=$("body").css("font-size").match(/[0-9.]*/)*1;}
	else							{sizeCurrent=sizeDefault;}

	if(mode=="bigger")				{if(sizeCurrent+sizeStep<=sizeMax) sizeCurrent+=sizeStep;}
	else if(mode=="smaller")		{if(sizeCurrent-sizeStep>=sizeMin) sizeCurrent-=sizeStep;}
	else							{sizeCurrent=sizeDefault;}

	$.get(sizeAjaxRequest+sizeCurrent+sizeUnit);
	$("body").css("font-size",sizeCurrent+sizeUnit);
}


// opens a popup window 
var drCurrentPopWnd = null;
function drOpenPopup(pURL, wndName, width, height, arguments) 
{	
	if(!arguments || ("" == arguments)) arguments = ",resizable=no,toolbar=no,dependent=no,menubar=no,location=no,status=no,scrollbars=yes";
	else arguments += "status=no,scrollbars=yes";
	if(drCurrentPopWnd) drCurrentPopWnd.close();
	drCurrentPopWnd =  window.open(pURL, wndName, "width=" + width + ",height=" + height + arguments);
	drCurrentPopWnd.focus();
}

// selects a broker in the search result list and sends a request to server
function drBrokerSearchSelection(brokerId, saveBrokerUrl)
{
	$(".drPartnerDetails .drSel").removeClass("drSel");	
	$("#drPartnerItem" + brokerId).addClass("drSel");
	$.get(saveBrokerUrl);
}

// Absoluten aus relativem Pfad berechnen
function absPath(url){
	var Loc = location.href;
	Loc = Loc.substring(0, Loc.lastIndexOf('/'));
	while (/^\.\./.test(url)){
		Loc = Loc.substring(0, Loc.lastIndexOf('/'));
		url= url.substring(3);
	}
	return Loc + '/' + url;
}

function getParameterByName( name ) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}


// Base Methods for reading Json Values, see drSitemap for details
var jJSON={
	getValue:function(obj,num) 
	{
		return jJSON[obj]["values"][num];
	},
	getValues:function(obj,num) 
	{
		return jJSON[obj]["values"].slice(0,((num == null) ? jJSON[obj]["values"].length : num));
	},
	getCount: function(obj) 
	{
		return jJSON[obj]["count"];
	}
};	
