var telFaxRegExp = /^(\s*(\+?\(?[\d]+\)?)?(\s*[-_\.\s\/]?\s*\(?[\d]+\)?)*\s*)?$/i;
var emailRegExp = /^\s*(("[\w-\s\ß\ä\ü\ö]+")|([\w-\ß\ä\ü\ö]+(?:\.[\w-\ß\ä\ü\ö]+)*)|("[\w-\s\ß\ä\ü\ö]+")([\w-\ß\ä\ü\ö]+(?:\.[\w-\ß\ä\ü\ö]+)*))(@((?:[\w-\ß\ä\ü\ö]+\.)*\w[\w-\ß\ä\ü\ö]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)\s*$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?\s*$)/i;
var textRegExp = /^([^<>]*)*$/i;

var errors = new Array(6);

var switchDD = true;

var mainSelected = LL['all']; // LL['all'] !!!!
var subSelected = LL['all'];
var isFiltered = false;

var intervallID;
var intervallPrevNext;
var tempInterval;
var intervallDDMenu;
var intervallCloseDDMenu;
var loadingIntervallID;

var isScrolling = false;

var menuItems = [];
var menuCounter;
var currentPosition = 0;

var currentHash, lastHash, intervalHash;

var contactTemplate;

$(document).ready(function(){
    /* show subnavi when JS active */
    $('.subnaviplacement').css('display', 'block');
    /* set hash at start */
    if ((window.location.hash == undefined || window.location.hash == "" || window.location.hash == "#") && showUid == 0) {
        window.location.hash = "#pro1";
    }
    intervalHash = setInterval('backButton()', 200);
    /****************************** initialize submenu ******************************/
    if (jQuery.support.opacity == true) {
        fadeInContent();
    }
    setLoadingGif();
    reinitializeSubmenu();
    filterProjects(mainSelected, subSelected, categories, projects);
    loadGallery();
    
    iniPopUpContact();
    
    /******************************* eventhandler prev/next Button ********************************/
    var $prevEntry = $('.prevEntry');
    var $nextEntry = $('.nextEntry');
    $prevEntry.bind('click', function(){
        if (!isScrolling) {
            if (currentPosition > 0) {
                currentPosition--;
                setFocus();
                if (currentPosition < menuCounter - 4 && percentInView < .99) {
                    scrollUp();
                }
            }
            clearInterval(intervallPrevNext);
            intervallPrevNext = setTimeout('prevNext()', 300);
        }
    }).bind('mousedown', function(){
        ctrlDownStr('.prevEntry');
        tempInterval = setTimeout("intervallID = setInterval('scrollUp()', 100); isScrolling = true;", 300);
    }).bind('mouseup', function(){
        ctrlUpOverStr('.prevEntry');
        clearInterval(intervallID);
        clearInterval(tempInterval);
        tempInterval = setTimeout("isScrolling = false;", 300);
    }).bind('mouseover', function(){
        ctrlUpOverStr('.prevEntry');
        clearInterval(intervallID);
        clearInterval(tempInterval);
        tempInterval = setTimeout("isScrolling = false;", 300);
    }).bind('mouseleave', function(){
        ctrlLeaveStr('.prevEntry');
        clearInterval(intervallID);
        clearInterval(tempInterval);
        tempInterval = setTimeout("isScrolling = false;", 300);
    });
    
    $nextEntry.bind('click', function(){
        if (!isScrolling) {
            if (currentPosition != menuCounter - 1) {
                currentPosition++;
                setFocus();
                if (currentPosition > 3 && percentInView < .99) {
                    scrollDown();
                }
            }
            clearInterval(intervallPrevNext);
            intervallPrevNext = setTimeout('prevNext()', 300);
        }
    }).bind('mousedown', function(){
        ctrlDownStr('.nextEntry');
        tempInterval = setTimeout("intervallID = setInterval('scrollDown()', 100); isScrolling = true;", 300);
    }).bind('mouseup', function(){
        ctrlUpOverStr('.nextEntry');
        clearInterval(intervallID);
        clearInterval(tempInterval);
        tempInterval = setTimeout("isScrolling = false;", 300);
    }).bind('mouseover', function(){
        ctrlUpOverStr('.nextEntry');
        clearInterval(intervallID);
        clearInterval(tempInterval);
        tempInterval = setTimeout("isScrolling = false;", 300);
    }).bind('mouseleave', function(){
        ctrlLeaveStr('.nextEntry');
        clearInterval(intervallID);
        clearInterval(tempInterval);
        tempInterval = setTimeout("isScrolling = false;", 300);
    });
    
    /****************************** Bind EventListener to Drop Down Boxes ******************************/
    var $mainDropDown = $('#mainDropDown1');
    $mainDropDown.bind("click", function(){
        fillMainPopUp('#mainDropDown1', '#subDropDown1');
    }).bind('mouseup', ddUpOver).bind('mouseover', ddUpOver).bind('mouseleave', ddLeave);
    var $subDropDown = $('#subDropDown1');
    $subDropDown.bind("click", function(){
        fillSubPopUp('#subDropDown1');
    }).bind('mouseup', ddUpOver).bind('mouseover', ddUpOver).bind('mouseleave', ddLeave);
    var $popUp = $('#popUp');
    $popUp.bind("mouseout", function(){
        intervallDDMenu = setTimeout('closeDD()', 500);
    }).bind("mouseover", function(){
        clearInterval(intervallDDMenu);
    });
    reinitializeSubmenu();
}); // END DOCUMENT.READY
/******************************** Filter Projects **************************/
var filterProjects = function(mainfilter, subfilter, cats, pros){
    removeSubmenuItemListeners();
    $('#subnavigation').empty();
    menuCounter = 0;
    currentPosition = 0;
    
    for (var i = 0; i < pros.length; i++) {
        var id, image, url, title, html;
        
        // show filtered projects
        if (mainfilter != LL['all'] || subfilter != LL['all']) {
            if (pros[i] != undefined) {
            
                for (var j = 0; j < pros[i].category.length; j++) {
                    // main category choosen
                    if (mainfilter == LL['all'] && subfilter == LL['all']) {
                        menuItems[menuCounter] = i;
                        writeListItem(i, pros[i].image, pros[i].title, pros[i].description, pros[i].url, menuCounter);
                        menuCounter++;
                        j = pros[i].category.length;
                    }
                    else 
                        if (pros[i].category[j] == mainfilter && subfilter == LL['all']) {
                            menuItems[menuCounter] = i;
                            writeListItem(i, pros[i].image, pros[i].title, pros[i].description, pros[i].url, menuCounter);
                            menuCounter++;
                            j = pros[i].category.length;
                        }
                        else 
                            if (pros[i].category[j] == mainfilter && subfilter != LL['all']) {
                                for (var h = 0; h < pros[i].category.length; h++) {
                                    if (pros[i].category[h] == subfilter) {
                                        menuItems[menuCounter] = i;
                                        writeListItem(i, pros[i].image, pros[i].title, pros[i].description, pros[i].url, menuCounter);
                                        menuCounter++;
                                        j = pros[i].category.length;
                                    }
                                }
                            }
                }
            }
            // show all projects
        }
        else {
            if (mainfilter == LL['all'] && subfilter == LL['all']) {
                if (pros[i] != undefined) {
                    menuItems[menuCounter] = i;
                    writeListItem(i, pros[i].image, pros[i].title, pros[i].description, pros[i].url, menuCounter);
                    menuCounter++;
                }
            }
        }
    }
    
    setProjectCount(menuCounter, menuItems.length);
    addSubmenuItemListeners();
    
	if (window.location.hash != '#off') {
		/* loadContent() for bookmarks */
		if (isFiltered == false && showUid > 0 && (window.location.hash == "" || window.location.hash == "#" || window.location.hash == undefined)) {
			refreshPage(showUid);
		}
		/* loadContent() after submenu was filtered */
		else 
			if (isFiltered == true) {
				loadContent(projects[menuItems[currentPosition]].url);
				/* generate hash after filtering */
				window.location.hash = "#pro" + menuItems[0];
				isFiltered = false;
			}
			else {
				var tempHash = window.location.hash.split('ro');
				var tempHashFront = tempHash[0];
				if (tempHashFront == "#p") {
					var extractedID = tempHash[1];
					refreshPage(extractedID);
					extractedID = 0;
				}
			}
		setFocus();
	} else {
		removeFocus();
		$('.loading').remove();
	}
	
    
    
    htmlTemp = '<li class="subItemAlign">';
    htmlTemp += '<span class="linkProject"><span class="subFloatImage clear">';
    htmlTemp += '<div class="subItemSpacer">&nbsp;</div>';
    htmlTemp += '</span>';
    htmlTemp += '</span></li>';
    
    $('#subnavigation').append($(htmlTemp));
    
    reinitializeSubmenu();
}
/****************************** Hilfsfunktionen ******************************/
var backButton = function(){
    currentHash = window.location.hash;
    if (currentHash != lastHash && window.location.hash != "" && window.location.hash != "#") {
        var temp = window.location.hash.split('ro');
        var hash = temp[1];
        refreshPage(hash);
        currentHash = window.location.hash;
        lastHash = currentHash;
    }
    else 
        if (showUid == 0) {
            if ((currentHash == "" || currentHash == "#" || currentHash == undefined) && currentPosition != 0) {
                currentPosition = 0;
                alert('test');
                window.location.hash = "#pro1";
                loadContent(projects[menuItems[currentPosition]].url);
                setFocus();
            }
        }
}
var refreshPage = function(id){
    loadContent(projects[id].url);
    $('.linkProject').each(function(){
        if ($(this).attr('id') == id) {
            currentPosition = $(this).attr('name');
            setFocus();
        }
    });
}
var setLoadingGif = function(){
    $('.loading').remove();
    var loading = '<div><img class="loading" src="' + loadingImg + '"></div>';
    $('.projectCount').after($(loading));
}
var loadingFadeOut = function(){
    $('.loading').fadeOut(1000, function(){
        $(this).remove();
    });
}
var setProjectCount = function(count, maxNr){
    var projectCountText;
    if (maxNr > 1 || maxNr == 0) {
        projectCountText = count + " " + LL['Projects'];
    }
    else 
        if (maxNr == 1) {
            projectCountText = count + " " + LL['Projects'];
        }
    $('.projectCount').text(projectCountText);
}
var loadContent = function(projectURL){
    if (menuCounter > 0) {
        $.ajax({
            cache: false,
            type: "POST",
            url: projectURL, //htmlDetails + elementID,
            dataType: "html",
            before: setLoadingGif(),
            // error: function(){
            //    alert("Error: \""+htmlDetails + elementID+"\"  XMLHttpRequest not successfull!");
            // },
            success: function(htmlFile){
                $('.contentProjects').html(htmlFile);
                var $imageContainerIMG = $('.imageContainer img');
                $imageContainerIMG.css("opacity", "0").css("-moz-opacity", "0").css('-ms-filter:', '"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)"').css("filter", "alpha(opacity=0)").animate({
                    opacity: 1
                }, 2000);
                loadGallery();
                loadingFadeOut();
            }
        });
    }
}

var writeListItem = function(index, img, tit, des, url, counter){
    htmlTemp = '<li class="subItemAlign">';
    htmlTemp += '<span class="linkProject" id="' + index + '" name="' + counter + '"><span class="subFloatImage clear">';
    htmlTemp += '<img class="mouseOver" src="' + img + '" alt="thumb" />';
    htmlTemp += '</span>';
    htmlTemp += '<span class="subFloatTitle" name="' + counter + '">' + tit + '<br/><span class="descriptionColor">' + des + '</span></span>';
    htmlTemp += '</span></li>';
    
    $('#subnavigation').append($(htmlTemp));
}
var fillMainPopUp = function(containerMain, containerSub){
    if (switchDD == true) {
    
        var firstLine = '<li class="listItem" id="allMain">' + LL['all'] + '</li>';
        $('#popUpContainer').append($(firstLine));
        $('#allMain').bind("click", function(event){
            stopPropag(event);
            catMainText = $(this).text();
            catSubText = LL['all'];
            mainSelected = LL['all'];
            subSelected = LL['all'];
            $(containerMain).html(catMainText);
            $(containerSub).html(catSubText);
            closeDD();
            window.location.hash = "";
			isFiltered = true;
            filterProjects(mainSelected, subSelected, categories, projects);
        });
        
        for (var i = 0; i < categories.length; i++) {
            var mainCategory, catID, catTitle, catMainText, catSubText;
            
            if (categories[i] != undefined && categories[i].parent == 0) {
                catTitle = categories[i].title;
                catID = categories[i].id;
                mainCategory = '<li class="listItem" id="cat' + catID + '">' + catTitle + '</li>';
                $('#popUpContainer').append($(mainCategory));
                
                /****************************** add eventlistener - click ******************************/
                $('#cat' + catID).bind("click", function(event){
                    stopPropag(event);
                    
                    catMainText = $(this).text();
                    catSubText = LL['all'];
                    $(containerMain).html(catMainText);
                    $(containerSub).html(catSubText);
                    
                    closeDD();
                    
                    var tempString = $(this).attr('id');
                    mainSelected = tempString.substr(3);
                    subSelected = LL['all'];
                    window.location.hash = "";
					isFiltered = true;
                    filterProjects(mainSelected, subSelected, categories, projects);
                });
            }
        }
        openDD("main");
    }
    else 
        if (switchDD == false) {
            closeDD();
        }
}
var fillSubPopUp = function(containerSub){
    if (switchDD == true) {
    
        var firstLine = '<li class="listItem" id="allSub">' + LL['all'] + '</li>';
        $('#popUpContainer').append($(firstLine));
        $('#allSub').bind("click", function(event){
            stopPropag(event);
            catSubText = $(this).text();
            subSelected = LL['all'];
            $(containerSub).html(catSubText);
            closeDD();
            window.location.hash = "";
			isFiltered = true;
            filterProjects(mainSelected, subSelected, categories, projects);
        });
        
        for (var i = 0; i < categories.length; i++) {
            var subCategory, catID, catTitle, catMainText, catSubText, parent;
            
            if (categories[i] != undefined && categories[i].parent != 0) {
                catTitle = categories[i].title;
                catID = categories[i].id;
                parent = categories[i].parent;
                subCategory = '<li class="listItem" id="sub' + catID + '">' + catTitle + '</li>';
                if (parent == mainSelected) 
                    $('#popUpContainer').append($(subCategory));
                
                /****************************** add eventlistener - click ******************************/
                $('#sub' + catID).bind("click", function(event){
                    stopPropag(event);
                    
                    catSubText = $(this).text();
                    $(containerSub).html(catSubText);
                    
                    closeDD();
                    var tempString = $(this).attr('id');
                    subSelected = tempString.substr(3);
                    window.location.hash = "";
					isFiltered = true;
                    filterProjects(mainSelected, subSelected, categories, projects);
                });
            }
        }
        openDD("sub");
    }
    else 
        if (switchDD == false) {
            closeDD();
        }
}
var stopPropag = function(e){
    if (e.stopPropagation) {
        e.stopPropagation();
    } //For 'Good' browsers
    else {
        e.cancelBubble = true;
    } //For IE
}
var reinitializeSubmenu = function(){
    $('#pane1').jScrollPane();
}
var closeDD = function(){
    $('#mainDropDown1').unbind('click');
    $('#subDropDown1').unbind('click');
    switchDD = true;
    $('#popUp').addClass("popUpDisabled").fadeOut('fast');
    intervallCloseDDMenu = setTimeout('closeIt()', 300);
}
var closeIt = function(){
    clearInterval(intervallCloseDDMenu);
    $('#popUp').removeClass("popUpMain").removeClass("popUpSub");
    $('#mainDropDown1').css("background-position", "0 0");
    $('#subDropDown1').css("background-position", "0 0");
    $('#popUpContainer li').remove();
    
    $('#mainDropDown1').bind("click", function(){
        fillMainPopUp('#mainDropDown1', '#subDropDown1');
    });
    $('#subDropDown1').bind("click", function(){
        fillSubPopUp('#subDropDown1');
    });
}
var openDD = function(selection){
    if (selection == "main") {
        $('#popUp').addClass("popUpMain").fadeIn('fast');
        $('#mainDropDown1').css("background-position", "0 -32px");
        switchDD = false;
    }
    else {
        $('#popUp').addClass("popUpSub").fadeIn('fast');
        $('#subDropDown1').css("background-position", "0 -32px");
        switchDD = false;
    }
}
var scrollDown = function(){
    $('#pane1')[0].scrollBy(48);
    return false;
}
var scrollUp = function(){
    $('#pane1')[0].scrollBy(-48);
    return false;
}
var prevNext = function(){
    //alert ("currentPosition="+currentPosition+" --- menuItems="+menuItems[currentPosition]+" --- projects[]="+projects[menuItems[currentPosition]].url);
    window.location.hash = '#pro' + menuItems[currentPosition];
    currentHash = window.location.hash;
    lastHash = currentHash;
    loadContent(projects[menuItems[currentPosition]].url);
}
var setFocus = function(){
    $('.linkProject').each(function(){
        var selectedElement = $(this).find(':nth-child(2)');
        if ($(selectedElement).attr('name') == currentPosition) {
            highlightItem($(this));
            addSubmenuItemListeners();
            removeSubmenuItemListenersSingle($(this));
        }
        else {
            deHighlightItem($(this));
        }
    });
}
var removeFocus = function() {
	$('.linkProject').each(function(){ 
    	deHighlightItem($(this));
    });
}
var removeSubmenuItemListeners = function(){
    $('.linkProject').each(function(){
        $(this).unbind('click', submenuClick).unbind('mouseover', submenuOver).unbind('mouseleave', submenuLeave);
    });
}
var removeSubmenuItemListenersSingle = function(obj){
    $(obj).unbind('click', submenuClick).unbind('mouseover', submenuOver).unbind('mouseleave', submenuLeave);
}
var addSubmenuItemListeners = function(){
    $('.linkProject').each(function(){
        $(this).bind('click', submenuClick).bind('mouseover', submenuOver).bind('mouseleave', submenuLeave);
    });
}
var submenuClick = function(event){
    $('.linkProject').each(function(){
        deHighlightItem($(this));
    });
    highlightItem($(this));
    addSubmenuItemListeners();
    removeSubmenuItemListenersSingle($(this));
    //alert ("$(this).attr('id')="+$(this).attr('id')+" --- projects[]="+projects[$(this).attr('id')].url);
    loadContent(projects[$(this).attr('id')].url);
    currentPosition = $(this).attr('name');
    setFocus();
    
    /* set hash for bookmarks */
    window.location.hash = '#pro' + $(this).attr('id'); //projects[$(this).attr('id')].id;
    currentHash = '#pro' + $(this).attr('id'); //projects[$(this).attr('id')].id;
    lastHash = currentHash;
}
var submenuOver = function(){
    highlightItem($(this));
}
var submenuLeave = function(){
    deHighlightItem($(this));
}
var highlightItem = function(ele){
    var $ele1 = ele.find(":nth-child(1)");
    if (checkVersion() > 6 || navigator.appName != 'Microsoft Internet Explorer') {
        $ele1.css('opacity', '1').css("-moz-opacity", "1").css('-ms-filter:', '"progid:DXImageTransform.Microsoft.Alpha(Opacity=99)"').css("filter", "alpha(opacity=99)");
    }
    var $ele2 = ele.find(":nth-child(2)");
    $ele2.css('color', '#82aaff').find(":nth-child(2)").css('color', '#888888');
}
var deHighlightItem = function(ele){
    var $ele1 = ele.find(":nth-child(1)");
    if (checkVersion() > 6 || navigator.appName != 'Microsoft Internet Explorer') {
        $ele1.css('opacity', '.60').css("-moz-opacity", ".60").css('-ms-filter:', '"progid:DXImageTransform.Microsoft.Alpha(Opacity=60)"').css("filter", "alpha(opacity=60)");
    }
    var $ele2 = ele.find(":nth-child(2)");
    $ele2.css('color', '#cccccc').find(":nth-child(2)").css('color', '#888888');
}


var fadeInContent = function(){
    $('.subnaviplacement').css("opacity", "0").css("-moz-opacity", "0").css('-ms-filter:', '"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)"').css("filter", "alpha(opacity=0)").animate({
        opacity: 1
    }, 2000);
    
    $('.contentProjects').css("opacity", "0").css("-moz-opacity", "0").css('-ms-filter:', '"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)"').css("filter", "alpha(opacity=0)").animate({
        opacity: 1
    }, 2000);
}
var ctrlDown = function(){
    $(this).css("background-position", "0 -34px");
}
var ctrlUpOver = function(){
    $(this).css("background-position", "0 -17px");
}
var ctrlLeave = function(){
    $(this).css("background-position", "0 0");
}
var ctrlDownStr = function(str){
    $(str).css("background-position", "0 -34px");
}
var ctrlUpOverStr = function(str){
    $(str).css("background-position", "0 -17px");
}
var ctrlLeaveStr = function(str){
    $(str).css("background-position", "0 0");
}
var ddUpOver = function(){
    $(this).css("background-position", "0 -16px");
}
var ddLeave = function(){
    if (switchDD == true) 
        $(this).css("background-position", "0 0");
}


var getInternetExplorerVersion = function()// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
    var rv = -1; // Return value assumes failure.
    if (navigator.appName == 'Microsoft Internet Explorer') {
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null) 
            rv = parseFloat(RegExp.$1);
    }
    return rv;
}
var checkVersion = function(){
    var ver = getInternetExplorerVersion();
    return ver;
}

var iniPopUpContact = function(){
    $('.popUpContact a').bind('click', openContact);
    contactTemplate = '<div class="contactContainer">';
    contactTemplate += '<div class="transparentLayer">';
    contactTemplate += '<div class="innerContact">';
    contactTemplate += '<div class="contactHeader">' + LL['contactHeader'] + '</div>';
    contactTemplate += '<div class="errorMessage"></div>';
    contactTemplate += '<div class="contactInfo">' + LL['contactInfotext'] + '</div>';
    contactTemplate += '<div class="contactInnerContainer">';
    contactTemplate += '<form action="" method="get" name="contactform" id="cform"><div class="ccontactLeft"><ol>';
    contactTemplate += '<li><label for="cfirma" id="cfirmaLabel">' + LL['contactFirma'] + '</label><input name="caderacontact[firma]" id="cfirma" type="text"></li>';
    contactTemplate += '<li><label for="cname" id="cnameLabel">' + LL['contactName'] + '</label><input name="caderacontact[name]" id="cname" type="text" />';
    contactTemplate += '<label for="cvorname" id="cvornameLabel">' + LL['contactVorname'] + '</label><input name="caderacontact[vorname]" id="cvorname" type="text" /></li>';
    contactTemplate += '<li><label for="ctel" id="ctelLabel">' + LL['contactTelefon'] + '</label><input name="caderacontact[tel]" id="ctel" type="text"></li>';
    contactTemplate += '<li><label for="cemail" id="cemailLabel">' + LL['contactEmail'] + '</label><input name="caderacontact[email]" id="cemail" type="text"></li>';
    contactTemplate += '<li><label for="cihrText" id="cihrTextLabel">' + LL['contactText'] + '</label><textarea name="caderacontact[ihrText]" id="cihrText"></textarea></li>';
    contactTemplate += '<li><label for="cihrInteresse" id="cihrTextLabel">' + LL['contactInteresse'] + '</label>';
    contactTemplate += '<ul class="selections"><li><input name="caderacontact[interesseID]" id="cinteresseID" type="checkbox"><label for="cinteresseID" id="cinteresseIDLabel">Industrial Design</label></li>';
    contactTemplate += '<li><input name="caderacontact[interesseUID]" id="cinteresseUID" type="checkbox"><label for="cinteresseUID" id="cinteresseUIDLabel">User Interface Design</label></li>';
    contactTemplate += '<li><input name="caderacontact[interesseICO]" id="cinteresseICO" type="checkbox"><label for="cinteresseICO" id="cinteresseICOLabel">Icon Design</label></li>';
    contactTemplate += '<li><input name="caderacontact[interesseSonstiges]" id="cinteresseSonstiges" type="checkbox"><label for="cinteresseSonstiges" id="cinteresseSonstigesLabel">Integrated Design</label></li></ul>';
    contactTemplate += '<li style="clear: both"><input name="caderacontact[submit]" id="csubmitBtn" value="' + LL['contactSubmit'] + '" type="button"><div class="closeContact">' + LL['contactClose'] + '</div></li>';
    contactTemplate += '</ol></div></form></div></div></div></div>';
}
var sendAjaxMail = function(event){
    event.preventDefault();
    
    if (errors[0] == true ||
    errors[1] == true ||
    errors[2] == true ||
    errors[3] == true ||
    errors[4] == true ||
    errors[5] == true) {
        $('.contactHeader').css('backgroundColor', '#ff0000').html(LL['error']);
        return false;
    }
    else {
        var mailURL = 'index.php?eID=sgAjaxMail&type=ppv&';
        mailURL += 'caderacontact[firma]=' + $('#cfirma').val() + '&';
        mailURL += 'caderacontact[name]=' + $('#cname').val() + '&';
        mailURL += 'caderacontact[vorname]=' + $('#cvorname').val() + '&';
        mailURL += 'caderacontact[tel]=' + $('#ctel').val() + '&';
        mailURL += 'caderacontact[email]=' + $('#cemail').val() + '&';
        mailURL += 'caderacontact[ihrText]=' + $('#cihrText').val() + '&';
        mailURL += 'caderacontact[interesseID]=' + $('#cinteresseID:checked').val() + '&';
        mailURL += 'caderacontact[interesseUID]=' + $('#cinteresseUID:checked').val() + '&';
        mailURL += 'caderacontact[interesseICO]=' + $('#cinteresseICO:checked').val() + '&';
        mailURL += 'caderacontact[interesseSonstiges]=' + $('#cinteresseSonstiges:checked').val() + '&';
        mailURL += 'L=' + activeLang;
		
		//alert (mailURL);
        
        $('.contactHeader').css('backgroundColor', '#465074').html(LL['contactHeader']);
        $('.contactInnerContainer, .contactInfo').hide();
        $('.innerContact').animate({
            height: '150px'
        }, 200);
        $('.errorMessage').html('<img class="contactLoading" src="' + loadingImg + '">' + LL['try']).show();
        
        $.ajax({
            cache: false,
            type: "POST",
            url: mailURL,
            dataType: "xml",
            error: function(){
                alert("Error: XMLHttpRequest not successfull! - Url: " + mailURL);
            },
            success: function(xmlFile){
                $(xmlFile).find("result").each(function(){
                    var errorcode = $(this).find("errorcode").text();
                    switch (errorcode) {
                        case '0':
                            $('.errorMessage').html(LL['success']);
                            var vanishInterval = setTimeout('$(".contactContainer").remove();', 1500);
                            break;
                        case '1':
                            $('.contactInnerContainer, .contactInfo').show();
                            $('.errorMessage').hide();
							if(checkVersion() == 7) {
								$('.innerContact').animate({
                                	height: '560px'
                            	}, 200);
							} else {
								$('.innerContact').animate({
                                	height: '530px'
                            	}, 200);
							}
                            
                            $('.contactHeader').css('backgroundColor', '#ff0000').html(LL['problem']);
                            break;
                        case '2':
                            $('.contactInnerContainer, .contactInfo').show();
                            $('.errorMessage').hide();
                            if(checkVersion() == 7) {
								$('.innerContact').animate({
                                	height: '560px'
                            	}, 200);
							} else {
								$('.innerContact').animate({
                                	height: '530px'
                            	}, 200);
							}
                            $('.contactHeader').css('backgroundColor', '#ff0000').html(LL['error']);
                            break;
                        default:
                            break;
                    }
                });
            }
        });
        return false;
    }
}
var openContact = function(event){
    if (checkVersion() == 6) {
        return true;
    }
    else {
        event.preventDefault();
        $('body').append($(contactTemplate));
        $('.errorMessage').hide();
        setDimensionsContact();
        $(window).resize(setDimensionsContact);
        $('#csubmitBtn').bind('click', sendAjaxMail).bind('mousedown', submitDown).bind('mouseup', submitOut).bind('mouseenter', submitOver).bind('mouseleave', submitOut);
        $('.closeContact').bind('click', closeContact).bind('mousedown', submitDown).bind('mouseup', submitOut).bind('mouseenter', submitOver).bind('mouseleave', submitOut);
        
        /***** contact ini *****/
        for (var i = 0; i < errors.length; i++) {
            errors[i] = false;
        }
        
        /* firma check */
        $('#cfirma').bind('blur', function(){
            var inputFirmaValue = document.contactform.cfirma.value;
            checkInput(inputFirmaValue, textRegExp, "#cfirmaLabel", 0);
        });
        /* name check */
        $('#cname').bind('blur', function(){
            var inputNameValue = document.contactform.cname.value;
            checkInput(inputNameValue, textRegExp, "#cnameLabel", 1);
        });
        /* vorname check */
        $('#cvorname').bind('blur', function(){
            var inputVornameValue = document.contactform.cvorname.value;
            checkInput(inputVornameValue, textRegExp, "#cvornameLabel", 2);
        });
        /* tel check */
        $('#ctel').bind('blur', function(){
            var inputTelefonValue = document.contactform.ctel.value;
            checkInput(inputTelefonValue, telFaxRegExp, "#ctelLabel", 3);
        });
        /* email check */
        $('#cemail').bind('blur', function(){
            var inputEmailValue = document.contactform.cemail.value;
            checkInput(inputEmailValue, emailRegExp, "#cemailLabel", 4);
        });
        /* ihrText check */
        $('#cihrText').bind('blur', function(){
            var inputTextValue = document.contactform.cihrText.value;
            checkInput(inputTextValue, textRegExp, "#cihrTextLabel", 5);
        });
    }
}
var closeContact = function(event){
    event.preventDefault();
    $('.contactContainer').remove();
    return false;
}
var setDimensionsContact = function(){
    var viewportwidth;
    var viewportheight;
    
    if (typeof window.innerWidth != 'undefined') {
        viewportwidth = window.innerWidth, viewportheight = window.innerHeight
    }
    else 
        if (typeof document.documentElement != 'undefined' &&
        typeof document.documentElement.clientWidth !=
        'undefined' &&
        document.documentElement.clientWidth != 0) {
            viewportwidth = document.documentElement.clientWidth, viewportheight = document.documentElement.clientHeight
        }
        else {
            viewportwidth = document.getElementsByTagName('body')[0].clientWidth, viewportheight = document.getElementsByTagName('body')[0].clientHeight
        }
    
    $('.transparentLayer').css('width', viewportwidth).css('height', viewportheight);
    if (checkVersion() == 6) {
        $('.transparentLayer').css('margin-top', -viewportheight);
    }
}
var submitDown = function(){
    $(this).css("background-position", "0 -38px");
}
var submitOver = function(){
    $(this).css("background-position", "0 -19px");
}
var submitOut = function(){
    $(this).css("background-position", "0 0");
}
var checkInput = function(inputFieldValue, regExp, errId, index){
    if (inputFieldValue.search(regExp) == -1 && inputFieldValue != "") {
        $(errId).removeClass('nonErrorColor').addClass('errorColor');
        errors[index] = true;
        $('.contactHeader').css('backgroundColor', '#ff0000').html(LL['error']);
    }
    else {
        $(errId).removeClass('errorColor').addClass('nonErrorColor');
        errors[index] = false;
        if (errors[0] == false &&
        errors[1] == false &&
        errors[2] == false &&
        errors[3] == false &&
        errors[4] == false &&
        errors[5] == false) {
            $('.contactHeader').css('backgroundColor', '#465074').html(LL['contactHeader']);
        }
    }
	if(inputFieldValue == "") {
			$(errId).removeClass('nonErrorColor').remove('errorColor');
	}
}
