/*
This is the main js file with most of the functionality
*/

 // activate MainMenu
 function activateMenu(level1ItemOverlayHelper) {
 	$("li.level1Item").each(function(){
			//$(this).addClass("inactive");
			$(this).children("div.logooverlayhelper").removeClass("menuOn");
	})
	level1ItemOverlayHelper.addClass("menuOn");
	//$(level1ItemOverlayHelper).parent("li.level1Item").removeClass("inactive");
}

// deactivate MainMenu
function deactivateMenu(level1ItemOverlayHelper) {
	$("li.level1Item").each(function(){
			//$(this).removeClass("inactive");
			$(this).children("div.logooverlayhelper").removeClass("menuOn");
	})
		level1ItemOverlayHelper.removeClass("menuOn");
		clearTimeout(Mairs.menutimer);
		Mairs.menutimer = 0;
}
// deactivate MainMenu
function deactivateMenuAll() {
		clearTimeout(Mairs.menutimer);
		Mairs.menutimer = 0;
		$("li.level1Item").each(function(){
		//	$(this).removeClass("inactive");
			$(this).children("div.logooverlayhelper").removeClass("menuOn");
		})
}

var Mairs = new Array();
Mairs.menutimer = 0;
Mairs.menutimerReduceFlicker = 0;
 
 
 
 
 
 
 // document ready -------------------------------------------------------------------------
 // document ready -------------------------------------------------------------------------
 // document ready -------------------------------------------------------------------------
 // document ready -------------------------------------------------------------------------
 // document ready -------------------------------------------------------------------------
 // document ready -------------------------------------------------------------------------
 // document ready -------------------------------------------------------------------------
 // document ready -------------------------------------------------------------------------
 jQuery(document).ready(function() {
              
// greying out when hover menu with #blurrer++++++++++++++++++++++++++++++++++++++++++
// calc size of blurrer on startup
$("#blurrer").css("height",$(window).height()+"px");
$("#blurrer").css("width",$(window).width()+50+"px");

$(window).resize(function() {
 $("#blurrer").css("height",$(window).height()+"px");
 $("#blurrer").css("width",$(window).width()+50+"px");
});

     



// main menu functionality ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++  
if (!isiPhonePad()) {
	
	
					
			helperBlurrer = false;	
			$("#mainMenuWrap").bind("mouseenter mouseleave", function(e) {
				if(e.type == "mouseenter") {
					//console.log("mainMenuWrap ENTEr");
					Mairs.menutimerReduceFlicker = setTimeout(function() {
						if (jQuery.browser.msie) {$("#blurrer").slideDown(200);}
						else {$("#blurrer").fadeIn(200);}
					}, 200);
					helperBlurrer = true;
					return true;
				}
				if(e.type == "mouseleave") {
					//console.log("mainMenuWrap leave");
					clearTimeout(Mairs.menutimerReduceFlicker);
					Mairs.menutimerReduceFlicker = 0;
					//$("#blurrer").slideUp(200);
					if (jQuery.browser.msie) {$("#blurrer").slideUp(200);}
						else {$("#blurrer").fadeOut(200);}
					return true;
				}
			});
			// additional hover blurrer hides blurrer
			$("#blurrer").bind("mouseenter", function(e) {
				if (helperBlurrer) {
					//console.log("mainMenuWrap leave");
					clearTimeout(Mairs.menutimerReduceFlicker);
					Mairs.menutimerReduceFlicker = 0;
					//$("#blurrer").slideUp(200);
					if (jQuery.browser.msie) {$("#blurrer").slideUp(200);}
					else {$("#blurrer").fadeOut(200);}
					helperBlurrer = false;
					deactivateMenuAll();
				}
			});
			
			
			
			
		

	
	$("li.level1Item").bind("mouseenter", function(e){
		// removing element.style form touch device script - kind of resetting it to default (this is important)
		curItem = $(this).children('div.logooverlayhelper');
		
			if (Mairs.menutimer != 0) {
				activateMenu(curItem);
			}
			else {
				Mairs.menutimer = setTimeout(function(){
					activateMenu(curItem)
				}, 200);
			}
		});
		$("li.level1Item").bind("mouseleave", function(e){
			deactivateMenu(curItem);
		});
		
	if (jQuery.browser.msie) {
		$("li.level1Item>a").bind("mouseenter", function(e){
			$(this).parent("li").trigger("mouseenter");
			return true;
			
		});
	}
		


	
		// additional event binding to helper, because of several reasons
		$("div.logooverlayhelper").bind("mouseleave", function(e) {
			// IE<8 doesn't fire li.level1Item mouseleave (see above) so additionally we bind mouseleave to logooverlayhelper
			if(jQuery.browser.msie && jQuery.browser.version.substr(0, 1) < 8) {
				$(this).removeClass("menuOn");
				// all other browsers: removing blurrer
			} else {
				// only deac when mouse enters an other element
				//console.log("leave helperArte", e.target);
				if(e.target != this) {
					deactivateMenu($(this));
				}
			}
			//return false;
		});
	


} // end no touch browsers

	// showing menu-close button when its iphone / ipad
	if(isiPhonePad()) {
		$("div.logooverlayhelper").append("<div id='withCloseBtn'><div>");
		$("li.level1Item").bind("click", function(e) {
			// removing element.style form touch device script - kind of resetting it to default (this is important)
			curItem = $(this).children('div.logooverlayhelper');
			activateMenu(curItem);
			$("#blurrer").fadeIn(200);
		});
		// prevent click on level1 link
		$("li.level1Item>a").bind("click", function(e) {
			$(this).parent("li").click();
			return false;
		});
		
   
    
    // additional hover blurrer hides blurrer
	$("#blurrer").bind("mouseenter click", function(e) {
			//console.log("mainMenuWrap leave");
			clearTimeout(Mairs.menutimerReduceFlicker);
			Mairs.menutimerReduceFlicker = 0;
			//$("#blurrer").slideUp(200);
			$("#blurrer").fadeOut(200);
			deactivateMenuAll();
	});
		//
	} // end is IPas	// bind close event to closebtn

$("div#withCloseBtn").bind("click", function(){
	curItem = $(this).parent('div.logooverlayhelper');
	deactivateMenuAll();
	clearTimeout(Mairs.menutimerReduceFlicker);
    Mairs.menutimerReduceFlicker = 0;
	$("#blurrer").fadeOut(200);
	return false;
});
 
// end main menu ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 
  
  
  
  // adjusting h1 width on product page, 
  $("#moduleFullView #rowOf3-left h1 br").parent().contents().each(function(i) {
    if(this.nodeName == "#text")
    {
        if($(this).text().length>9) {
        	$("#moduleFullView #rowOf3-left h1").css("font-size","41px");
        }
    }
});

  
 
// render the survey with flashembed ( flowplayer.org/tools/toolbox/flashembed.html)
        if ( jQuery("#survey").length > 0) {
              flashembed("survey", {
                  src: "../resource/av/flash/home3.swf",
                  version: [9, 0],
                      wmode:'#FF0000',
                      wmode:'transparent'
              }, {
              
                  // 
                  flashvars: 'myAnswerTxt1=Handbuch&myAnswerTxt2=Support-Hotline&myAnswerTxt3=Hilfen in der Software&myAnswerTxt4=Hilfe auf der Website&totalTxt=Antworten&myXMLPath=../../library/resource/xml/survey4.xml&myPHPPath=../../library/system/code/php/survey/survey.php',
                  myAnswerTxt1: 'Handbuch',
                  myAnswerTxt2: 'Handtuch',
                  myAnswerTxt3: 'Hotline',
                  myAnswerTxt4: 'Google',
                  totalTxt: 'Antworten.', // this text is shown below the survey
                  myXMLPath: '../../library/resource/xml/surveySupport.xml'
              });
              
              // there ist a problem because the logo is hover an so the sitemapmenu is closed...
              //here we overwrite this

        };
	
	


 
 //interaction on page with a textList (list template)  
 //interaction on page with a textList (list template) ##################################
 if (jQuery("#textList").length > 0) {
 	$(".textListItem li").bind("click",function(){
		$(this).children(".textListInner").toggle(100);
	})

 
 // making selection list on list template
 $("aside#sidebarLeft").append('<select name="filterlist" id="filterlist" />');
 $("select#filterlist").append("<option name='all'>Alle Anzeigen</option>");
 var optionindex=0;
 	$("#textList .textListItem").each(function(){
		$("select#filterlist").append("<option name="+optionindex+">"+$(this).children("h3").text()+"</option>")
		optionindex++;
	})


 // selecthandler for all browsers ()
  $("select#filterlist").bind("change",function(){
	var selectet = $(this).children("option:selected");
	var hideByOption = selectet.attr("name");
	if (hideByOption == "all") {
		$(".textListItem").show(100);
	}
	else {
		$(".textListItem").hide(100);
		$(".textListItem").eq(Number(hideByOption)).show(100);
	}
 });
 
  } // end if #textlist
  
 
 
/* FORM HANDLING --------------------------------------------------------------------------*/
/* FORM HANDLING --------------------------------------------------------------------------*/

// UPLOAD FILES
// DEFINING some global form properties
	THEFORM = new Array();
	THEFORM.maxfiles = 2;
	THEFORM.filenames = new Array();
	
// Flash Session Problems, so we have to send Session ID manually
// this is taken from here: http://www.uploadify.com/forums/discussion/43/using-sessions-tricking-basic-authentication/p1
var start = document.cookie.indexOf("PHPSESSID=");
var end = document.cookie.indexOf(";", start); // First ; after start
if (end == -1) end = document.cookie.length; // failed indexOf = -1
var cookie = document.cookie.substring(start+10, end);
	
if ($('#fileUpload1').length > 0) {	

  $('#fileUpload1').uploadify({
    'uploader'  : '../../library/system/code/php/forms/uploadify/uploadify.swf',
	'script'    : '../../library/system/code/php/forms/uploadify/uploadify.php',
	'cancelImg' : '../../library/system/code/php/forms/uploadify/cancel.png',
	'scriptData' : { 'PHPSESSID': cookie },
	'folder'    : '/internally',
	'fileExt'     : '*.jpg;*.gif;*.png;*.PDF;*.pdf;*.PNG;*.JPG;*.GIF;*.jpeg*;.JPEG;*.JPEG;*.zip;*.ZIP;',
	'fileDesc'    : 'Image Files and PDFs are allowed',
	'removeCompleted' : false,
	'auto'           : true,
	'multi'          : true,
	'queueSizeLimit' : 2,
	'height'      : 30,
	'buttonImg': '../../library/system/resource/image/uploadFileButton.png',
	'width': '140',
	'height': '22',
	'wmode': 'transparent',
	'onComplete': function(event, ID, fileObj, response){
					THEFORM.filenames.push(fileObj.name);
					//console.info(THEFORM.filenames);
					checkMaxUpload();
				 if (response !== '1') //  ERROR
                   {  
				 
				   $('#fileUpload1').parent().append("<label class='error'>Es ist ein Fehler aufgetreten:"+response+"</div");
		 			}
                 else   //  SUCCESS
                   {    // $('#fileUpload1').parent().append("<label class='error'>Es ist ein Fehler aufgetreten:"+response+"</div");         
                   }
     },
	'onAllComplete' : function(event, ID, fileObj, response) {
	},
	'onError'     : function (event,ID,fileObj,errorObj) {
			 $('#fileUpload1').parent().append("<label class='error'>Es ist ein Fehler aufgetreten:"+errorObj.info+"</div");
		},
	'onCancel'     : function (event,ID,fileObj,errorObj) {
		setTimeout(checkMaxUpload,500);
	}
 }); // end file upload
} // end if fileupload exists

/* adding tabindex to form elements */
if (jQuery("form#theform").length > 0) {
	var formCounter=1;
	
	$("div.form-element-block").not(".preQuestion").each(function(){
		$(this).children("div.form-elem").children().attr("tabindex",formCounter);
		formCounter++;
		
	});
	
}

/* 
 * Validate form and call ajax form backend ///////////////////////////////////////////////////////////////////	
 * */

if (jQuery("form#theform").length > 0) {
	 	jQuery("form#theform").validate({
	 		meta: "validate",
	 		submitHandler: function(form){ /* When Validated do this */
					
					$('form#theform input.submit').hide();
					var loadingmes = 'Einen Moment bitte'; // todo hier Variable verwenden
					$('form#theform').append('<div id="loading">' + loadingmes + '<br /> <img src="../../library/system/resource/image/ajax-loader.gif" class="loaderIcon" alt="Loading..." /> </div>');
					
					var data = {};
					/*extracting form-element-values*/
					$("div.form-element-block").each(function(){
						// when its an input element of type text:
						if ($(this).find('input[type=text]').length > 0) {
							var key = $(this).children('div.form-label').children('label');
							var value = $(this).find('input');
							key = $.trim(key.text());
							keykey = encodeURI(key);
							valuevalue = encodeURI(value.val());
							nameAttr = value.attr("name");
							fieldType = "input_Text";
						}
					// when its an textarea element
						if ($(this).find('textarea').length > 0) {
							var key = $(this).children('div.form-label').children('label');
							var value = $(this).find('textarea');
							key = $.trim(key.text());
							keykey = encodeURI(key);
							valuevalue = encodeURI(value.val());
							nameAttr = value.attr("name");
							fieldType = "textarea";
						}
						// when its an select option element
						if ($(this).find('select').length > 0) {
							var key = $(this).children('div.form-label').children('label');
							value = $(this).find('option:selected');
							key = $.trim(key.text());
							keykey = encodeURI(key);
							valuevalue = encodeURI(value.text());
							nameAttr = $(this).find('select').attr("name");
							fieldType = "select";
						}
						// when its an input type=radio
						if ($(this).find('input[type=radio]').length > 0) {
							var key = $(this).children('div.form-label').children('label');
							key = $.trim(key.text());
							keykey = encodeURI(key);
							valueSelector = $(this).find('input:checked').attr("id");
							value = $(this).find('label[for=' + valueSelector + ']');
							value = $.trim(value.text());
							valuevalue = encodeURI(value);
							nameAttr = $(this).find('input:checked').attr("name");
							fieldType = "input_Radio";
						}
					var betterkey = String(keykey)+ "__" + String(nameAttr)+ "__" + fieldType;
					data[betterkey] = valuevalue;
					data['pageTitle'] = document.title;
					// checking if there where file-upload
					if( THEFORM.filenames.length > 0) {
						data.files =  THEFORM.filenames;
					};
					})// end each form-element-block;
					jQuery.ajax({
						type: 'post',
						url: '../../library/system/code/php/forms/kforms.php',
						data: data,
						success: function(results){
							jQuery('form#theform').hide();
					 		jQuery('#loading').fadeOut(1000);
					 		jQuery('section#form-block').append("<div class='form-right' id='formresponse'>"+results+"</div>");
						},
						error: function(results){
							jQuery('form#theform').hide();
					 		jQuery('#loading').fadeOut(1000);
					 		jQuery('section#form-block').append("<div class='form-right' id='formresponse'>"+results+"</div>");
						}
					}); // end ajax
				//console.log(data);
				
				}
			});// end validate
		} // end if form exists


/*send mails in other format ----------------------------------------------
 lfk: 15/10/2011 

* 
* 
* */

if (jQuery("form#theformSpecial").length > 0) {		
	 	jQuery("form#theformSpecial").validate({
	 		meta: "validate",
	 		submitHandler: function(form){ /* When Validated do this */
					
					$('form#theformSpecial input.submit').hide();
					var loadingmes = 'Einen Moment bitte'; // todo hier Variable verwenden
					$('form#theform').append('<div id="loading">' + loadingmes + '<br /> <img src="../../library/system/resource/image/ajax-loader.gif" class="loaderIcon" alt="Loading..." /> </div>');
					
					var data = {};
					/*extracting form-element-values*/
					$("div.form-element-block").each(function(){
						// when its an input element of type text:
						if ($(this).find('input[type=text]').length > 0) {
							var key = $(this).children('div.form-label').children('label');
							var value = $(this).find('input');
							key = $.trim(key.text());
							keykey = encodeURI(key);
							valuevalue = encodeURI(value.val());
							nameAttr = value.attr("name");
							fieldType = "input_Text";
						}
					// when its an textarea element
						if ($(this).find('textarea').length > 0) {
							var key = $(this).children('div.form-label').children('label');
							var value = $(this).find('textarea');
							key = $.trim(key.text());
							keykey = encodeURI(key);
							valuevalue = encodeURI(value.val());
							nameAttr = value.attr("name");
							fieldType = "textarea";
						}
						// when its an select option element
						if ($(this).find('select').length > 0) {
							var key = $(this).children('div.form-label').children('label');
							value = $(this).find('option:selected');
							key = $.trim(key.text());
							keykey = encodeURI(key);
							valuevalue = encodeURI(value.text());
							nameAttr = $(this).find('select').attr("name");
							fieldType = "select";
						}
						// when its an input type=radio
						if ($(this).find('input[type=radio]').length > 0) {
							var key = $(this).children('div.form-label').children('label');
							key = $.trim(key.text());
							keykey = encodeURI(key);
							valueSelector = $(this).find('input:checked').attr("id");
							value = $(this).find('label[for=' + valueSelector + ']');
							value = $.trim(value.text());
							valuevalue = encodeURI(value);
							nameAttr = $(this).find('input:checked').attr("name");
							fieldType = "input_Radio";
						}
					var betterkey = String(keykey)+ "__" + String(nameAttr)+ "__" + fieldType;
					data[betterkey] = valuevalue;
					
					//data['fullSerial'] = document.URL;
					// checking if there where file-upload
					if( THEFORM.filenames.length > 0) {
						data.files =  THEFORM.filenames;
					};
					})// end each form-element-block;
					data['pageTitle'] = document.title;
					// these are different from other forms
					data['urlofForm'] = document.URL;
					data['FULLSeriennummer'] = $("#FULLSeriennummer").val();
				
					jQuery.ajax({
						type: 'post',
						url: '../../library/system/code/php/forms/kformsSpezial.php',
						data: data,
						success: function(results){
							jQuery('form#theformSpecial').hide();
					 		jQuery('#loading').fadeOut(1000);
					 		jQuery('section#form-block').append("<div class='form-right' id='formresponse'>"+results+"</div>");
						},
						error: function(results){
							jQuery('form#theformSpecial').hide();
					 		jQuery('#loading').fadeOut(1000);
					 		jQuery('section#form-block').append("<div class='form-right' id='formresponse'>"+results+"</div>");
						}
					}); // end ajax
				//console.log(data);
				
				}
			});// end validate
		} // end if form exists
/*
 * END FORMS SPECIAL -----------------------------------------------------------------------------------
 * */




 
//give ids to left-right/even-odd items on produk2-page
// comment this out to have the majortopics the full size...
if (jQuery(".majortopic").length > 0) {
	var i = 0;
	var count = jQuery('.majortopic').length;
	jQuery('.majortopic').each(function(){
		jQuery(this).attr('id', String('maintopic-' + i + "-" + count));
		if ((i % 2) == 0) {
			jQuery(this).addClass('majortopic-even');
		}
		if ((i % 2) == 1) {
			jQuery(this).addClass('majortopic-odd');
		}
		i++;
	});
	var i = 0;
	jQuery('.modalItem').each(function(){
		jQuery(this).attr('id', String('minortopic-' + i));
		if ((i % 2) == 0) {
			jQuery(this).addClass('minortopic-even');
		}
		if ((i % 2) == 1) {
			jQuery(this).addClass('minortopic-odd');
		}
		i++;
	});
}



/* handles the modal window on modul-pages ----------------------------------------------------*/   
/*following are for modal window open,close,next, prev ----------------------------------------*/
// to top	
        jQuery('#functionButtonsBottom-Top').click(function(event) {
                var modwind = jQuery(this).parents('#modalwindow');
                jQuery(document).scrollTop(modwind.position().top-40);
                event.stopPropagation();
        });
// close	
        jQuery('#functionButtonsTop-Close').click(function(event) {
                //var modwind = jQuery(this).parents(".modalwrapper");
                jQuery("#blurrer").hide(300);
                jQuery('#modalwindow #modalwindow-content').html('');
                jQuery('#modalwindow').hide(300);
                event.stopPropagation();
        });
// prev reader window
        jQuery('#functionButtonsTop-Left').click(function(event) {
                if (jQuery(this).hasClass("aktivleft")) {
                        var idm = jQuery('#modalwindow').attr('class').split('-');
                        reloadmodalcountent('maintopic-' + String(idm[1] - 1) + '-' + String(idm[2]));
                        event.stopPropagation();
                }
        });
		
// next reader window
        jQuery('#functionButtonsTop-Right').click(function(event) {
                if (jQuery(this).hasClass("aktivright")) {
                        var idm = jQuery('#modalwindow').attr('class').split('-');
                        next = Number(idm[1]) + 1;
                        reloadmodalcountent('maintopic-' + String(next) + '-' + String(idm[2]));
                        event.stopPropagation();
                }
        });
        
        
// open	
    jQuery('.majortopic').click(function() {
            reloadmodalcountent(jQuery(this).attr('id'));
     });
         
// clicking on dark area closes modalwindow
    jQuery("#blurrer").click(function(){
              jQuery("#blurrer").hide(300);
              jQuery('#modalwindow #modalwindow-content').html('');
              jQuery('#modalwindow').hide(300);
     });


// template newsletter -----------------------------------------------------
// template newsletter -----------------------------------------------------
 if ($(".newsletterItem").length > 0) {
 	$(".newsletterItem").filter(":last").css("border","none");
 	$(".newsletterItem").each(function(){
		//$(".stageParagraph").append()
		ha2 = $(this).children("h2").clone(true,true);
		anker =$(this).attr("name");
		//console.info();
		ha2.wrap('<a class="stageParaAnker" href="#'+anker+'" />')
		ha2.parent("a.stageParaAnker").appendTo('.stageParagraph');
	})
 }
 
 
 
 // opening BigPicture Overlay
 $("a.kImageOpenBigIcon").live("click",function(event){
 	event.preventDefault();
	//jQuery('#modalwindow #modalwindow-content').html('');
 	//console.log("Open BigPicture Overlay");
	var imageSource = $(this).attr("href");
	var bigImage = $("<img src='"+imageSource+"' />");
	bigImage.css("width",$('#modalwindow').css("width"));
	$('#modalwindow #modalwindow-content').html('');
	$('#modalwindow #modalwindow-content').append(bigImage);
	copyRinModal = $(this).parent().children(".kImageTextCopyRight").clone();
	captioninModal = $(this).parent().children(".kImageTextCaption").clone();
	copyRinModal.css("float","right");
	captioninModal.css("font-size","150%");
	captioninModal.css("padding","10px");
	$('#modalwindow #modalwindow-content').append(copyRinModal);
	$('#modalwindow #modalwindow-content').append(captioninModal);

	//BIdim = getImgSize(imageSource);
	modwind = $('#modalwindow');
    toppos = $(window).scrollTop();
    modwind.css("top",toppos+"px");
	
	// greying out left right
	fbl = jQuery('#functionButtonsTop-Left');
	fbl.removeClass('aktivleft');
	fbl.attr("src","http://www.mairpro.com/Library/Resource/Image/modal-left1-off.png");
    fbr = jQuery('#functionButtonsTop-Right');
	fbr.removeClass('aktivright');
	fbr.attr("src","http://www.mairpro.com/Library/Resource/Image/modal-right1-off.png");
    
	jQuery('#functionButtonsTop-Right').removeClass('aktivright');
        	
	 modwind.show(function() {
	        var morethanwindow = modwind.position().top + modwind.height() + 100;
	        
			// adjust height and width of blurrer (gray background)
	        var blurrer = jQuery("#blurrer");
	        blurrer.css("width",jQuery(document).width()+"px");
	        if (morethanwindow < jQuery(document).height()) {
	                //blurrer.height(jQuery(document).height());
	                blurrer.css("height",jQuery(document).height()+"px");
	        }
	        else {
	                blurrer.css("height",morethanwindow+"px");
	        }
	        blurrer.fadeTo(200, 0.75);
		}); // end  modwind.show
 })

});
 // end document ready +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 // end document ready +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 // end document ready +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
						





















//things to do an page load ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//things to do an page load ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//things to do an page load ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//things to do an page load ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//things to do an page load ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// we do not need this anymore because of horizontal background

jQuery(window).load(function() {
	
	
	
// initialsize the carousel...
  if ( jQuery("#thekarousell").length > 0) {
    jQuery("#thekarousell").jcarousel({
        scroll: 1,
        initCallback: mycarousel_initCallback,
		buttonNextCallback: karousel_buttonNextCallback,
		buttonPrevCallback: karousel_buttonPrevCallback, 
        // This tells jCarousel NOT to autobuild prev/next buttons
        buttonNextHTML: null,
        buttonPrevHTML: null
    });
  }
  

  
  // bind swipe events for karousell
  if (isiPhonePad()) {
        $("#karousell li").swipe({
              swipeLeft: function() { $('#karousell-right').trigger("click"); },
              swipeRight: function() { $('#karousell-left').trigger("click"); }
       });
      
 };
 
	
	
	
  //adjust the height of the menu
  var submenuLevel3MAX = 0;
  $("#mainMenu ul.submenuLevel3").each(function(){
  		if ($(this).height() > submenuLevel3MAX) {submenuLevel3MAX = $(this).height();}
  })
  $("#mainMenu ul.submenuLevel3").each(function(){
  		$(this).height(submenuLevel3MAX);
  })
  //$(".logooverlayhelper").height(submenuLevel3MAX+58);
   $("#mainMenu   ul.submenuLevel2").each(function(){
  		$(this).height(submenuLevel3MAX+58);
  		//$(this).css("padding-bottom","60px");
  })
  $("ul.submenuLevel2 li.level2Item").each(function(){
  		//$(this).height(submenuLevel3MAX+53);
  })
  
	
  if ( jQuery(".moduleMain-Item-Wrap").length > 0) {   adjustheightofItems(); };
  if ( jQuery("#doubleblockleft").length > 0) {  adjustheightofDoubleBlock(); };
  if ( jQuery(".rowOf3.firstrowof3").length > 0) {  adjustrowof3height(); };
  if ( jQuery(".rowOf3.secondrowof3").length > 0) {  adjustrowof32height(); };
  
  
  //enlarging the length of each last mostsearchItem to rest of line
  if($(".mostsearchItem").length > 0) {
  	  internalCounter = 0;
	  boxwidth = $("#meistgesuchtWrap").width();
  	  $(".mostsearchItem").each(function() {
	  	if (internalCounter>0){
			curPosY = $(this).position().top;
			formerItem = $(".mostsearchItem").eq(internalCounter-1);
			formerPos = formerItem.position();
			formerPosY = formerPos.top;
			formerPosX = formerPos.left;
			
			if (curPosY > formerPosY) {
				
				formerItem.css("width",boxwidth-formerPosX-32+"px");
			}
		}
		internalCounter ++;
	  });
	  // do the same for last element
	 	lastItem = $(".mostsearchItem").last();
		lastItemPosX = lastItem.position().left;
	  	lastItem.css("width",boxwidth-lastItemPosX-32+"px");
  }
  
})
// end window load +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 // end window load +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 // end window load +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
								
	
	
// adjust height of moduleMain-Item-Wrap on Produkt1 page
function adjustheightofItems() {
	var maxheight = 0;
	if (jQuery.browser.msie) {
	    jQuery('.moduleMain-Item-Wrap').each(function(){
		var ro3h = jQuery(this).find("p").innerHeight();
		
		if (ro3h > maxheight) {maxheight = ro3h;}
	     });
	    jQuery('.moduleMain-Item-Wrap').each(function(){
		 jQuery('p',this).css("height",maxheight+"px");
	    });
	    
	} else {	    
	    jQuery('.moduleMain-Item-Wrap').each(function(){
		 // opera.postError("hiegh " + jQuery("p",this).css("height"));
		var ro3h = jQuery("p",this).css("height");
		var ro3hr = Number(ro3h.substring(0, ro3h.length-2));
		if (ro3hr > maxheight) {maxheight = ro3hr;}
	    });
	    
	    jQuery('.moduleMain-Item-Wrap').each(function(){
		 
		    jQuery('p',this).css("height",maxheight+"px");
	    });
	}
} // end adjustheightofItems

//adjust text height on doubleblock produkt1 page
function adjustheightofDoubleBlock (){
     
	    var dbl = jQuery('#doubleblockleft .doubleblock-text p').css("height");
	    var dbln = Number(dbl.substring(0, dbl.length-2));
	    var dbr = jQuery('#doubleblockright .doubleblock-text p').css("height");
	    var dbrn = Number(dbr.substring(0, dbr.length-2));
	    if (dbln < dbrn) {jQuery('#doubleblockleft .doubleblock-text p').css("height",dbrn+"px")};
	    if (dbln > dbrn) {jQuery('#doubleblockright .doubleblock-text p').css("height",dbln+"px")};
	    
	   	    
	    if (jQuery.browser.msie) {
		
		
	     
		var dbl = jQuery('#doubleblockleft .doubleblock-text p').height();
		var dbr = jQuery('#doubleblockright .doubleblock-text p').height();
		if (dbl < dbr) {jQuery('#doubleblockleft .doubleblock-text p').height()};
		if (dbl > dbr) {jQuery('#doubleblockright .doubleblock-text p').height()};

	    }

} // end adjustheightofDoubleBlock
                
                				
						
						
//adjust borders / height of certain elements on Produkt2 pages
function adjustrowof3height() {
        var maxheight = 0;
        var maxheightText = 0;
        var mosttop = 0;
	if (jQuery.browser.msie) {
	     jQuery('.rowOf3.firstrowof3>*').each(function(){
		var ro3h = jQuery(this).innerHeight();
		if (ro3h > maxheight) {maxheight = ro3h;}
		var toppos = jQuery('.rowOf3-text p',this).position().top
		 if (toppos > mosttop) {mosttop = toppos;}
		var ro3texth = jQuery('.rowOf3-text p',this).innerHeight();
		if (ro3texth > maxheightText) {maxheightText = ro3texth;}
	    });
	
        
	    jQuery('.rowOf3.firstrowof3>*').each(function(){
		    var diff = mosttop - jQuery('.rowOf3-text p',this).position().top ;
		    jQuery('.rowOf3-text p',this).css("margin-top",diff+"px");
		    jQuery('.rowOf3-text p',this).css("height",maxheightText+"px");
	    });
	
	}
	else {
	    jQuery('.rowOf3.firstrowof3>*').each(function(){
		var ro3h = jQuery(this).css("height");
		var ro3hr = Number(ro3h.substring(0, ro3h.length-2));
		if (ro3hr > maxheight) {maxheight = ro3hr;}
		var toppos = jQuery('.rowOf3-text p',this).position().top
		 if (toppos > mosttop) {mosttop = toppos;}
		var ro3texth = jQuery('.rowOf3-text p',this).css("height");
		var ro3texthr = Number(ro3texth.substring(0, ro3texth.length-2));
		if (ro3texthr > maxheightText) {maxheightText = ro3texthr;}
	    });
	
        
	    jQuery('.rowOf3.firstrowof3>*').each(function(){
		    var diff = mosttop - jQuery('.rowOf3-text p',this).position().top ;
		    jQuery('.rowOf3-text p',this).css("margin-top",diff+"px");
		    jQuery('.rowOf3-text p',this).css("height",maxheightText+"px");
		    //jQuery('.rowOf3-text p',this).css("border","1px solid red"); 
	    });
	}
} // end adjustrowof3height

function adjustrowof32height() {
        var maxheight = 0;
        var maxheightText = 0;
        var mosttop = 0;

	if (jQuery.browser.msie) {
	     jQuery('.rowOf3.secondrowof3>*').each(function(){
		var ro3h = jQuery(this).innerHeight();
		if (ro3h > maxheight) {maxheight = ro3h;}
		var toppos = jQuery('.rowOf3-text p',this).position().top
		 if (toppos > mosttop) {mosttop = toppos;}
		var ro3texth = jQuery('.rowOf3-text p',this).innerHeight();
		if (ro3texth > maxheightText) {maxheightText = ro3texth;}
	    });
	
        
	    jQuery('.rowOf3.secondrowof3>*').each(function(){
		    var diff = mosttop - jQuery('.rowOf3-text p',this).position().top ;
		    jQuery('.rowOf3-text p',this).css("margin-top",diff+"px");
		    jQuery('.rowOf3-text p',this).css("height",maxheightText+"px");
	    });
	
	}
	else {
	    jQuery('.rowOf3.secondrowof3>*').each(function(){
            var ro3h = jQuery(this).css("height");
            var ro3hr = Number(ro3h.substring(0, ro3h.length-2));
            if (ro3hr > maxheight) {maxheight = ro3hr;}
            var toppos = jQuery('.rowOf3-text p',this).position().top;
            if (toppos > mosttop) {mosttop = toppos;}
            var ro3texth = jQuery('.rowOf3-text p',this).css("height");
            var ro3texthr = Number(ro3texth.substring(0, ro3texth.length-2));
            if (ro3texthr > maxheightText) {maxheightText = ro3texthr;}
        });
        
        jQuery('.rowOf3.secondrowof3>*').each(function(){
                
                var diff = mosttop - jQuery('.rowOf3-text p',this).position().top ;
                jQuery('.rowOf3-text p',this).css("margin-top",diff+"px");
                jQuery('.rowOf3-text p',this).css("height",maxheightText+"px");
               // jQuery('.rowOf3-text p',this).css("border","1px solid red"); 
        });
        
	}
        
}	// end adjustrowof32height				
						
       
       
       /**
 * Karousell Scripts
 * used on new Product Page
 */
function mycarousel_initCallback(carousel) {
    jQuery('.jcarousel-control a').bind('click', function() {
        carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text()));
        return false;
    });
	
	jQuery('#karousell-left').bind('click', function() {
		carousel.prev();
 		return false;
	}); 
	
	jQuery('#karousell-right').bind('click', function() {
		carousel.next();
 		return false;
	}); 
	
} // end mycarousel_initCallback

function karousel_buttonPrevCallback(carousel, button, enabled) {
 	if (!enabled) {	jQuery('#karousell-left').addClass('disabled');}
	else {jQuery('#karousell-left').removeClass('disabled');}
}; 
function karousel_buttonNextCallback(carousel, button, enabled) {
 	if (!enabled) {	jQuery('#karousell-right').addClass('disabled'); }
	else {jQuery('#karousell-right').removeClass('disabled');}
}; 


// detecting iphone / ipad
function isiPhonePad(){
	
	
    return (
        //Detect iPhone
        (navigator.platform.indexOf("iPhone") != -1) ||
        //Detect iPod
        (navigator.platform.indexOf("iPod") != -1) ||
        // IPAD
        (navigator.userAgent.indexOf("iPad") != -1)
    );
} // end is iPad


// Make PDF ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Make PDF ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Make PDF ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Make PDF ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

function makePDFofthis(){
		
       //selecting elements
       var encoHTML = '';
       $('article').find('.inPDF').each(function(){
       		var currentThing = $(this).clone();
	   		// removing inline styles, because of some js-adjustments not desired in PDF
	   		currentThing.removeAttr("style"); 
			// and for all kids also
	   		currentThing.find('*[style]').each(function(){
				$(this).removeAttr("style");
			});
			// make image path relative
			currentThing.find('img').each(function(){
				var absPath = $(this).attr("src");
				// replace "www" in absPath (if exists)
				absPath = absPath.replace("www.","");
				// replace ".com" with ".de"
				absPath = absPath.replace(".com",".de");
				// replace "www" in window.location.host
				var wlh = window.location.host;
				wlh = wlh.replace("www.","");
				// replace ".com" with ".de"
				wlh = wlh.replace(".com",".de");
				var toReplace = window.location.protocol + "//" +wlh;
				var relPath = absPath.replace(toReplace,"../..");
				// replace mairpro2011, attention when live !!!!!
				//var relPath = relPath.replace("mairpro2011/","");
				$(this).attr("src",relPath);
			});
			// append full text 
			currentThing.find('a').each(function(){
				//make links absolute
				//check if absolute
				if(($(this).attr("href").substr(0,4))!="http") {
					var absLink =  window.location.host + "/" +$(this).attr("href");
				} else {
					var absLink = $(this).attr("href");
				}
				$(this).wrap($("<div class='helper'></div>"));
				$(this).attr("href","");
				$(this).parent(".helper").append(" ("+absLink+") ");
		
			});
			
			// when is applied to an img tag $(this).html() is empty, so this tries to repair this problem
			if (currentThing.html()=="") {
				var helper= $("<div>");
				//helper.append($(this));
				currentThing.wrap(helper);
				encoHTML+= encodeURI(helper.html());
			}
            encoHTML+= encodeURI(currentThing.html()); 
       })
     	//console.info(encoHTML);
    // Launch AJAX request.
       var pathn = location.pathname.split("/");
       var filename = pathn[pathn.length-1];
       var sinHtml = filename.split(".");
       sinHtml = sinHtml[0];
       var data = {
              titel: document.title,
              html: encoHTML,
              pathname: location.pathname,
              filename:filename,
              withoutEnding : sinHtml,
              theurl : location.href,
    };
    
   $.ajax({
        url: '../../services/dompdf/kdomToPdf.php', 
        type: "POST",
        data : data,
        error: function(){
            $("#pdfmakerFeedback").html("<p>Es ist ein Fehler aufgetreten</p>");
        },
        beforeSend: function(){
              $("#pdfmakerFeedback").html("<p>Einen Moment, das PDF wird erzeugt</p>");
        },
        complete: function(strData){
        	//console.info(strData);
          $("#pdfmakerFeedback").html("<p><a href='"+strData.responseText+"'>Download PDF</a></p>");
           autodownload(strData.responseText);
        },
        success: function(strData){
        	//console.info(strData);
	        $("#pdfmakerFeedback").html("<p>In Ihrem Browser sollte der Download starten <br> Falls dies nicht geschieht,  <a href='"+strData.responseText+"'>klicken Sie hier.</a></p>");
        }
    }); 
    // Prevent default click.
    return (false);
} // end makePDF +++++++++++++++++++++++++++++++++++

// for this template we need an other parsing
function makePDFofSystemvoraussetzungen(){
		
       //selecting elements
       var encoHTML = ''
	   
       $('article').find('.inPDF').each(function(){
	   		// removing inline styles, because of some js-adjustments not desired in PDF
	   		$(this).removeAttr("style"); 
			// and for all kids also
	   		$(this).find('*[style]').each(function(){
				$(this).removeAttr("style");
			});
			// make image path relative
			$(this).find('img').each(function(){
				var absPath = $(this).attr("src");
				// replace "www" in absPath (if exists)
				absPath = absPath.replace("www.","");
				// replace ".com" with ".de"
				absPath = absPath.replace(".com",".de");
				// replace "www" in window.location.host
				var wlh = window.location.host;
				wlh = wlh.replace("www.","");
				// replace ".com" with ".de"
				wlh = wlh.replace(".com",".de");
				var toReplace = window.location.protocol + "//" +wlh;
				var relPath = absPath.replace(toReplace,"../..");
				
				// replace mairpro2011, attention when live !!!!!
				var relPath = relPath.replace("mairpro2011/","");
				$(this).attr("src",relPath);
			});
		
			// when is applied to an img tag $(this).html() is empty, so this tries to repair this problem
			if ($(this).html()=="") {
				var helper= $("<div>");
				helper.append($(this));
				encoHTML+= encodeURI(helper.html());
			}
			$(this).find('tr').each(function(){
				$(this).attr("style","border-bottom:1px solid #4f5559 !important;");
			});
		
            encoHTML+= encodeURI($(this).html()); 
       })
    // Launch AJAX request.
       var pathn = location.pathname.split("/");
       var filename = pathn[pathn.length-1];
       var sinHtml = filename.split(".");
       sinHtml = sinHtml[0];
       var data = {
              titel: document.title,
              html: encoHTML,
              pathname: location.pathname,
              filename:filename,
              withoutEnding : sinHtml,
              theurl : location.href
    };
   $.ajax({
        url: '../../services/dompdf/kdomToPdf-Systemvoraussetzungen.php', 
        type: "POST",
        data : data,
        error: function(){
            $("#pdfmakerFeedback").html("<p>Es ist ein Fehler aufgetreten</p>");
        },
        beforeSend: function(){
              $("#pdfmakerFeedback").html("<p>Einen Moment, das PDF wird erzeugt</p>");
        },
        complete: function(strData){
          $("#pdfmakerFeedback").html("<p><a href='"+strData.responseText+"'>Download PDF</a></p>");
           autodownload(strData.responseText);
        },
        success: function(strData){
	        $("#pdfmakerFeedback").html("<p>In Ihrem Browser sollte der Download starten <br> Falls dies nicht geschieht,  <a href='"+strData.responseText+"'>klicken Sie hier.</a></p>");
        }
    }); 
    // Prevent default click.
    return (false);
} // end makePDF +++++++++++++++++++++++++++++++++++

// since the download link is provide via ajax call, we have to do autodownloadprompt like this
function autodownload(url){
  var elemIF = document.createElement("iframe");
  elemIF.src = url;
  elemIF.style.display = "none";
  document.body.appendChild(elemIF);
} // end autodownload


function ShowStatus (whattoShow) {
	//console.log(whattoShow);
}

// hide upload button when max files is reached
function checkMaxUpload () {
		//console.log("checkMaxUpload");
		//console.log($('.uploadifyQueueItem').length);
		if ($('.uploadifyQueueItem').length >= Number(THEFORM.maxfiles)) {
			$("#fileUpload1Uploader").width(0);
		} else {
			$("#fileUpload1Uploader").width(140);
		}
} // end checkMaxUpload
	

	

// this function handles the modal-window things
function reloadmodalcountent (itemIdtoLoad) {
        modwind = jQuery('#modalwindow');
        modalwindowcontent = jQuery('#modalwindow #modalwindow-content');
        modalwindowcontent.html('');
        //var selektor = '#maintopic-'+String(odditemid)+"-"+String(countitem);
        var selektor = '#'+itemIdtoLoad;
        //console.log (selektor);
        var topload = jQuery(selektor);
        
		// append  the content to modal window
		var contents = {};
		jQuery.extend(true, contents, topload.find(".modalwrapper"));
		modalwindowcontent.append(contents.html());	

		// clean, update class attribute for identifikation/left right navigation
        modwind.attr('class','');
        modwind.addClass(itemIdtoLoad); 
		
		//left right navigation / aktiv / inaktiv
        fbl = jQuery('#functionButtonsTop-Left');
        fbr = jQuery('#functionButtonsTop-Right');
        var maneuvre = itemIdtoLoad.split('-');
        odditemid = maneuvre[1];
        countitem = maneuvre[2];
        if (odditemid==0) {
                fbl.removeClass('aktivleft');
                fbl.attr("src","http://www.mairpro.com/Library/Resource/Image/modal-left1-off.png");
        } else 	{
                fbl.addClass('aktivleft');
                fbl.attr("src","http://www.mairpro.com/Library/Resource/Image/modal-left1.png");
        }
        if (odditemid == countitem-1) {
                fbr.removeClass('aktivright');
                fbr.attr("src","http://www.mairpro.com/Library/Resource/Image/modal-right1-off.png");
        } else 	{
                fbr.addClass('aktivright');
                fbr.attr("src","http://www.mairpro.com/Library/Resource/Image/modal-right1.png");
        }
                                
		// Adjust Scroll
        toppos = topload.position().top;
        modwind.css("top",toppos+"px");
        jQuery(document).scrollTop(toppos);
        
        modwind.show(function() {
	        var morethanwindow = modwind.position().top + modwind.height() + 100;
	        
			// adjust height and width of blurrer (gray background)
	        var blurrer = jQuery("#blurrer");
	        blurrer.css("width",jQuery(document).width()+"px");
	        if (morethanwindow < jQuery(document).height()) {
	                //blurrer.height(jQuery(document).height());
	                blurrer.css("height",jQuery(document).height()+"px");
	        }
	        else {
	                blurrer.css("height",morethanwindow+"px");
	        }
	        blurrer.fadeTo(200, 0.75);
		}); // end  modwind.show

} // end reloadmodalcountent
  
// this returns the width and height of images not displayed yet
function getImgSize(imgSrc){
    var newImg = new Image();
    newImg.src = imgSrc;
    var height = newImg.height;
    var width = newImg.width;
    p = $(newImg).ready(function(){
        return {width: newImg.width, height: newImg.height};
    });
   return Array(p[0]['width'],p[0]['height']);
}

						
	
	
