$(document).ready(function() {
  
    $('#contactform').submit(function(){
        $('form').isFormValid();
        return false;
    })

});



function startContactform(emailTo){
    document.getElementById('tx_editcontactform_pi1[contactform_emailfromJS]').value = emailTo;
    $('#shaderContact_main').showShader();
}

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();
        $.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:         '0px 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;
    }
