var cufonUpdate = null;
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

jQuery.noConflict();
try {
  document.execCommand("BackgroundImageCache", false, true);
} catch(err) {

}
var time_out;
function hover_default_menu_2(){
  jQuery('.menu-2 .col:first-child img').show();
}
function hover_default_menu_1(){
  jQuery('.menu-1 .col:first-child img').show();
}
function hover_default_menu_4(){
  jQuery('.menu-4 .col:first-child img').show();
}
jQuery(document).ready(function($) {
	function setBodyClasses () {
		function case1 () {
		var product_wrapper = $('#product_wrapper');
			if(product_wrapper.length) {
				document.body.className = 'embed_breadcrumbs product_list_layout';
			}
		}
		case1();


		function case2 () {
			var product_list = $('.product_list');
			var intro = $('#intro');
			if(product_list.length&&(intro.length<1)) {
				document.body.className = 'embed_breadcrumbs product_list_layout';
			}
		}

		case2();

		$('body').addClass('js');
	}
	setBodyClasses();

	function mainMenuLists () {
		var main_menu_lists = $('.large_dropdown .main_menu_lists');
		if(!main_menu_lists.length) {return false}
		var tempHeight = 0;
		//alert(main_menu_lists.length);
		for(var i=0; i<main_menu_lists.length; i++) {
			tempHeight = $(main_menu_lists[i]).height() - 17;
			$(main_menu_lists[i]).parent().css('height',tempHeight);
		}
	}
	mainMenuLists();


	function mainMenuLists2 () {
		var main_menu_lists = $('.service_dropdown .main_menu_lists');
		if(!main_menu_lists.length) {return false}
		var tempHeight = 0;
		for(i=0; i<main_menu_lists.length; i++) {
			tempHeight = $(main_menu_lists[i]).height() - 13;
			$(main_menu_lists[i]).parent().css('height',tempHeight);
		}
	}
	mainMenuLists2();

	function adjustContent () {
		var dropdowns = $('#main_menu .dropdown');
		var dropdowns_height = [];
		var maxValue = 0;
		for(i=0; i<dropdowns.length; i++) {
			dropdowns_height.push($(dropdowns[i]).height());
		}
		for(i=0; i<dropdowns_height.length; i++) {
				if(dropdowns_height[i]>maxValue) {
					maxValue = dropdowns_height[i];
				}
		}
		maxValue+=100;
		if (typeof document.body.style.maxHeight != "undefined") {
			$('#content').css('min-height',maxValue);
		} else {
			$('#content').css('height',maxValue);
		}
	}
	adjustContent();

	function slidesInit () {

		var slides_list = $('#slides');
		if(slides_list.length) {
			var slides_list_li = $('#slides li');
			 if(slides_list_li.length<2) {return false}

			 var prev = $('<span class="carousel-control previous carousel-previous"><span>Prev</span></span>');
			var next = $('<span class="carousel-control next carousel-next"><span>Next</span></span>');
			$('#header').append(prev);
			$('#header').append(next);

			prev.css('display','none');
			next.css('display','none');
			next.css('visibility','visible');
			prev.css('visibility','visible');

			var slide_index = 0;

			function onAfter(curr, next, opts) {
				slide_index++;
				 if(slide_index==slides_list_li.length) {
					 opts.timeout = 0;
				 }
				  $('#header .previous').click(function () {
					opts.timeout = 0;
				 });
				 $('#header .next').click(function () {
					opts.timeout = 0;
				 });
			}

			$('#slides ul').cycle({
				fx: 'fade',
				timeout:  3000,
				speed: 1000,
				prev: '#header > .previous',
				next:  '#header > .next',
				after:   onAfter

			});

			var xx = [$('#slides ul').offset().left,$('#slides ul').offset().left+$('#slides ul').width()];
			var yy = [$('#slides ul').offset().top,$('#slides ul').offset().top+$('#slides ul').height()];
			var xlimit =  $('#slides ul').offset().left+$('#slides ul').width()/2;

			$(document.body).mousemove(
				function (event) {
					//start conditions
					if(event.pageX>=xx[0]&&event.pageX<=xx[1]&&event.pageY>=yy[0]&&event.pageY<=yy[1]&&slide_index>slides_list_li.length) {
						if(event.pageX<=xlimit) {
							$(next).fadeOut('slow');
							$(prev).fadeIn('slow');
						} else {
							$(next).fadeIn('slow');
							$(prev).fadeOut('slow');
						}
					} else {
							next.css('display','none');
							prev.css('display','none');
					}
					//end conditions
				}
			);
		}
	}
	slidesInit();

	Cufon.replace('#intro h1');
	Cufon.replace('#teaser strong');
	Cufon.replace('.news_title_middle');
	Cufon.replace('h4.gallery-title a');

	// andu
	Cufon.replace('#category_teaser .FCE_title');
	Cufon.replace('#extended-footer .subscribe-button');

	function teasersHeightAdjust() {

		var $categoryTeaser = $('#category_teaser');
		var $imgs = $categoryTeaser.find('img');

		function getOriginalDimension(img_element) {
		    var t = new Image();
		    t.src = (img_element.getAttribute ? img_element.getAttribute("src") : false) || img_element.src;
		    return { width: t.width, height: t.height }
		}


		$imgs.each(function() {
			var $this = $(this);
			var originalDimension = getOriginalDimension(this);
			//var initialWidth = ~~$this.attr('width'); // ~~ integer conversion
			//var initialHeight = ~~$this.attr('height');
			var currentWidth = $this.width();
			$this.height(originalDimension.height * currentWidth / originalDimension.width);
		});
	}

	//teasersHeightAdjust();

    $.fn.equalHeight = function() {

        var maxHeight = 0;
        this.each(function() {
            var height = $(this).height();
            if(height > maxHeight) {
                maxHeight = height;
            }
        });
        this.each(function() {
            $(this).height(maxHeight);
        });
        return this;
    }

    $.fn.placeholder = function(attribute) {

        attribute = attribute || 'title';

        this.each(function() {
            $this = $(this);
            $this.data('placeholder', $this.attr(attribute));
            $this.val($this.data('placeholder'));
            $this.removeAttr(attribute);
        });

        this.bind('focus', function() {
            var $this = $(this);
            if($this.val() == $this.data('placeholder')) {
                $this.val('');
            }
        });

        this.bind('blur', function() {
            var $this = $(this);
            if($this.val() == '') {
                $this.val($(this).data('placeholder'));
            }
        });

        return this;
    }

    $.unserialize = function(str) {
        var pieces = str.split('&');
        var object = {};
        for(i in pieces) {
            var attr = pieces[i].split('=');
            object[attr[0]] = attr[1];
        }
        return object;
    }


    function teaserVideos() {

    	var $teasers = $('#category_teaser > div');
    	var $videoTeasers = $teasers.filter(function() {
            var $this  = $(this);
            return $this.has('div.FCE_movie_details') && $this.children('.FCE_movie_details').text().indexOf('#') > 0;
        });

        $videoTeasers.wrap(function(index) {
            var $this = $(this);
            var attributes = $this.children('.FCE_movie_details').text().split('##');
            var videoParams = {
                url: attributes[0],
                width: attributes[1],
                height: attributes[2],
                image: attributes[3]
            }
            var wrap = $('<a class="modalvideolink"></a>').data('params', videoParams);

            return wrap;
        }).append('<span class="play-overlay"></span>');

        $videoTeasers.parents('a.modalvideolink').each(function() {

            var $this = $(this);
            var href = '#teaser'+Math.floor(Math.random()*1000);

            $this.attr('href', href);
            if($.browser.msie) {
                this.href = href;
            }
            var params = $this.data('params');
            params.url = unescape(params.url);

            var embed = "<object height='"+params.height+"' width='"+params.width+"' name='player' classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' id='player'>"+
                "<param value='/typo3conf/ext/hubachervideo/mediaplayer/player-licensed.swf' name='movie'>"+
				"<param value='true' name='allowfullscreen'>"+
				"<param value='always' name='allowscriptaccess'>"+
				"<param value='file=/"+params.url+"&amp;image=/uploads/pics/leer_14.png&amp;skin=/typo3conf/ext/hubachervideo/mediaplayer/glow.zip&amp;autostart=true' name='flashvars'>"+
				"<embed height='"+params.height+"' width='"+params.width+"' flashvars='file=/"+params.url+"&amp;image=/uploads/pics/leer_14.png&amp;skin=/typo3conf/ext/hubachervideo/mediaplayer/glow.zip&amp;autostart=true' allowfullscreen='true' allowscriptaccess='always' src='/typo3conf/ext/hubachervideo/mediaplayer/player-licensed.swf' name='player2' id='player2' type='application/x-shockwave-flash'>"+
			"</object>";
            $this.fancybox({
                frameWidth: params.width,
                frameHeight: params.height,
                padding: 10,
                overlayShow: true,
                overlayOpacity: 0.7,
                autoScale: false,
                titleShow: false,
                content: embed
            });
        });
    }

    function teaserFlash() {

        var $wrapper = $('#category_teaser');
        var $objects = $('object', $wrapper);
        var $embeds = $('embed', $wrapper);
        var $all = $objects.add($embeds);

        $objects.each(function() {
            var $this = $(this);
            var $parent = $this.parent();
            var $embed = $this.children('embed');
            var $param = $this.children('param[name=movie]');
            var url = $param.attr('value');

            if(!/^\//.test(url)) {
                url = '/' + url;
            }
            $param.attr('value', url);
            $embed.attr('src', url);

            var html = $parent.html();
            $parent.html('').html(html); // redundant, I know :)

        });

		var maskEdges = '<div class="mask-left"></div><div class="mask-right"></div><div class="mask-bottom"></div>';

		$wrapper.find('.full_width, .half_width, .quarter_width, .sixth_width').has('object').find('.FCE_data').replaceWith(maskEdges);
    }



    function hideEmptyTeasers() {

        $('#category_teaser li').each(function() {
            var $this = $(this);
            if($this.find('img').length == 0) {
                $this.css('display', 'none');
            }
        });
    }

    function ajustFooterColumnWidth() {
        var $footer_column_counter = $('#extended-footer .column-1  ul li').size();

        if ($footer_column_counter == 2) {
	  $('#extended-footer .column').css('width','130px');
	  $('#extended-footer .column-1').css('padding-right','0');
	}
    }

    $('#extended-footer .intro_middle > div').equalHeight();
    $('#newsletter-form input:text').placeholder();
    ajustFooterColumnWidth();
    teaserVideos();
    teaserFlash();
    hideEmptyTeasers();
    jQuery("#category_teaser a[href='']").addClass("empty_link").bind("click", function(){
		return false;
    });

	window.extensibleDropdown = function () {
		var extensible_dropdown = $('.extensible_dropdown');
		if(!extensible_dropdown.length) {return false}



		for(i=0; i<extensible_dropdown.length; i++) {
			var maxVal = 0;

			var news_title = $(extensible_dropdown[i]).find('.news_title');
			for(x=0; x<news_title.length; x++) {
				if(maxVal<$(news_title[x]).width()) {
					maxVal=$(news_title[x]).width();
				}
			}
			if(isIE){
			 maxVal = maxVal + 27;
			 maxVal1 = maxVal - 35;
			}else{
			  maxVal = maxVal + 18;
			  maxVal1 = maxVal - 35;
			}
			$(extensible_dropdown[i]).find('.news_lists dd').css('width',(maxVal));
			$(extensible_dropdown[i]).find('.news_lists dd .news_content').css('max-width',(maxVal1));
			var tempVal = 0;
			var news_title_middle =  $(extensible_dropdown[i]).find('.news_title_middle');
			for(x=0; x<news_title_middle.length; x++) {
				if(tempVal<$(news_title_middle[x]).width()) {
					tempVal=$(news_title_middle[x]).width();
				}
			}

			news_title_middle.css('width',tempVal);
			$(extensible_dropdown[i]).find('.ddm .a').css('height',$(extensible_dropdown[i]).find('.ddm').height());
			$(extensible_dropdown[i]).find('.ddm .c').css('height',$(extensible_dropdown[i]).find('.ddm').height());
			if(maxVal>351) {
				var finalWidth = maxVal + 157;
				$(extensible_dropdown[i]).css('width',finalWidth);
				//var tempWidth = maxVal  - 25;
				//console.log(tempWidth);
				//$(extensible_dropdown[i]).find('.news_title_middle').css('width',tempWidth);
			}
		}
	}
	cufonUpdate = window.setTimeout('extensibleDropdown()', 30);
	if(typeof $.fn.fancybox != 'undefined') {
		$('area').fancybox({
					frameWidth: 500,
					frameHeight: 400,
					padding: 10,
					overlayShow: true,
					overlayOpacity: 0.7,
					autoScale: false,
					titleShow: false
		});
	}

	$('.menu-2 .dropdown dl').hover (function() {
	    clearTimeout(time_out);
	    $(".menu-2 .col:first-child img").hide();
	  },
	  function(){
	    time_out = setTimeout("hover_default_menu_2()", 200);
          }
	);
	$('.menu-1 .dropdown dl').hover (function() {
	    clearTimeout(time_out);
	    $(".menu-1 .col:first-child img").hide();
	  },
	  function(){
	    time_out = setTimeout("hover_default_menu_1()", 200);
          }
	);
	$('.menu-4 .dropdown dl').hover (function() {
	    clearTimeout(time_out);
	    $(".menu-4 .col:first-child img").hide();
	  },
	  function(){
	    time_out = setTimeout("hover_default_menu_4()", 200);
          }
	);
});

