/*
    ALLIANZ JAVASCRIPT

    File: common.js
    Templates: H1, M1, M2, M3, M4, M5, C1a, C1b, C2, C3, C4, C5, L1, U1, U2, U3, F1, F2, F3, F4
    Date: 15 October 2010

*/

// DEFINE variables form the page
var currentTextSize = 100;
var minTextSize = 80;
var maxTextSize = 140;
var $contentBox = null;
var flapTabTimeout = null;
var sendToFriendLoaded = false;
var sendFeedbackLoaded = false;

$(document).ready(function(){
	
	$contentBox = $("#content .content-box");
	
	// on forms hide the default text on textarea
	$('textarea').each(function()
	{
		this.value = $(this).attr('defaultvalue');
		
		$(this).focus(function()
		{
			if(this.value == $(this).attr('defaultvalue')) this.value = '';
		});
	 
		$(this).blur(function()
		{
			if(this.value == '') this.value = $(this).attr('defaultvalue');
		});
	});
	
	//display tools
	$('.tools').show();		
	
	if (!isMobile ())
	{
		$(function(){
			 $('select.selectmenu').selectmenu({width: 303, maxHeight: 350, menuWidth: 300, style: 'dropdown'});
		});
	}
	
	var bttOffset = $('p.back-to-top:last').offset();
	// hide back to top if last back to top link is visible within inital viewport
	if( bttOffset != null && ($(window).height() > bttOffset.top ) ){
		$('p.back-to-top').hide();
	}
	
	//
	// BINDINGS
	//
	// Bind the hashchange event.
	/*$(window).hashchange( function(){
		// Alerts every time the hash changes
		var stepClass = window.location.hash.toString();
		changeStep(stepClass);
	});*/
	
	// setup continue buttons for accordion forms
	$('.form-list a.continue').click(function(){
		// get step class
		var stepClass = $(this).attr("href");
		
		//set hash
		window.location.hash = stepClass;
		
		// hashchange triggers function call above
		// stop link
		return false;
	});
	
	// bind tools to functions
	$('.tools a.print').click(function(){ window.print(); return false; });
	$('.tools a.decrease-text').click(function(){ changeTextSize(-10); return false; });
	$('.tools a.increase-text').click(function(){ changeTextSize(10); return false; });
	
	// Forms loaded by AJAX - target specified in HTML
	$('.tools a.friend').colorbox({ width: 530, height: 620, iframe:true, onComplete: function(){ 
		$('#pp-container').hover(function(){ $("#pp-link").addClass('over'); }, function(){ $("#pp-link").removeClass('over'); });} 
	});
	$('.tools a.feedback').colorbox({ width: 510, height: 550, iframe:true, onComplete: function(){ 
		$('#pp-container').hover(function(){ $("#pp-link").addClass('over'); }, function(){ $("#pp-link").removeClass('over'); });} 
	});
	
	$('.tools a.share').colorbox({ width: 550, height: 550, iframe:true, overlayClose: false, onComplete: function(){ 
		$('#pp-container').hover(function(){ $("#pp-link").addClass('over'); }, function(){ $("#pp-link").removeClass('over'); });} 
	});
	
	// Bind colorbox to privacy popup links
	$('a.privacy-popup').colorbox({ width: 510, height: 550 });
	
	//
	// close all flaps, except first one
	//
	$('.flap-btn').each(function(i){
		// get flap ID
		var flapID = $(this).attr("id").replace('-btn','');

		// get the parent ".collapser" div so we make sure we are always doing actions on THIS flap
		var parent = $(this).parent ().parent ().parent ();
		
		
		var forceclose = false;
		if ($ (this).hasClass ("flap-hidden"))
			forceclose = true;
		
		// keep open: force a tab to stay open :)
		var keep_open = false;
		if ($ (this).hasClass ("keep-open"))
			keep_open = true;
		
		// if > 0, i.e. not the first item hide it
		if (i>0 && !keep_open)
		{
			$ (this).removeClass ('flap-down');
			$ (this).addClass ('flap-hidden');
			$ (parent).find ('#'+flapID+'-box').hide();
		}

		if (forceclose)
		{
			if ($ (this).hasClass ("flap-down")) $ (this).removeClass ('flap-down');
			if (!$ (this).hasClass ("flap-hidden")) $ (this).addClass ('flap-hidden');
			$ (parent).find ('#'+flapID+'-box').hide();
		}

		
		// bind click
		$(this).click(function()
		{
			// toggle display of content flap in THIS .collapser span only!!
			$ (parent).find ('#'+flapID+'-box').toggle("fast");	
			$(this).toggleClass("flap-hidden");	
			
			// reload the google maps if any
			if (typeof (initialize) != "undefined")
				initialize();
			
			return false;
		});
	});
	
	// left tabs
	// flap tab li
	$("#flap-tabs>ul>li").hover(
		function(){
			setFlapTab($(this),false);
		}, function(){
			clearTimeout(flapTabTimeout);
		}
	);
	$("#flap-tabs>ul>li>a").click(function(){ setFlapTab($(this).parent(),true); return false; });
	
	var maxFlapTabHeight = 0;
	// get flap-tab heights
	$("#flap-tabs>ul>li>ul>li").each(function(){
		maxFlapTabHeight = ($(this).height() > maxFlapTabHeight) ? $(this).height() : maxFlapTabHeight;
		//console.log($(this).height());
	});
	// set overall height to tallest
	$("#flap-tabs>ul, #flap-tabs>ul>li>ul>li").css("height",maxFlapTabHeight+"px");
	
	// Look for content text size cookie
	/*if($.cookie("textSize")){
		var textSize = $.cookie("textSize");
		//set text size to size specified in cookie
		changeTextSize(textSize-currentTextSize);
	}*/
	
	if(!DetectMobileQuick()){
		var maxFlapTabHeight = 0;
		// get flap-tab heights
		$("#flap-tabs>ul>li>ul>li").each(function(){
			maxFlapTabHeight = ($(this).height() > maxFlapTabHeight) ? $(this).height() : maxFlapTabHeight;
		});
		// set overall height to tallest
		$("#flap-tabs>ul, #flap-tabs>ul>li>ul>li").css("height",maxFlapTabHeight+"px");
	}
	
	// Clear default values from a form when it is submitted, prior to triggering validation
	$("form").submit(function(){
		//clear default values from freetext input fields
		$(this).find("input[type='text'], textarea").each(function(){
			if($(this).val() == this.defaultValue)	{
				$(this).val('');
			}
		});
				
		// validate form here
	});

	//keep parent highlight on main nav
	$("#main-nav>li>ul").hover(function(){
		// apply over class	
		$(this).parent("li").addClass("over");
   	}, function() {
	   // remove over class
		$(this).parent("li").removeClass("over");
   	});
	
	// fix z-indexing
	$("#top-nav li.toplink-language a").hover(function(){
													   		$(this).parent("li").css("z-index","99");
													   }, function(){
														   $(this).parent("li").css("z-index","11");
														   $("#top-nav li.toplink-websites").css("z-index","12");
													   });
	$("#top-nav li.toplink-websites a").hover(function(){
													   		$(this).parent("li").css("z-index","99");
													   }, function(){
														   $(this).parent("li").css("z-index","11");
														   $("#top-nav li.toplink-language").css("z-index","12");
													   });

	/***
		* TRIGGER EVENTS
	***/
		  
	// Trigger the event (useful on page load).
	$(window).hashchange();
});

/**
 *	isMobile ()
 * 	Detect if we are runnign on a mobiel device or not
 *	by simply looking at which stylesheet is loaded
 */
function isMobile ()
{
	// just look at the value of the background image, on mobiles we use a special one
	var controlValue = $ ("body").css ("background-image");
	if (controlValue.indexOf ("mobile-head-bg.png") > 0) return true;
	else return false;
}


/**
 * loadCss()
 */
function loadCss (path, type)
{
	// go find the /root folder, so it works with /corporate, /entreprise, /biznes, etc
	var href = document.getElementsByTagName("head")[0].getElementsByTagName("link") [0].href;
	var root = href.split ("/") [3];
	
	var fileref = document.createElement('link');
	fileref.setAttribute ("rel","stylesheet");
	fileref.setAttribute ("type", "text/css");
	fileref.setAttribute ("media", type);
	fileref.setAttribute ("href", "/" + root + "/images/" + path + ".css");
	if (typeof fileref != "undefined")
		document.getElementsByTagName("head")[0].appendChild (fileref);
}

// force CSS screen for old FIrefox versions (force for < 1.9.1.0 (1.9.0.19 requires it))
var v_i = $.browser.version.substr(0,3);	// 1.9
var v_ii = $.browser.version.substr(4,5);	// (1.9.)2.3
if ($.browser.mozilla && (v_i < 1.9 || (v_i == "1.9" && v_ii < 1)))
{
	loadCss ("type", "screen");
	loadCss ("layout", "screen");
	loadCss ("grid", "screen");
	loadCss ("colorbox", "screen");
	loadCss ("jquery-ui", "screen");
	loadCss ("ui.selectmenu", "screen");
	loadCss ("print", "print");
	
	// if not homepage load the cotnent-page css
	var p = window.location.pathname.split ("/");
	if (p.length > 3) loadCss ("content-pages", "screen");
}

function setFlapTab($target, immediate){
	
	var delay = (immediate) ? 0 : 500;
	
	clearTimeout(flapTabTimeout);
	
	flapTabTimeout = setTimeout(function(){
		
		// get the parent ul of this li
		var parent_ul = $ ($target).parent ();
		
		// remove all active classes ONLY on the childs of the parent ul
		$(parent_ul).find ("li").removeClass("active");
		
		// add to target
		$target.addClass("active");
										 
	}, delay);
	
}

function changeTextSize(increment) {
	currentTextSize += increment;
	currentTextSize = (currentTextSize<minTextSize) ? minTextSize : ((currentTextSize>maxTextSize) ? maxTextSize : currentTextSize);

	$contentBox.css("font-size", currentTextSize+"%");
	//$.cookie("textSize",currentTextSize);
}

	
function changeStep(stepClass){
	
	/*var gotoStep = stepClass.replace('#step','');
	
	gotoStep = (gotoStep == '') ? 1 : gotoStep;
		
	if($('#flap'+gotoStep+'-btn').hasClass('flap-hidden')){
		
		// hide all flaps
		$('.flap').hide("fast");	
		$('.flap-btn').attr("class", "flap-btn flap-hidden");	
		
		// show relevant flap
		$('#flap'+gotoStep+'-box').show("fast");
		// toggle class on button
		$('#flap'+gotoStep+'-btn').toggleClass("flap-hidden");
	
	}*/
}


var bookmarkURL = encodeURIComponent(window.location); 
var bookmarkTitle = encodeURIComponent(document.title);

var bookmarks = new Array();
bookmarks["delicious"] = "http://del.icio.us/post?v=4&noui&jump=close&url=" + bookmarkURL + "&title=" + bookmarkTitle;
bookmarks["stumbleupon"] = "http://www.stumbleupon.com/submit?url=" + bookmarkURL + "&title=" + bookmarkTitle;
bookmarks["facebook"] = "http://www.facebook.com/sharer.php?u=" + bookmarkURL + "&t=" + bookmarkTitle;
bookmarks["digg"] = "http://digg.com/submit?phase=2&url=" + bookmarkURL + "&title=" + bookmarkTitle;
bookmarks["reddit"] = "http://www.reddit.com/submit?url=" + bookmarkURL + "&title=" + bookmarkTitle;
bookmarks["yahoo"] = "http://buzz.yahoo.com/submit/?submitUrl=" + bookmarkURL + "&submitHeadline=" + bookmarkTitle;
bookmarks["google"] = "http://www.google.com/buzz/post?url=" + bookmarkURL + "&title=" + bookmarkTitle;
bookmarks["twitter"] = "http://twitter.com/home?status=" + bookmarkURL + "&t=" + bookmarkTitle;
bookmarks["linkedin"] = "http://www.linkedin.com/shareArticle?mini=true&url=" + bookmarkURL + "&title=" + bookmarkTitle;
bookmarks["myspace"] = "http://www.myspace.com/index.cfm?fuseaction=postto&u=" + bookmarkURL + "&t=" + bookmarkTitle;
bookmarks["xing"] = "http://www.xing.com/app/user?op=share_add;url=" + bookmarkURL + ";title=" + bookmarkTitle;

function bookmark(site){
		
	var winFeatures = 'location=0, statusbar=0, menubar=0, width=700, height=400, scrollbars=0, resizable=1';
	
	var theWindow = window.open(bookmarks[site], "_blank", winFeatures);
	theWindow.focus();
	return false;
	
}

/**
 *	dropDown_submit ()
 *	Submit a onchange dropdown event
 */
function dropDown_submit (select_node, form_id) {
	// get the selected value
	var value = select_node.options [select_node.selectedIndex].value; 
	
	// check that we're not on the first element
	if (select_node.selectedIndex != 0) 
	{	
		document.getElementById (form_id).action = value;
		document.getElementById (form_id).submit();
		// open the link in a new window
		//window.open(value, '_blank');
	}
}
