var DEBUG = false;
//$.log( 'LIFEHELP::debug start at:' + new Date().toLocaleString() );
//$.log( 'LIFEHELP::jquery initialisation start!' );

//var url = 'http://'+location.host+'/livehelp.php';
var url = './livehelp.php';

var state = 0;
var oldState = 0;
var vorName = '';
var nachName = '';
var teleFon = '';
$(document).ready(
  function()
  {
    $('#support_failure').ajaxForm({
      success: function(data) {
          //$.log( 'LIFEHELP::ajaxForm support_failure!' );
          window.self.close();
      }
    });
    $('#support_success').ajaxForm({
        success: function(data) {
            //$.log( 'LIFEHELP::ajaxForm support_success!' );
            window.self.close();
        }
    });
    $('body').append('<div id="windowModal">'+
                     '<div id="windowModalTop">'+
                     '<div id="windowModalTopContent">Soforthilfe</div>'+
                     '<img src="window_demo/images/window_close.jpg" alt="" id="windowModalClose" />'+
                     '</div>'+
                     '<div id="windowModalBottom"><div id="windowModalBottomContent">&nbsp;</div></div>'+
                     '<div id="windowModalContent">&nbsp;</div>'+
                     '</div>');
    $('#windowModalClose').bind(
      'click',
      windowModalClose
    );
    $('#windowModalMin').bind(
      'click',
      function()
      {
        //$.log( 'LIFEHELP::windowModal minimized!' );
        $('#windowModalContent').SlideToggleUp(300);
        $('#windowModalBottom, #windowModalBottomContent').animate({height: 10}, 300);
        $('#windowModal').animate({height:40},300).get(0).isMinimized = true;
        $(this).hide();
        $('#windowModalResize').hide();
        $('#windowModalMax').show();
      }
    );
    $('#windowModalMax').bind(
      'click',
      function()
      {
        //$.log( 'LIFEHELP::windowModal maximized!' );
        var windowModal = $.iUtil.getSize(document.getElementById('windowModalContent'));
        $('#windowModalContent').SlideToggleUp(300);
        $('#windowModalBottom, #windowModalBottomContent').animate({height: windowModal.hb + 13}, 300);
        $('#windowModal').animate({height:windowModal.hb+43}, 300).get(0).isMinimized = false;
        $(this).hide();
        $('#windowModalMin, #windowModalResize').show();
      }
    );
    $('#windowModal').Resizable(
      {
        minWidth: 325,
        minHeight: 348,
        maxWidth: 700,
        maxHeight: 400,
        dragHandle: '#windowModalTop',
        handlers: {
          se: '#windowModalResize'
        },
        onResize : function(size, position) {
          //$.log( 'LIFEHELP::windowModal resize!' );
          $('#windowModalBottom, #windowModalBottomContent').css('height', size.height-33 + 'px');
          var windowModalContentEl = $('#windowModalContent').css('width', size.width - 25 + 'px');
          if (!document.getElementById('windowModal').isMinimized) {
            windowModalContentEl.css('height', size.height - 48 + 'px');
          }
        }
      }
    );
    windowModalUpdate();
    appendWindowModalOpen();
  }
);
function appendWindowModalOpen() {
  //$.log( 'LIFEHELP::windowModal append OnClick!' );
  $('#windowModalOpen').unbind('click');
  $('#windowModalOpen').bind(
    'click',
    function() {
      url = this.href;
      //$.log( 'LIFEHELP::windowModal found url:'+url );
      var checkURL = url.toLowerCase();
      if( /\.(xhtml|php|html)$/.test(checkURL) ) {
          if($('#windowModal').css('display') == 'none') {
              //$.log( 'LIFEHELP::windowModal initialized!' );
              try { $(this).TransferTo({
                  to:'windowModal',
                  className:'transferer2',
                  duration: 400,
                  complete: function(){
                      //$.log( 'LIFEHELP::windowModal show!' );
                      windowModalUpdate(true);
                      $('#windowModal').show();
                  }
              }); } catch(e) {
                  windowModalUpdate(true);
                  $('#windowModal').show();
              };
          } //else $.log( 'LIFEHELP::windowModal allways initialized!' );
      } //else $.log( 'LIFEHELP::windowModal url dropped!' );
      this.blur();
      return false;
    }
  );
}
function initAjaxForm() {
    if (state == 1 || state == 4 || state == 5) {
        //$.log( 'LIFEHELP::ajaxForm initialized!' );
        $('#livehelp').ajaxForm({
            target: '#windowModalContent',
            beforeSubmit:  function(formData){
                var valid = true;
                for (var i=0; i < formData.length; i++) {
                    if (formData[i].name == 'vorname') {
                        //$.log( 'LIFEHELP::ajaxForm validate vorname' );
                        if (!checkName(formData[i].value)) {
                            valid = false;
                            $('input[@name=vorname]').addClass('inputTextBlueError');
                        }
                        else $('input[@name=vorname]').removeClass('inputTextBlueError');
                    }
                    else if (formData[i].name == 'nachname') {
                        //$.log( 'LIFEHELP::ajaxForm validate nachname' );
                        if (!checkName(formData[i].value)) {
                            valid = false;
                            $('input[@name=nachname]').addClass('inputTextBlueError');
                        }
                        else $('input[@name=nachname]').removeClass('inputTextBlueError');
                    }
                    else if (formData[i].name == 'telefon') {
                        //$.log( 'LIFEHELP::ajaxForm validate telefon' );
                        if (!checkPhoneNumber(formData[i].value)) {
                            valid = false;
                            $('input[@name=telefon]').addClass('inputTextBlueError');
                        }
                        else $('input[@name=telefon]').removeClass('inputTextBlueError');
                    }
                    //else $.log( 'LIFEHELP::ajaxForm validate skip:'+formData[i].name );
                }
                //$.log( 'LIFEHELP::ajaxForm validation:'+valid );
                return valid;
            },
            success: function(data) {
                //$.log( 'LIFEHELP::ajaxForm success!' );
                checkState();
                if (oldState == 4) {
                    windowModalClose();
                    oldState = state;
                    state = 0;
                    //$.log( 'LIFEHELP::windowModal state:'+state );
                } else {
                    //$.log( 'LIFEHELP::ajaxForm content reload!' );
                    windowModalUpdate();
                }
                return true;
            }
        });
        //$.log( 'LIFEHELP::windowModal restore fields!' );
        $('input[@name=vorname]').val(vorName);
        $('input[@name=nachname]').val(nachName);
        $('input[@name=telefon]').val(teleFon);
    }
    return true;
}
function initAjaxSlider() {
    if (state == 4) {
        //$.log( 'LIFEHELP::ajaxForm slider initialized!' );
        $('.slider').Slider(
          {
            accept : '.indicator',
            fractions: 5,
            opacity: 0.8,
            values: [[70,70]],
            onSlide : function(cordx)
                {
                  document.getElementById('rating').value = Math.round((5/100)*cordx)+1;
                }
          }
        );
    }
    return true;
}
function windowModalUpdate(force) {
    //$.log( 'LIFEHELP::windowModal state:'+state );
    //$.log( 'LIFEHELP::windowModal update force:'+force );
    if ((force == true || state == 0 || state == 2 || state == 3) && /\.(xhtml|php|html)$/.test(url) ) {
        num = Math.random();
        var sep = '?';
        if( /\?/.test(url) ) sep = '&';
        //$.log( 'LIFEHELP::ajaxForm catch:'+url );
        //$('#windowModalContent').load(url+sep+num);
        $.ajax({
            type: "GET",
            url: url+sep+jsSessionNAME+'='+jsSessionID+'&'+num,
            dataType: "html",
            //ifModified: true,
            success: function(html){
                //$.log( 'LIFEHELP::ajaxForm success!' );
                $("#windowModalContent").html(html);
                //$.log( 'LIFEHELP::ajaxForm content reload!' );
                checkState();
                initAjaxForm();
                initAjaxSlider();
                if($('#windowModal').css('display') == 'none' && oldState != state && (state == 2 || state == 3 || state == 4)) {
                    //$.log( 'LIFEHELP::windowModal initialized by state:'+state );
                    try { $('#windowModalOpen').TransferTo({
                        to:'windowModal',
                        className:'transferer2',
                        duration: 400,
                        complete: function(){
                            //$.log( 'LIFEHELP::windowModal show!' );
                            $('#windowModal').show();
                        }
                    }); } catch(e) {
                      $('#windowModal').show();
                    }
                } //else $.log( 'LIFEHELP::windowModal allways initialized by state:'+state );
            }
        });
        setTimeout('windowModalUpdate()', 2000);
    } //else $.log( 'LIFEHELP::windowModal update skiped!' );
}
function checkState() {
    var newstate = parseInt($("#state").text());
    if (newstate >= 1) {
        oldState = state;
        state = newstate;
        //$.log( 'LIFEHELP::windowModal state:'+state );
        return true;
    } else {
        alert('Status Fehler!');
        //$.log( 'LIFEHELP::windowModal state error!' );
        windowModalClose();
        oldState = state;
        state = 0;
        //$.log( 'LIFEHELP::windowModal state:'+state );
        return false;
    }
}
function windowModalClose() {
    //$.log( 'LIFEHELP::windowModal backup fields!' );
    vorName = $('input[@name=vorname]').fieldValue();
    nachName = $('input[@name=nachname]').fieldValue();
    teleFon = $('input[@name=telefon]').fieldValue();
    //$.log( 'LIFEHELP::windowModal close!' );
    $('#windowModal').TransferTo(
        {
            to:'windowModalOpen',
            className:'transferer2',
            duration: 400
        }
    ).hide();
}
function checkName(name) {
    var pattern = /^[a-zA-ZäüöÄÜÖß\s]{3,}$/i;
    if (!pattern.test(name) || trim(name) == 0) return false;
    else return true;
}
function checkPhoneNumber(phone) {
    var patternInt = /^[0-9]{3,}$/i;
    var patternFull = /^[+]?[\-\(\)0-9\s]{5,}$/i;
    if ((!patternInt.test(phone) && !patternFull.test(phone))  || trim(phone) == 0) return false;
    else return true;
}
function trim(s) {
	while (s.substring(0,1) == ' ') {
		s = s.substring(1,s.length);
	}
	while (s.substring(s.length-1,s.length) == ' ') {
		s = s.substring(0,s.length-1);
	}
	return s;
}
//$.log( 'LIFEHELP::jquery initialization ready!' );