$(document).ready(function() {
  
//    $('#contactform').submit(function(){
//        $('#contactform').isFormValid();
//        return false;
//    })

	$('#contactform').validate({
		rules: {
    	 "tx_editcontactform_pi1[contactform_prename]" : {required: true},
    	 "tx_editcontactform_pi1[contactform_name]" : {required: true},
    	 "tx_editcontactform_pi1[contactform_email]" : {required: true, email : true},
    	 "tx_editcontactform_pi1[contactform_message]" : {required: true},
    	 "tx_editcontactform_pi1[contactform_gender]" : {required: true}
    	 
	   },
	   messages: {
	     "tx_editcontactform_pi1[contactform_prename]": {
	       required: contactform_em_prename
	     },
	     "tx_editcontactform_pi1[contactform_name]": {
	       required: contactform_em_name
	     },
   	     "tx_editcontactform_pi1[contactform_email]": {
	       required: contactform_em_email,
	       email: contactform_em_email
	     },
	     "tx_editcontactform_pi1[contactform_gender]": {
	       required: contactform_em_gender
	     },
	     "tx_editcontactform_pi1[contactform_message]" : {
	     	required: contactform_em_message
	     }
		},
	   errorPlacement: function(error, element) {
	       error.insertBefore(element);
	   },
	   highlight: function(element, errorClass, validClass) {
   		  $(element).parents(".row").addClass("errorRow");
	   },
       unhighlight: function(element, errorClass, validClass) {
		 $(element).parents(".row").removeClass("errorRow");
	  },
	  invalidHandler: function()
	  {
	  	if ($('#jqcInput').val() != jqSum)
  		{
			$('#jqcInput').parents(".row").addClass("errorRow");
			$('#jqcInput').parents(".row").find("p.captchaError").remove();

			//if ($('#jqcInput').parents(".row").find("p.captchaError").length == 0)
			if ($('#jqcInput').val() == '')
			{
				$('#jqcInput').parents(".row").prepend("<p class=\"captchaError\">" + contactform_em_captcha + "</p>")
			} else {
				$('#jqcInput').parents(".row").prepend("<p class=\"captchaError\">" + contactform_em_captcha_wrong + "</p>")			
			}
		}
		else
		{
			$('#jqcInput').parents(".row").removeClass("errorRow");
			$('#jqcInput').parents(".row").find("p.captchaError").remove();
		}
	  },
	  submitHandler: function(form)
	  {
  		if ($('#jqcInput').val() != jqSum)
  		{
			$('#jqcInput').parents(".row").addClass("errorRow");
			$('#jqcInput').parents(".row").find("p.captchaError").remove();
			//if ($('#jqcInput').parents(".row").find("p.captchaError").length == 0)
			//if ($('#jqcInput').parents(".row").find("p.captchaError").length == 0)
			//{
			//	$('#jqcInput').parents(".row").prepend("<p class=\"captchaError\">Please enter the captcha code</p>")
			//}
			if ($('#jqcInput').val() == '')
			{
				$('#jqcInput').parents(".row").prepend("<p class=\"captchaError\">" + contactform_em_captcha + "</p>")
			} else {
				$('#jqcInput').parents(".row").prepend("<p class=\"captchaError\">" + contactform_em_captcha_wrong + "</p>")			
			}
		}
		else
		{
			 $('#shaderContact_msg_wait').showShader();
       	                 var postData = $('#contactform').serialize();


						$.get($('#contactform').attr('action') + "&no_cache=1&"+postData, function(data){
    						$('#shaderContact_msg_success').showShader();
						});

/*	                 var dUrl=document.URL;
	                 var lUrl= dUrl.substring(dUrl.length-1, dUrl.length);
	                 var newUrl = '';
	                 if(lUrl == '/'){
	                    $.get(document.URL + "?no_cache=1&"+postData, function(data){
        	                 $('#shaderContact_msg_success').showShader();
	                    });
	                }else{
	                    $.get(document.URL + "&no_cache=1&"+postData, function(data){
        	               $('#shaderContact_msg_success').showShader();
        	            });
	                }
	                
*/        	            
        	            if (typeof(pageTracker) != "undefined") {
       	                    	pageTracker._trackPageview('/conversions/contactform/sent/' + document.getElementById('tx_editcontactform_pi1[contactform_emailfromJS]').value );
       	                    }
		}
	  },
	  
	   errorElement: "p"
   });

	/*Rechenaufgabe*/
	var lowerBound = 1;
        var upperBound = 10;
	var a = Math.floor(Math.random() * (upperBound - lowerBound + 1)) + lowerBound;
        var b = Math.floor(Math.random() * (upperBound - lowerBound + 1)) + lowerBound;
	$('#jqCaptcha').html(a + " + " + b + " = ");
	var jqSum = a+b;
	/*
	$('#submitIt').live('click', function(){
		if ($('#jqcInput').val() == jqSum) {
		}
		else {
			alert("Wrong sum!");
			return false;
		}
	});
	*/

});



function startContactform(emailTo,name,position,img,save){
    document.getElementById('tx_editcontactform_pi1[contactform_emailfromJS]').value = emailTo;
	if (name) {
	    $('#contactform_new_to').html(name);
	    $('#contactform_new_name').html(name);
	}
	if (img) {
	    img = img.replace(/%/, '<');
	    img = img.replace(/::/, '>');
	    $('#contactform_new_image').html(img);
	}
	
	if (position) {
	    $('#contactform_new_function').html(position);
	}
	if (save) {    
	    $('#contactform_new_phone').html(save);
    	}
    	
    $('#shaderContact_main').showShader();
    if (typeof(pageTracker) != "undefined") {
	    pageTracker._trackPageview('/conversions/contactform/open/');
    }
}

function reloadCaptcha(){
    $("#contactform_captcha_img").attr("src","/typo3conf/ext/captcha/captcha/captcha.php?id="+(new Date()).getTime());
}


jQuery.fn.isFormValid = function() {
    window.fails = false;
    $('[name^="tx_editcontactform_pi1[contactform_"]:input').each(function(){
        var obj = $(this);
        if(typeof (obj.attr('default')) == 'undefined' || obj.val() == obj.attr('default')){
            if(obj.attr("req")){
                window.fails = true;
                obj.css("color", "red");
            }
        }else{
            var emailAdd = $("#contactform_email").val();
            var matchPos = emailAdd.search('@');
            if(matchPos == -1){
                $("#contactform_email").css("color","red");
                window.fails = true;

            }else{
                $("#contactform_email").css("color","black");
            }
            obj.css("color", "black");
        }
    });
    var wert = base64_decode($.cookie('secreatString'));
    var capthaVal = $('#dd_captcha').val();
    if(wert != capthaVal){
        $('#shaderContact_msg_error').showShader();
        window.fails = true;
    }
    if(window.fails){
        $('#shaderContact_msg_error').showShader();
    }else{
        $('#shaderContact_msg_wait').showShader();
        var postData = $('#contactform').serialize();
	var dUrl=document.URL;
	var lUrl= dUrl.substring(dUrl.length-1, dUrl.length);
	var newUrl = '';
	
	if(lUrl == '/'){
	        $.get(document.URL + "?no_cache=1&"+postData, function(data){
        	    $('#shaderContact_msg_success').showShader();
	        });
	}else{
	        $.get(document.URL + "&no_cache=1&"+postData, function(data){
        	    $('#shaderContact_msg_success').showShader();
        	});
	}

    }
    
   
}

jQuery.fn.showShader = function() {
    //Screen Berechnung mitte
    var obj = $(this);
    var objHeight = obj.height();
    var objWidth = obj.width();

    //var doc = $(document);
    //var docHeight = doc.height();
    //var docWidth = doc.width();

    //var posTop = (docHeight / 2) - (objHeight /2);
   // var posLeft = (docWidth / 2) - (objWidth / 2);


    //neu
    var db = document.body;
    var dde = document.documentElement;
    var docHeight = Math.max(db.scrollHeight, dde.scrollHeight, db.offsetHeight, dde.offsetHeight, db.clientHeight, dde.clientHeight);
    var pageHeight = getPageSize();

    var offsets = getPosition(obj);
    var vanillaLeft = (($(window).width() - (objWidth)) / 2),
        vanillaTop = (($(window).height() - (objHeight)) / 2);

    var resultLeft = vanillaLeft + $(window).scrollLeft() - offsets[0],
        resultTop = vanillaTop + $(window).scrollTop() - offsets[1];


    $.blockUI.defaults = {
    // styles for the message when blocking; if you wish to disable
    // these and use an external stylesheet then do this in your code:
    // $.blockUI.defaults.css = {};
    css: {
    padding:        0,
    margin:         0,
    textAlign:      'center',
    color:          '#000',
    border:         '5px solid #aaa',
    backgroundColor:'',
    cursor:         'default',
    position:       'absolute'
    },

    // styles for the overlay
    overlayCSS:  {
    backgroundColor:'#000',
    opacity:        '0.5'
    },

    // z-index for the blocking overlay
    baseZ: 1000,

    // set these to true to have the message automatically centered
    centerX: true, // <-- only effects element blocking (page block controlled via css above)
    centerY: true,

    // allow body element to be stetched in ie6; this makes blocking look better
    // on "short" pages.  disable if you wish to prevent changes to the body height
    allowBodyStretch: true,

    // be default blockUI will supress tab navigation from leaving blocking content;
    constrainTabKey: true,

    // fadeOut time in millis; set to 0 to disable fadeout on unblock
    fadeOut:  400,

    // suppresses the use of overlay styles on FF/Linux (due to significant performance issues with opacity)
    applyPlatformOpacityRules: true
    };


    $.blockUI({ message: obj, css: {  cursor: 'pointer'}});

    
    if($.browser.msie){
        obj.css("position","fixed");
        obj.css("top","40px");
        obj.css("left",resultLeft);
        scrollTo(0,20);
    }else{
        obj.css("position","absolute");
        obj.css("top","40px");
        obj.css("left",resultLeft);
        scrollTo(0,20);
    }
    

    //--------------------------------------------------------------------------
}

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // NOTE Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

function base64_decode( data ) {    // Decodes data encoded with MIME base64
    //
    // +   original by: Tyler Akins (http://rumkin.com)


    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i=0, enc='';

    do {  // unpack four hexets into three octets using index points in b64
        h1 = b64.indexOf(data.charAt(i++));
        h2 = b64.indexOf(data.charAt(i++));
        h3 = b64.indexOf(data.charAt(i++));
        h4 = b64.indexOf(data.charAt(i++));

        bits = h1<<18 | h2<<12 | h3<<6 | h4;

        o1 = bits>>16 & 0xff;
        o2 = bits>>8 & 0xff;
        o3 = bits & 0xff;

        if (h3 == 64)      enc += String.fromCharCode(o1);
        else if (h4 == 64) enc += String.fromCharCode(o1, o2);
        else               enc += String.fromCharCode(o1, o2, o3);
    } while (i < data.length);

    return enc;
}
function getPageSize(){

        var xScroll, yScroll;

        if (window.innerHeight && window.scrollMaxY) {
            xScroll = document.body.scrollWidth;
            yScroll = window.innerHeight + window.scrollMaxY;
        } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
            xScroll = document.body.scrollWidth;
            yScroll = document.body.scrollHeight;
        } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
            xScroll = document.body.offsetWidth;
            yScroll = document.body.offsetHeight;
        }

        var windowWidth, windowHeight;
        if (self.innerHeight) {	// all except Explorer
            windowWidth = self.innerWidth;
            windowHeight = self.innerHeight;
        } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
            windowWidth = document.documentElement.clientWidth;
            windowHeight = document.documentElement.clientHeight;
        } else if (document.body) { // other Explorers
            windowWidth = document.body.clientWidth;
            windowHeight = document.body.clientHeight;
        }

        // for small pages with total height less then height of the viewport
        if(yScroll < windowHeight){
            pageHeight = windowHeight;
        } else {
            pageHeight = yScroll;
        }

        // for small pages with total width less then width of the viewport
        if(xScroll < windowWidth){
            pageWidth = windowWidth;
        } else {
            pageWidth = xScroll;
        }


        arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
        return arrayPageSize;
    }
    function getPosition(id){
        ele = document.getElementById(id)
        var topValue= 0,leftValue= 0;
        while(ele){
            leftValue += ele.offsetLeft;
            topValue += ele.offsetTop;
            ele = ele.offsetParent;
        }
        result = new Array(leftValue, topValue);
        return result;
    }

