var ieCornerElements = '<span class="tr" unselectable="on"></span><span class="tl" unselectable="on"></span><span class="bl" unselectable="on"></span><span class="br" unselectable="on"></span>';
      
function updateForm(form) {
    $('p.required input', form).each(function(){
        if ($(this).val() != "") {
            $(this).parents('p').removeClass('error');
        }
    });
}

function checkForm(form){
    var error = 0;
    $('p.required input', form).each(function(){
        if ($(this).val() == "") {
            $(this).parents('p').addClass('error');
            error++;
        }
        else {
            $(this).parents('p').removeClass('error');
        }
        
    });
    return error;
}


function is_touch_device() {  
  try {  
    document.createEvent("TouchEvent");  
    return true;  
  } catch (e) {  
    return false;  
  }  
}


(function($){
    var cache = [];
    $.preLoadImages = function(){
        var args_len = arguments.length;
        for (var i = args_len; i--;) {
            var cacheImage = document.createElement('img');
            cacheImage.src = arguments[i];
            cache.push(cacheImage);
        }
    }
})(jQuery);
;

$.fn.outline = function(options, counters){
    var options = $.extend({}, $.fn.outline.defaults, options), counters = counters || [];
    
    this.each(function(){
        $(this).children('li').each(function(i){
            var ct = counters.concat([i + 1]);   
            if (counters.length) {  
                $('<span></span>').addClass(options.numberClass).text(ct.join('.') + ' ').prependTo(this);
            }
            $(this).children('ol').outline(options, ct);
        })
    });
    
    if (!counters.length) 
        this.addClass(options.processedClass)
}

$.fn.outline.defaults = {
    numberClass: 'pseudo-num',
    processedClass: 'pseudo-processed'
}

jQuery.fn.uniqueId = function(suffix, clobber){
    if (suffix == null) 
        suffix = "UniqueId";
    return this.each(function(){
        if (!this.id || clobber) 
            this.id = "n" + (++jQuery.fn.uniqueId.index) + suffix;
    });
};
jQuery.fn.uniqueId.index = 0;




$.fn.equalHeights = function(px){
    $(this).each(function(){
        var currentTallest = 0;
        $(this).children().each(function(i){
            if ($(this).height() > currentTallest) {
                currentTallest = $(this).height();
            }
        });
        if (!px || !Number.prototype.pxToEm) 
            currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
        // for ie6, set height since min-height isn't supported
        if ($.browser.msie && $.browser.version == 6.0) {
            $(this).children().css({
                'height': currentTallest
            });
        }
        $(this).children().css({
            'min-height': currentTallest
        });
    });
    return this;
};

$.fn.equalHeightsInner = function(px){
    $(this).each(function(){
        var currentTallest = 0;
        $(this).children().each(function(i){
            if ($(this).height() > currentTallest) {
                currentTallest = $(this).innerHeight();
            }
        });
        if (!px || !Number.prototype.pxToEm) 
            currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
        // for ie6, set height since min-height isn't supported
        if ($.browser.msie && $.browser.version == 6.0) {
            $(this).children().css({
                'height': currentTallest
            });
        }
        $(this).children().css({
            'min-height': currentTallest
        });
    });
    return this;
};



function accordion() {
	$('dl.accordion').each(function() {
		var con = this;
		$('dd',con).hide().click(function(){$('dt', con).removeClass('active').removeClass('sub-active');$(this).slideUp('fast');}); /*AMI 20110302*/		
		$('dt',this).each(function(index) {
			$(this).click(function(){
				if (!$(this).hasClass('active')) {
					$('dd', con).hide();
					$('dt', con).removeClass('active').removeClass('sub-active');
					$('dd:eq(' + index + ')', con).slideDown('fast');
					$(this).addClass('active');
					$('dt:eq(' + (index+1) + ')', con).addClass('sub-active');
				} else {
					$('dd:eq(' + index + ')', con).slideUp('fast');
					$(this).removeClass('active');
					$('dt', con).removeClass('active').removeClass('sub-active');
				}
			});
		});
		// $('dt:first',this).addClass('active');
		// $('dt:eq(1)',this).addClass('sub-active');
		// $('dd:first',this).show();
	});
}



function doMoreNews(parent) {
	var elm = $('.more-news a',parent);
	var cH = elm.height();
	cH = $(cH).toEm({
        scope: '.more-news span'
    });
    $('.more-news span',parent).height(cH);
}


function formFields() {
    /*@cc_on
     if(!$('button.submit').hasClass('added')) {
      $('button.submit').append(ieCornerElements).addClass('added');
     }
     if(!$('p.error-info').hasClass('added')) {
      $('p.error-info').append(ieCornerElements).addClass('added');
     }
    @*/
  $('span.form-field').each(function(){
    if(!$(this).hasClass('added')) {
      var elm = this;
      $('input,textarea',this).
        focus(function(){$(elm).addClass('focus');}).
        blur(function(){$(elm).removeClass('focus');});
      $(this).addClass('added');
      /*@cc_on
      $(elm).append(ieCornerElements);
      @*/
    }
  });
}

//$().ready(function() {

function init() {
	
  // for adding some css rules, just in case js is running...
    $('body').addClass('js-enabled');
    
    // scanning and preloading all images which can be 
    //viewed in an overlay 
    $('a.image-view').each(function(i){
        var cSrc = $(this).attr('href');
        jQuery.preLoadImages(cSrc);
    });
	

	accordion();
	formFields();
    
    // main navigation tab has rounded elements to 
	// second level-navigation, added by script, 
	// because ie retreives rounded border by script
    var f = $('#main-nav li.active a:eq(0)');
    if (f) {
        $(f).after('<div class="space-l"></div><div class="space-r"></div>');
    }
	
	/* adu */
	var f = $('#main-nav .second-level li.active_nosub a');
	if(f) {
		$(f).after('<span class="marker">&nbsp;</span>');
	}
    
	// elements in a row which should have the same height
    // $('#news, #company-news, .paging-list li').equalHeights(); /* MST 20110217 */  
	$('#news > li ,#company-news > li ').each(
		function(){
			var link = $('a',this);
			var s = (link.innerHeight() - link.height());
			var h = $(this).height()-s;
			h = h.pxToEm();
		
			if ($.browser.msie && $.browser.version == 6.0) {
	            link.css({
	                'height': h
	            });
	        }
			
			link.css({
            	'min-height': h
        	});
		
	});
    
	$('ul.teaser-list.eqh').each(function(){
        $(this).uniqueId().addClass('fixed-h');
        $('#' + this.id).equalHeights();
        var h = $('li:first', this).height()-50;
		if ($.browser.msie && $.browser.version == 6.0) {
            $('.teaser,.banner,.teaser-elm', this).css({
                'height': h
            });
        }
        $('.teaser,.banner,.teaser-elm', this).css({
            'min-height': h
        });
    });
    
	if ($('#company-news .more-news').size() > 0) {
       doMoreNews($('#company-news'));
    }
	
	if ($('#news .more-news').size() > 0) {
      doMoreNews($('#news'));
    }
    
	// ie only scripting for rounded corners on various 
	// content elements, a mixture of a classic four 
	// images solution and a jquery plugin building vml
	
	/* MRA 20110303 problem in ie with long programmes list - removed a.join */
	
    /*@cc_on
     $('#main-nav .first-level li, #main-nav .second-level, #main-nav .third-level span, .quotes blockquote, #main .programmes th a').append(ieCornerElements);
    // $('#main-nav > ul > li > a, .contact-teaser, .button-arrow span.button, .contact-teaser span span, a.join, form button.submit').corner();
     $('#main-nav > ul > li > a, .contact-teaser, .button-arrow span.button, .contact-teaser span span, form button.submit, .btn-teaser span.button').corner();
     $('.pager span').corner({radius: 5});
     $('.pager a span').mouseover(function() {     
  		$(this).find('div:first').css('background', '#F39300');
  		$(this).find('div div div:last-child').css('background', '#F39300');
  		$(this).find('div div div div').css('background', '#F39300');
  	}).mouseout(function(){
  		$(this).find('div:first').css('background', '#282828');
  		$(this).find('div div div:last-child').css('background', '#282828');
    	$(this).find('div div div div').css('background', '#282828');
  	});
     @*/
    
	// inline labels for forms, might be a bit more specified (only login)?
	$("#login form fieldset label").show();
    $("#login label").inFieldLabels();
    
    
    
	// handling the quotes elements (navigation and display) 
    $('ul.quotes').each(function(){
        var quotes = $('li', this).size();
        if (quotes > 1) {
            $(this).wrap('<div class="quotes-box"></div>');
            var parent = $(this).parent();
            if ($(this).hasClass('fl')) {
                $(parent).addClass('fl');
                $(this).removeClass('fl');
            }
            else 
                if ($(this).hasClass('fr')) {
                    $(parent).addClass('fr');
                    $(this).removeClass('fr'); /* MRA 20110207 - changed 'fl' to 'fr' */
                }
            var w = $('li:last',this).width();    
            $('li:gt(0)', this).hide();
            //$('li:eq(0)', this).css({'width':w}); // LLA 20110714
            $(parent).css({
                'position': 'relative'
            });
            var nav = "";
            for (var i = 0; i < quotes; i++) {
                nav += '<li rel="' + i + '"><span>' + (i + 1) + '</span></li>';
            }
            $('<ul class="quotes-nav">' + nav + '</ul>').appendTo(parent);
            $('.quotes-nav li:eq(0)', parent).addClass('active');
            $('.quotes-nav li', parent).click(function(){
                var c = $(this).attr('rel');
                $('ul.quotes li', parent).hide();
                $('ul.quotes li:eq(' + c + ')', parent).show();
                $('.quotes-nav li', parent).removeClass('active');
                $(this).addClass('active');
            });
        }
    })
    
    function closeOverlay(){
        $('#bg-overlay').hide();
        $('#image-overlay').hide();
        $('#fo, #text-overlay').hide();
        $('#bg-overlay,#hoverclaim').hide();
        $('#nav-holder,#active-nav').remove();
        $('#start-nav').removeClass('hover');
    }
    
    $('a.image-view').click(function(){
        if ($('#bg-overlay').size() == 0) {
            $('<div id="bg-overlay"></div>').appendTo('body');
            $('#bg-overlay').click(closeOverlay);
        }
        if ($('#image-overlay').size() == 0) {
            $('<div id="image-overlay"><div id="image-overlay-box"><div id="image-view"></div><div id="image-text"></div><div class="overlay-close"><span>X</span></div></div></div>').appendTo('body');
            
        }
        var img = $(this).attr('href');
        var text = $(this).attr('title');
        $('#image-view').html('<img src="' + img + '" alt="' + text + '" />');
        $('#image-text').html('<p>' + text + '</p>');
        $('#bg-overlay').show();
        
        
        $('#image-view img').one('load', function(){
        	/*@cc_on
        		$('#image-overlay-box').removeCorners(); // MST 20110308
        	@*/
        	$('#image-overlay').removeAttr('style'); /* MST 20110308 */
            $('#image-overlay').show();
            var h = $('#image-overlay').height();
            var t = (h / 2) * -1;
            var w = $('#image-overlay').width();
            var l = (w / 2) * -1;
            /*@cc_on             
             $('#image-overlay-box').css({'height':h-40,'width':w-40});
             // if(!$('#image-overlay-box').hasClass('rounded')) { // MST 20110308
             	$('#image-overlay-box').corner({radius:20}).addClass('rounded');
             // } // MST 20110308
             @*/
            $('#image-overlay').css({
                'margin-top': t,
                'margin-left': l
            });
        }).attr('src', img).each(function(){
            if (this.complete) 
                $(this).trigger('load');
        });
        
        
        $('.overlay-close').click(closeOverlay);
        return false;
    });
    
    $('ul.bullets li').each(function() {
        if($('a',this).length > 0) {
          var href = $('a',this).attr('href');
          $(this).click(function(){location.href = href;});
          $(this).css({'cursor':'pointer'});
        }
    });
    
    $('a.contact, a.lBox').click(function(){
    	
       window.scrollTo(0, 0);
 	   if ($('#bg-overlay').size() == 0) {
           $('<div id="bg-overlay"></div>').appendTo('body');
           $('#bg-overlay').click(closeOverlay);
           
           if(is_touch_device()) {
		$('#bg-overlay').css('height', '300%'); /* fix for overlay breaking in mobile Safari */
	   }	
           		
      
			var src = $(this).attr('href');
            $('<div id="text-overlay"><div id="text-overlay-box"><div id="text-overlay-bt"></div><iframe src="'+src+'" id="fo" frameborder="0" scolling="no" allowTransparency="true" ></iframe><div class="overlay-close"><span>X</span></div></div></div>').appendTo('body');
			
			$('iframe#fo').load(function() {
				
				var $this = $(this);				
				var iFrameContent = $this.contents();			 
				$this.height(iFrameContent.height());
				iFrameContent.find('body').addClass('isLightbox');
				
				/* MST 20110309 */
				if (iFrameContent.find('#form_status').hasClass('success')) {
					$this.height(iFrameContent.find('#pop-wrapper').height());
					iFrameContent.find('h1:first').hide();
				}
				/* ************** */
				
				iFrameContent.find('select').change(function() { 				    	
					$this.height(iFrameContent.find('#pop-wrapper').height());
				});
				
				iFrameContent.find('.submitbutton').click(function() {					
					window.scrollTo(0,0);				
				});
				
			});

	   } else {	   
			$('#bg-overlay, #text-overlay, #fo').show();
	   }
 	   
 	  $('#text-overlay-box .overlay-close, a.closepop').click(closeOverlay);
        
        return false;
    });
    
   
    
    
    $('#lang').hide();
    var lang = "English";
    var ul = $('<ul></ul>').appendTo('#lang-choose');
    $('#lang option').each(function(){
        if (this.selected) {
            lang = $(this).text();
        }
        $('<li><a href="' + $(this).val() + '">' + $(this).text() + '</a></li>').appendTo(ul);
    });
    $('#lang-choose ul').before('<div id="lang-c"><span></span></div>'); /* MST 20110217 */
    $('#lang-choose ul').addClass('drop-down').hide();
	$('#lang-c').click(function(){
		/* MST 20110217 */
		if ($('#lang-choose').hasClass('active')) {
			$('#lang-choose').removeClass('active');
			$('#lang-choose ul').hide();
		} else {
			$('#lang-choose').addClass('active'); 
			$('#lang-choose ul').show();
		}
		/* ****************** */
	});
    $('#lang-c').prepend(lang); /* MST 20110217 */
    $('#lang-choose a').click(function(){    	
        $('#lang-c').html($(this).html());
        $('#lang-choose ul').hide();
        return false;
    });
    
    /* ADU 20110302 */
    // Clicking event off the element
    $('body').click(function(event) {
        if (!$(event.target).closest('#lang-choose').length) {
        	if ($('#lang-choose').hasClass('active')) {
    			$('#lang-choose').removeClass('active');
    			$('#lang-choose ul').hide();
        	}
        };
    });

	
	 /* adu  */
	$('#lang-choose select').attr("name", "uri_old");
	$("<input />").attr("type","hidden").attr("name", "uri").attr("id", "hidden_uri").appendTo("#lang-choose form");
		
	$('#lang-choose a').click(function() {
		$('#lang-c').html($(this).html());
		$('#lang-choose ul').hide();

		$("#hidden_uri").val($(this).attr("href"));
		$('#lang-choose select').change();
		return false;
	});
    
    /* carousel */
    $('.logo-carousel').each(function(){
        var size = $('li', this).size();
        if (size > 5) {
            $(this).wrap('<div class="carousel-container"><div class="carousel-box"></div></div>');
            var parent = $(this).parents('.carousel-container')[0];
            $('<div class="next"><div><span>&gt;</span></div></div>').uniqueId().appendTo(parent);
            $('<div class="prev"><div><span>&lt;</span></div></div>').uniqueId().appendTo(parent);
            var n = $('.next', parent)[0].id;
            var p = $('.prev', parent)[0].id;
            $(this).carouFredSel({
                auto: false,
                prev: "#" + p,
                next: "#" + n,
                scroll: 1
            });
            var cW = $('.caroufredsel_wrapper', parent).width();
            
        	/* MRA 20110221 correcting because of changes to margins in css */
			cW = $('.level-2').size()>0 ? cW-3 : cW-7.8;			
            
            cW = $(cW).toEm({
                scope: '.caroufredsel_wrapper'
            });
            $('.caroufredsel_wrapper', parent).width(cW);
        } else {		
			$(this).find('li:last img', 'li:last a').css({marginRight: '0px'}); /* logos centered; remove right margin of last logo */
		}
    });
    
	// nesting ordered lists for ie7, modern browsers using 
	// a pure css logic
	  if ($('#main ol').css('list-style-type') != 'none') {
        $('#main ol:not(ol ol)').each(function() {
          $('li:not(li li)',this).each(function(i){
              $(this).prepend('<span class="pseudo-num">' + (i + 1) + '.</span> ');
          });
          $(this).outline({},[]);
        });
        
    }
    $("#wrapper #main ol").css({'list-style-type': 'none'});
	
	 // Events page ADU
    $(".more.extendable").click(function(event) {	
		$(this).parent('p').hide().next().show();
			event.preventDefault();
		});
		
		$(".less.collapsable").click(function(event) {
			$(this).parent('p').hide().prev().show();
			event.preventDefault();
    });
    
    	/* workaround for browser auto-complete problem (In-Field Labels jQuery Plugin) - mst 20110323 // mst 20110406 // mst 20110504 // mst 20110512 */
	$('#username').focus(function(){
		pwd_field_value 			= $('#password').val();
		check_pwd_field_interval 	= window.setInterval("check_pwd_field()", 250);
		
		user_field_value			= $(this).val();		
		check_user_field_interval 	= window.setInterval("check_user_field()", 250);
	});
	$('#username').blur(function(){
		window.clearInterval(check_pwd_field_interval);
	});
	$('#password').focus(function(){
		if (check_pwd_field_keydown === false) {
			check_pwd_field();
		}		
	});
	$('#username').keydown(function(){
		check_user_field_keydown = true;
	});
	$('#password').keydown(function(){
		check_pwd_field_keydown = true;
	});
	/* ************************************** */

	// if a list comes up behind a text paragraph, reduce the margin between 
	$('.text-box .link-list').each(function(){
		$text_paragraph_before = $(this).parent().prev().find('.textParagraph'); 
		if ($text_paragraph_before.size() >= 1) {
			$text_paragraph_before.parent().addClass('less_margin');
		}
	});

	
	var current_tallest = 0;
	$('.teaser.greybox').each(function() {
		if($(this).height() > current_tallest) {
			current_tallest = $(this).height();
		}
		if(!Number.prototype.pxToEm) {
			current_tallest = current_tallest.pxToEm();
			//use ems unless px is specified
		}
	});
	// for ie6, set height since min-height isn't supported
	if($.browser.msie && $.browser.version == 6.0) {
		$('.teaser.greybox').css({
			'height' : current_tallest
		});
	}
	$('.teaser.greybox').css({
		'min-height' : current_tallest
	});
    
}

/* workaround for browser auto-complete problem (In-Field Labels jQuery Plugin) - mst 20110406 // mst 20110504 // mst 20110512 */
var pwd_field_value 			= '';
var check_pwd_field_interval	= false;
var check_pwd_field_keydown		= false;

function check_pwd_field() {	
	if (pwd_field_value != $('#password').val()) {
		$('#password').blur();
		window.clearInterval(check_pwd_field_interval);
	}
}

var user_field_value 			= '';
var check_user_field_interval	= false;
var check_user_field_keydown	= false;

function check_user_field() {	
	if (check_user_field_keydown === false) {
		if (user_field_value != $('#username').val()) {
			$('#username').blur();
			window.clearInterval(check_user_field_interval);
		}
	}
}
/* ************************************** */

var ffTimer = false;
var ffRetries = 0;
function start() {
	var ff = $('#wrapper').css('font-family');
	if(ff.indexOf('din-zanox-web-pro-1')!=-1 || ffRetries == 100) {
		if(ff.indexOf('din-zanox-web-pro-1')!=-1) {
			$('body').addClass('din');
		}
		init();
		if (typeof initStart == 'function') {
			initStart();
		}
		if (ffTimer) {
			clearTimeout(ffTimer)
		};
	} else {
		ffTimer = setTimeout('start()',1);
		ffRetries++;
	}	
}

$().ready(function(){
	if ($.browser.msie && ($.browser.version === "7.0" || $.browser.version === "8.0")) {
		var body = $(document.body),
			win = $(window);
		if (win.width() <= 1024) {
			body.addClass('page_small');
			body.css('font-size', '14px');
		} else {
			body.removeClass('page_small');
			body.css('font-size', '16px');
		};
	}	
	
	/* MST 20110908 */
	//start();	
	try {
		Typekit.load({
			active: function() {
				// Javascript to execute when fonts become active
				$('body').addClass('din');
				init();
				if (typeof initStart == 'function') {
					initStart();
				}
			}
		})
	} catch(e) {
		//console.log(e);
	}
	/* ******************** */

});
