/**
 * Globaler CSS-/JS-Controller (based on jQuery JavaScript Library)
 *
 * @copyright       Copyright (c) 2009 Daniel Quappe. All rights reserved.
 * @author          Created by dan on 04.11.2009 12:50:02. Last Editor: $Author: quappe $
 * @version         $Revision: 761 $ ($Date: 2012-01-24 19:42:00 +0100 (Di, 24 Jan 2012) $)
 */
$(document).ready(function()
{ 
    /* Activate pngFix on document.ready */
    // Deaktiviert, da Z&Z auch ein Script dafuer integriert haben, DQ 20100514
    //$(document).pngFix();

    /* DOM-Bindings zu verschiedenen Plugins initialisieren (Fancybox etc.) */
    initBindings();

    /* Verstecken definierter Bereiche, damit diese toggelbar sind, wenn Javascript aktiviert ist */
    $(".hideOnReady").hide();

    /* Freischaltung der Preview-Buttons, wenn Javascript aktiviert ist */
    $("#previewButton").show();

    /* Animiertes Ein-/Ausblenden der Flash-Message-Boxen */
    var flashMessageId;
    var animateFlashMessage = function(el)
    {
        // "Normale" Message (ohne positiv/negativ) werden nicht ausgeblendet
        if(!el.hasClass('message'))
        {
            // Ausblenden per SlideUp-Effekt
            setTimeout(function(){el.slideUp('slow')}, 6000);        
        }
    }
    if((flashMessageId = $("#authMessage")).length > 0) {   animateFlashMessage( flashMessageId ); };
    if((flashMessageId = $("#flashMessage")).length > 0) {   animateFlashMessage( flashMessageId ); };

    /* Ausgabe von Seiteninhalten und SWF-Videos per Fancybox-Overlay (Videos per Click wegen Anpassung von this.href) */
    $(".fancyhtml").click(function() {
        $.fancybox({
            'type': 'iframe',
            'width': 560,
            'height': 500,
            'href': addParameterToURL(this.href, 'printversion', '1'),
            'onComplete': function() {
        	    $.fancybox.hideActivity();
        	}, 
            'autoScale': false,
            'autoDimensions': false,
            'zoomSpeedIn': 200, 
            'zoomSpeedOut': 200, 
            'overlayShow': true,
            'overlayOpacity': 0.2
        });
        $.fancybox.showActivity();
        return false;
    });
    $(".fancyswf").click(function() {
        $.fancybox({
            'padding'       : 0,
            'autoScale'     : false,
            'transitionIn'  : 'none',
            'transitionOut' : 'none',
            'title'         : false,
            'width'         : 640,
            'height'        : 390,
            'href'          : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/') + '&version=3',
            'type'          : 'swf',
            'overlayOpacity': 0.2,
            'swf'           : {
                'wmode'     : 'transparent',
                'allowfullscreen'   : 'true'
            }
        });
        return false;
    });
    
    /* Akkordeon */
    var accordionSpeed = 300;
    $("#accordion .item_header").click(function(){
        if($(this).hasClass('active')) {
            $(this).removeClass("active").next('div.item_content').slideUp(accordionSpeed);
        } else {
            $(this).addClass("active").next('div.item_content').slideDown(accordionSpeed);
        }
    })
});

/**
 * DOM-Binding zu verschiedenen Plugins initialisieren (Fancybox etc.) 
 * Diese Auslagerung macht Sinn, damit nach einem AJAX-POSTBACK die 
 * Bindungen erneut zentral initialisiert werden koennen
 *
 * @return void
 *
 * @access public
 * @author Daniel Quappe
 */
function initBindings()
{
    /* Infoicon als qTip */
    /* Wichtig:
       Markieren der bereits in qTip umgewandelten Elemente mit dem Klassennamen "usesqtip" (um sie wiederzuerkennen), 
       da bei Ihnen das title-Attribut (durch qTip automatisch) geleert wurde und ein Re-initBindings() nach AJAX-Calls 
       die vorhandenen Tooltipps praktisch zerstoeren/unleserlich machen (doppelte linke untere Ecke durch leeren Titel)
    */
    $('img:not(.usesqtip).infoicon[title], a:not(.usesqtip).qtiplink[title]').qtip({
      position: {
        corner: { target: 'topMiddle', tooltip: 'bottomRight' },
        adjust: { screen: true, y: -3 }
      },
      style: {
        name: 'dortex',
        padding: '7px 13px',
        width: { max: 350, min: 0 },
        tip: true
      }
    }).addClass('usesqtip');

    /* Fancybox Bilder */
    $("a[rel^='fancybox']").fancybox({
        'zoomSpeedIn': 200, 
        'zoomSpeedOut': 200, 
        'overlayShow': true,
        'overlayOpacity': 0,
        'hideOnContentClick': true
    }).addClass('fancybox');
}

/**
 * Validation for hex inputs
 *
 * @return formatted hex-value
 *
 * @access public
 * @author Daniel Quappe
 */
(function($) {
    $.fn.validHex = function() {
        return this.each(function() {
            var value = $(this).val();
            value = value.replace(/[^#a-fA-F0-9]/g, ''); // non [#a-f0-9]
            if(value.match(/#/g) && value.match(/#/g).length > 1) value = value.replace(/#/g, ''); // ##
            if(value.indexOf('#') == -1) value = '#'+value; // no #
            if(value.length > 7) value = value.substr(0,7); // too many chars
            $(this).val(value); 
        }); 
    };
})(jQuery);

/**
 * Custom fadeIn/Out Method
 * This method serve’s as a replace­ment for the built-in fadeIn() & fade­Out() meth­ods for jQuery.
 * See http://www.kevinleary.net/jquery-fadein-fadeout-problems-in-internet-explorer/
 *
 * @return void
 *
 * @access public
 * @author Daniel Quappe
 */
(function($) {
    $.fn.customFadeIn = function(speed, callback) {
        $(this).fadeIn(speed, function() {
            if(jQuery.browser.msie)
                $(this).get(0).style.removeAttribute('filter');
            if(callback != undefined)
                callback();
        });
    };
    $.fn.customFadeOut = function(speed, callback) {
        $(this).fadeOut(speed, function() {
            if(jQuery.browser.msie)
                $(this).get(0).style.removeAttribute('filter');
            if(callback != undefined)
                callback();
        });
    };
})(jQuery);


/**
 * Nice delay-function to handle keyup-events without problem
 * http://stackoverflow.com/questions/1909441/jquery-keyup-delay
 */
var delay = (function(){
  var timer = 0;
  return function(callback, ms){
    clearTimeout(timer);
    timer = setTimeout(callback, ms);
  };
})();


/** add a parameter at the end of the URL. Manage '?'/'&', but not the existing parameters.
*  does escape the value (but not the key)
*/
function addParameterToURL(_url,_key,_value){
  var param = _key+'='+escape(_value);
  var sep = '&';
  if (_url.indexOf('?') < 0) {
    sep = '?';
  } else {
    var lastChar=_url.slice(-1);
    if (lastChar == '&') sep='';
    if (lastChar == '?') sep='';
  }
  _url += sep + param;
  return _url;
}


/**
 * Ajax-Update der Vorschau
 *
 * @param string  $ajaxUrl   URL des AJAX-Request (kommt von aussen, damit die SID mitgegeben werden kann)
 * @param string  $formId    ID des Formulars, dessen Daten per AJAX uebertragen werden sollen
 * @param boolean $ajaxAbort Flag to abort pending ajax-requests
 * @return void
 *
 * @access public
 * @author Daniel Quappe
 */
var ajaxRequest = null;
function updatePreview(ajaxUrl, formId, ajaxAbort)
{
    /* Optionale Parameter vorbelegen (defaults) */
    if (arguments.length < 3) ajaxAbort = true;

    /*  Check to see if there is an AJAX request already in progress that needs to be stopped. */
    if(ajaxAbort == true && ajaxRequest != null) {
        ajaxRequest.abort();
    }

    /* Preview-Area leeren und Indicator anzeigen */
    //$('#previewPicture').empty();
    $('#updateIndicator,.updateIndicator').show();

    var forceSubmitAction = false;

    /* AJAX-Call */
    ajaxRequest = $.ajax({
        type: 'POST',
        url: ajaxUrl, 
        data: $(formId).serialize(), 
        timeout: 15000,
        success: function(data, textStatus, XMLHttpRequest)
        {
            /* Preview-Area befuellen */
            $('#previewPicture').html(data);

            /* Bindings neu initialisieren (Fancybox etc.) */
            initBindings();

            /* Bandlaengen-Callback zur Pruefung aufrufen */
            if(typeof(checkRibbonLengthOnAjaxSuccess) != 'undefined' && checkRibbonLengthOnAjaxSuccess == true && checkRibbonLength()) {
                if(typeof(forceSubmitOnAjaxSuccess) != 'undefined' && forceSubmitOnAjaxSuccess == true) {
                    forceSubmitAction = true;
                }
            }

            /* Farbkontrast-Callback zur Pruefung aufrufen */
            if(typeof(checkColorContrastOnAjaxSuccess) != 'undefined' && checkColorContrastOnAjaxSuccess == true && checkColorContrast()) {
                if(typeof(forceSubmitOnAjaxSuccess) != 'undefined' && forceSubmitOnAjaxSuccess == true) {
                    forceSubmitAction = true;
                }
            }

            /* Submit forcieren (zeitverzoegert, um die Vorschaugrafik vorher korrekt anzuzeigen) */
            if(forceSubmitAction == true) {
                setTimeout(function() {
                    $(formId).addClass('forcesubmit').submit();    
                }, 150); 
            }
            /* Andernfalls die Indicatoren ausblenden */
            else {
                $('#updateIndicator,.updateIndicator').hide();
                $('#overlayIndicator').hide();
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown)
        {
            /* Indicatoren ausblenden */
            $('#updateIndicator,.updateIndicator').hide();
            $('#overlayIndicator').hide();
        }
    })
    return false;
}
/**
 * Ajax-Update fuer unterschiedliche Inhalte
 *
 * @param string  $ajaxUrl URL des AJAX-Request (kommt von aussen, damit die SID mitgegeben werden kann)
 * @param string  $formId  ID des Formulars, dessen Daten per AJAX uebertragen werden sollen
 * @param string  $dataId  ID des DOM-Objekts, das mit den abgerufenen Daten aktualisiert werden soll
 * @param string  $indicatorId  ID eines Indikators, zur Visualisierung des Update-Vorgangs
 * @param boolean $ajaxAbort Flag to abort pending ajax-requests
 * @return void
 *
 * @access public
 * @author Daniel Quappe
 */
function updateContent(ajaxUrl, formId, dataId, indicatorId, ajaxAbort)
{
    /* Optionale Parameter vorbelegen */
    if (arguments.length < 5) ajaxAbort = true;

    /*  Check to see if there is an AJAX request already in progress that needs to be stopped. */
    if(ajaxAbort == true && ajaxRequest != null) {
        ajaxRequest.abort();
    }

    /* Indikator anzeigen, falls vorhanden */
    $(indicatorId).show();

    /* AJAX-Call */
    ajaxRequest = $.ajax({
        type: 'POST',
        url: ajaxUrl, 
        data: $(formId).serialize(),
        timeout: 15000,
        success: function(data, textStatus, XMLHttpRequest)
        {
            /* Datenbereich befuellen */
            $(dataId).html(data);
            $(dataId).show();

            /* Indikator ausblenden */
            $(indicatorId).hide();
        },
        error: function(XMLHttpRequest, textStatus, errorThrown)
        {
            /* Indikator ausblenden, falls vorhanden */
            $(indicatorId).hide();
        }
    })
}

/**
 * Custom-Confirmation per Simplemodal-Overlay
 *
 * @access public
 * @author Daniel Quappe
 */
function modalconfirm(id, message, callback) {
    $(id).modal(
    {
//      closeHTML: "<a href='#' title='Close' class='modal-close'>x</a>",
//      position: ["20%",],
//      overlayId: 'confirm-overlay',
//      containerId: 'confirm-container', 
        onShow: function (dialog) {
            var modal = this;

            $('.message', dialog.data[0]).append(message);

            // if the user clicks "yes"
            $('.yes', dialog.data[0]).click(function ()
            {
                // close the dialog
                modal.close(); // or $.modal.close();

                // call the callback
                if ($.isFunction(callback)) {
                    callback.apply();
                }
            });
        }
    });
}

/**
 * Hilfs-Methode zum Resetten der Image-Source NACH dem Submit wegen IE-Bug,
 * damit die Animation weiterlaeuft (Progressbar, Indicator-Wheel etc.)
 *
 * @access public
 * @author Daniel Quappe
 */
function fixIESubmitProgressIndicator(elementId) {
    refObject = $('#'+elementId);
    if($.browser.msie && refObject.length > 0) {
        refObject.attr('src', refObject.attr('src'));
    }
}


/**
 * Hilfs-Methode zum Vorbefuellen der Model-Fenster mit den benoetigten Werten 
 *
 * @access public
 * @author Daniel Quappe
 */
function prepareModalHint()
{
    /* Image-Source des Tape uebertragen */
    $('#tapeImg1, #tapeImg2').attr('src', $('#tapeImg').attr('src'));

    /* Overflow und Breite setzen */
    if($('#tapeImg').css('width').replace(/px/, '') > $('#meldung2Content').css('width').replace(/px/, '')) {
        $('.divTapeImg').css('width', $('#meldung2Content').css('width'));
    }
    else {
        $('.divTapeImg').css('width', $('#tapeImg').css('width'));
    }
    $('.divTapeImg').css('overflow', 'hidden');

    /* Bandlaenge und Preis uebertragen */
    $('.meldungLaenge').html( (bandlaenge/10).toString().replace(/\./, ',') );
    $('.ueberlaengePreis').html( $('#einzelpreis').html() );
}  

/**
 * Hilfs-Methode zum Berechnung der Indicator-Position und Anzeigen des Indicators 
 *
 * @access public
 * @author Daniel Quappe
 */
function showOverlayIndicator(el)
{
    offsetTop  = parseInt( $('.joodo-Post').offset().top );
    offsetLeft = parseInt( $('.joodo-Post').offset().left );

    $('#overlayIndicator')
        .css('height', el.innerHeight() + 'px').css('width', el.innerWidth() + 'px')
        .css('left', (el.offset().left - offsetLeft) + 'px').css('top',  (el.offset().top - offsetTop) + 'px')
    ;
    $('#overlayIndicator img')
        .css('margin-left', ($('#overlayIndicator').outerWidth()/2 - 8) + 'px')
        .css('margin-top', ($('#overlayIndicator').outerHeight()/2 - 8) + 'px')
    ;
    $('#overlayIndicator').show();
}


/**
 * Javascript-Kontroll-Logik fuer die Textzeilen (wird aber auch noch per POST geprueft)
 *
 * @access public
 * @author Daniel Quappe
 */
var checkInputFlag = true;
var checkTextinputMessage = 'Please enter content at least in one row.';
function checkTextinput(el, popup)
{
    if(typeof(popup) == 'undefined') popup = true;

    if(checkInputFlag == true)
    {
        // Define content
        var _Content1; ($('#'+el+'0Beschriftung') != null) && (_Content1 = $('#'+el+'0Beschriftung').val());
        var _Content2; ($('#'+el+'1Beschriftung') != null) && (_Content2 = $('#'+el+'1Beschriftung').val());
        var _Content3; ($('#'+el+'2Beschriftung') != null) && (_Content3 = $('#'+el+'2Beschriftung').val());
        var _Content4; ($('#'+el+'3Beschriftung') != null) && (_Content4 = $('#'+el+'3Beschriftung').val());
    
        if (!_Content1 && !_Content2 && !_Content3 && !_Content4) {
            markInput(el);
            if(popup == true) {
                alert(checkTextinputMessage);
            }
            return false;
        }
    }
    unmarkInput(el);
    return true;
} 

/**
 * Javascript-Kontroll-Logik zur Suche nach Textzeilen mit fehlendem Text
 *
 * @access public
 * @author Daniel Quappe
 */
function hasEmptyTextRows(el)
{
    var foundEmptyTextRow = false;
    var rowCounter = 0;

    for (var i = 0; i <= 3; i++)
    {
        if($('#'+el+i+'Beschriftung').length > 0) {
            rowCounter++;
            if($('#'+el+i+'Beschriftung').val() == '') {
                foundEmptyTextRow = true;
            }
        }
    } 

    if(rowCounter > 1 && foundEmptyTextRow == true) {
        return true;
    } else {
        return false;
    }
} 

/**
 * Markierungs-Klassen hinzufuegen
 *
 * @access public
 * @author Daniel Quappe
 */
function markInput(el)
{
    /* Markierung u. Fokusierung der ersten Beschriftungsreihe (die gibt es immer) */
    if($('#'+el+'0Beschriftung') != null) {
        $('#'+el+'0Beschriftung').addClass('markedtextinput');
        $('#'+el+'0Beschriftung').focus();
    }

    /* Evtl. vorhandene Geschwister-Elemente finden und ebenfalls markieren */
    ($('#'+el+'1Beschriftung') != null) && $('#'+el+'1Beschriftung').addClass('markedtextinput');
    ($('#'+el+'2Beschriftung') != null) && $('#'+el+'2Beschriftung').addClass('markedtextinput');
    ($('#'+el+'3Beschriftung') != null) && $('#'+el+'3Beschriftung').addClass('markedtextinput');

    //$('input[type="text"]').addClass("markedtextinput");
}

/**
 * Markierungs-Klassen entfernen
 *
 * @access public
 * @author Daniel Quappe
 */
function unmarkInput(el)
{
    ($('#'+el+'0Beschriftung') != null) && $('#'+el+'0Beschriftung').removeClass('markedtextinput');
    ($('#'+el+'1Beschriftung') != null) && $('#'+el+'1Beschriftung').removeClass('markedtextinput');
    ($('#'+el+'2Beschriftung') != null) && $('#'+el+'2Beschriftung').removeClass('markedtextinput');
    ($('#'+el+'3Beschriftung') != null) && $('#'+el+'3Beschriftung').removeClass('markedtextinput');
}

