var CustVox = new Object; // as name space CustVox.Feedback
CustVox.Feedback = new Object;

/*==============================
*** CSS Browser Selector 3.5 ***
==============================*/
CustVox.css=function(u) {
 var ua = u.toLowerCase(),
 is=function(t){
  return ua.indexOf(t)>-1;
 },
 g='gecko',
 w='webkit',
 s='safari',
 o='opera',
 h=document.documentElement,
 b=[(!(/opera|webtv/i.test(ua))&&/msie\s(\d)/.test(ua))?
   ('ie ie'+RegExp.$1):is('firefox/2')?
   g+' ff2':is('firefox/3.5')?
   g+' ff3 ff3_5':is('firefox/3')?
   g+' ff3':is('gecko/')?g:is('opera')?
   o+(/version\/(\d+)/.test(ua)?
   ' '+o+RegExp.$1:(/opera(\s|\/)(\d+)/.test(ua)?
   ' '+o+RegExp.$2:'')):is('konqueror')?
   'konqueror':is('chrome')?
   w+' chrome':is('iron')?
   w+' iron':is('applewebkit/')?
   w+' '+s+(/version\/(\d+)/.test(ua)?
   ' '+s+RegExp.$1:''):is('mozilla/')?
   g:'',is('j2me')?'mobile':is('iphone')?
   'iphone':is('ipod')?
   'ipod':is('mac')?
   'mac':is('darwin')?
   'mac':is('webtv')?
   'webtv':is('win')?
   'win':is('freebsd')?
   'freebsd':(is('x11')||is('linux'))?
   'linux':'','js'];
 c = b.join(' ');
 h.className += ''+c;return c;
};
CustVox.css(navigator.userAgent);

/**
* Popup menu init
*/
CustVox._feedback_init=function(params) {
  var hideDelay = 500;
  var hideDelayTimer = null;
  var time = 150;

  var beingShown = false;
  var shown = false;

  var popup = $('div.Custvox > div.Wrap');
  var trigger = $(params.feedbackId); 

  popup.css({'display': 'none'});
  trigger.click(function() {return false});

  var overFunc = function() {
      var position = trigger.offset();      
      popup.css('top', position.top);
      popup.css('left', position.left + trigger.outerWidth());

      if (hideDelayTimer) clearTimeout(hideDelayTimer);
      if (beingShown || shown) {
        // don't trigger the animation again
        return false;
      } else {
        // show popup
        beingShown = true;
        popup.show(time, function() {
            beingShown = false;
            shown = true;
        });
      }
      return false;
  }

  var outFunc = function() {
      if (hideDelayTimer) clearTimeout(hideDelayTimer);
      hideDelayTimer = setTimeout(function() {
      hideDelayTimer = null;
      popup.hide(time, function() {
         shown = false;
      });
      }, hideDelay);
      return false;
  }

  trigger.mouseover(overFunc);
  trigger.mouseout(outFunc);
  popup.mouseover(overFunc);
  popup.mouseout(outFunc);
};

/*====================================
* Dialog window for CustVox feedback *
*===================================*/
CustVox.Dialog = function(params) {
    if ( params == undefined ) params = {};
    this.id = params.id||'customDialog';
    this.classes = params.classes||'';
    this.width = params.width||400;
    this.closeButton = params.closeButton||false;
    this.clearOnClose = params.clearOnClose||false; // clear content after close dialog
    this.createDOM();
};
/**
 * Create dialog window in DOM
 */
CustVox.Dialog.prototype.createDOM=function() {
    var dom = ''
    + '<div class="Custvox">\n'
    + '<div class="' + this.classes + '" id="' + this.id + '">\n'
    + (( this.closeButton ) ? ' <div class="CloseButton" title="Close"></div>\n' : '')
    + '<div class="DialogContent"></div>'
    + '</div>\n'
    + '</div>\n';
    $('body').append($(dom));

    var self = this;
    if ( this.closeButton ) {
        $(this.getJqId() + " div.CloseButton").click(function() {
            if ( self.clearOnClose ) {
                self.setContent("");
            }
            self.hide();
        });
    }
};
/**
 * Put any HTML content to inline dialog window
 */
CustVox.Dialog.prototype.setContent=function(html) {
    $(this.getJqId() + " div.DialogContent").html(html);
};
/**
 * Show window dialog
 */
CustVox.Dialog.prototype.show=function() {
    var dlgTop = ($(window).height() - $(this.getJqId()).height()) / 2 + $(window).scrollTop() + "px";
    var dlgLeft = ($(window).width() - $(this.getJqId()).width()) / 2 + $(window).scrollLeft() + "px";
    $(this.getJqId()).css({top: dlgTop, left: dlgLeft});
    $(this.getJqId()).fadeIn(0);
};
/**
 * Hide window dialog
 */
CustVox.Dialog.prototype.hide=function() {
    $(this.getJqId()).fadeOut(200);
};
/**
 * Just get jQuery id of dialog window
 */
CustVox.Dialog.prototype.getJqId=function() {
    return '#' + this.id;
};


/**
 * Call foreign web site from hide iframe object
 */
CustVox.runInIframe = function(url) {
    //window.alert("URL: " + url);
    $("#_foreign_call_iframe").remove();
    $("<iframe/>")
    .attr("src", url)
    .attr("id", "_foreign_call_iframe")
    .attr("width", 0)
    .attr("height", 0)
    .css("position", "absolute")
    .css("top", "-9999px")
    .css("left", "-9999px")
    .appendTo($('body'));
};

/*==================
*** jQuery Growl ***
==================*/
CustVox.Notify = {
 animationDuration: 200,
 displayFor: 2000,
 show: function(text) {
  if($('#Notify').length == 0)
   $('body').append('<div id="Notify"></div>');
   $('#Notify').css({
    'left': ($(window).width() - $('#Notify').width()) / 2 + $(window).scrollLeft() + "px",
    'top': ($(window).height() - $('#Notify').height()) / 2 + $(window).scrollTop() + "px"
   });

  var notification = $("<div>", {
   "class": "Notification",
    "text": text,
   "click": function(){CustVox.Notify.hide(notification);}
  }).appendTo($('#Notify'));

  setTimeout(function(){CustVox.Notify.hide(notification);}, this.displayFor);
 },
 hide: function(notification){
  notification.fadeOut(this.animationDuration, function(){$(this).parent().remove();});
 }
}


/*===========================
*** Feedback for Cablecom ***
===========================*/
CustVox.Feedback.init = function(p) {
  // main init function, calls from <script> in head of main page

  $(document).ready(function(){

     var jQId = p.feedbackId || "div.CustVox div.Feedback";
     var assetsPath = p.assetsPath || '/';
     var $feedback = $(jQId);

     // define page language
     var lang = $feedback.attr('lang')||'de';
     lang = {de: 'de', en: 'en', it: 'it', fr: 'fr'}[lang]||'de';

     // set common feedback params like menu placement and user language
     var params = {
         lang: lang,
         'drop-down': p.placement||'top',
         feedbackId: jQId
     };

     var desiredChannel = {
         en: 'Desired channel',
         de: 'Gewünschten Kanal',
         it: 'Tipo di canale',
         fr: 'Canal désiré'
     }[lang];

    // define popup content

     var content = ''
        + '<div class="Custvox">'
        + ' <div class="Wrap">'
        + '  <div class="Feedback Clearfix">'
        + '   <a class="Channel Phone" href="#"><img alt="" class="Icons Phone" src="%PATH%assets/none.gif" /><br />Phone</a>'
        + '   <a class="Channel Web" href="#"><img alt="" class="Icons Web" src="%PATH%assets/none.gif" /><br />Web</a>'
        + '   <a class="Channel Sms" href="#"><img alt="" class="Icons Sms" src="%PATH%assets/none.gif" /><br />Sms</a>'
        + '  </div>'
        + '</div>';
     content = content.replace(/\%PATH\%/g, assetsPath);
     $('body').append(content);
     $feedback.show();

     // CFM domain
     var cfmURL = p.cfmURL;

     // content of enter phone|sms number dialog
     var enterPhoneNumber = ''
        + '  <div class="Header">We do not have your SMS number</div>'
        + '  <form onsubmit="return false">'
        + '   <div class="Main_Block">'
        + '    <div class="Title">Please, enter your SMS number:</div>'
        + '    <input class="Phone" type="text" />'
        + '   </div>'
        + '   <div class="Buttons_Block Clearfix">'
        + '   <div class="Example">Example: +41 79 1234567</div>'
        + '    <div class="Submit"><input class="Submit" type="submit" value="Call me now" /></div>'
        + '   </div>'
        + '  </form>';


     // SMS dialog
     var smsDialog = new CustVox.Dialog({id: 'dlgSMS', classes: 'Phone', closeButton: true});
     smsDialog.setContent($(enterPhoneNumber));
     var smsTitle = {
         en: 'We do not have your SMS number',
         de: 'We do not have your SMS number',
         it: 'Purtroppo non abbiamo il vostro numero di SMS',
         fr: 'We do not have your SMS number'
     }[lang];
     $(smsDialog.getJqId() + " div.Header").text(smsTitle);
     var smsText = {
         en: 'Please, enter your SMS number:',
         de: 'Please, enter your SMS number:',
         it: 'Per favore, inserite il vostro numero di SMS:',
         fr: 'Please, enter your SMS number:'
     }[lang];
     $(smsDialog.getJqId() + " div.Title").text(smsText);
     var smsButton = {
         en: 'Send now',
         de: 'Send now',
         it: 'Send now',
         fr: 'Send now'
     }[lang];
     $(smsDialog.getJqId() + " div.Buttons_Block input.Submit").val(smsButton);
     $(smsDialog.getJqId() + " form").submit(function() {
         var number = $(smsDialog.getJqId() + " input.Phone").val();
         // TODO validation of number

         if ( number ) {
             var growlSms = {
                 en: 'Thank you! We will contact you by SMS now',
                 de: 'Vielen Dank! Wir werden Sie per SMS jetzt an',
                 it: 'Grazie! Ci metteremo in contatto via SMS ora',
                 fr: 'Merci! Nous prendrons contact avec vous par SMS maintenant'
             }[lang];
             smsDialog.hide();
             CustVox.Notify.show(growlSms);
             CustVox.runInIframe(cfmURL
                 + "/web/startSurvey?job=" + p.jobID + "&channel=sms&number=" + number + "&lang=" + lang
             );
         }
         return false;
     });

     $('div.Custvox a.Sms').click(function() {
      phoneDialog.hide();
      webDialog.hide();
      smsDialog.show();
      return false;
     });

     // Phone dialog
     var phoneDialog = new CustVox.Dialog({id: 'dlgPhone', classes: 'Phone', closeButton: true});
     phoneDialog.setContent($(enterPhoneNumber));
     var phoneTitle = {
         en: 'We do not have your phone number',
         de: 'Wir haben nicht Ihre Telefonnummer',
         it: 'Non abbiamo il numero di telefono',
         fr: 'Nous n\'avons pas votre numéro de téléphone'
     }[lang];
     $(phoneDialog.getJqId() + " div.Header").text(phoneTitle);
     var phoneText = {
         en: 'Please, enter your phone number:',
         de: 'Bitte geben Sie Ihre Telefonnummer ein:',
         it: 'Per favore, inserisci il tuo numero di telefono:',
         fr: 'S\'il vous plaît, entrez votre numéro de téléphone:'
     }[lang];
     $(phoneDialog.getJqId() + " div.Title").text(phoneText);
     var phoneButton = {
         en: 'Call me now',
         de: 'Call me now',
         it: 'Call me now',
         fr: 'Call me now'
     }[lang];
     $(phoneDialog.getJqId() + " div.Buttons_Block input.Submit").val(phoneButton);
     $(phoneDialog.getJqId() + " form").submit(function() {
         var number = $(phoneDialog.getJqId() + " input.Phone").val();
         // TODO validation of number

         if ( number ) {
             var growlPhone = {
                 en: 'Thank you! We will call you now',
                 de: 'Vielen Dank! Wir werden Sie jetzt anrufen',
                 it: 'Grazie! Vi invito adesso',
                 fr: 'Merci! Nous vous appelons maintenant'
             }[lang];
             phoneDialog.hide();
             CustVox.Notify.show(growlPhone);
             CustVox.runInIframe(cfmURL
                 + "/web/startSurvey?job=" + p.jobID + "&channel=phone&number=" + number + "&lang=" + lang
             );
         }
     });

     $('div.Custvox a.Phone').click(function() {
      smsDialog.hide();
      webDialog.hide();
      phoneDialog.show();
      return false;
     });

     // WEB dialog
     var webDialog = new CustVox.Dialog({
         id: 'dlgWebFeedback',
         classes: 'Window',
         closeButton: true,
         clearOnClose: true
     });

     $('div.Custvox a.Web').click(function() {
      smsDialog.hide();
      phoneDialog.hide();
      var $content = $('<div></div>');
      var $header = $('<div class="Header">CustVox - Customer Feedback Manager</div>');
      var $webIframe = $('<iframe border="0" frameborder="0" marginheight="0" marginwidth="0"></iframe>')
        .attr('scrolling', "no")
        .attr('height', "310")
        .attr('width', "640")
        .attr('src', cfmURL + "/web/custvox/survey.jsp?jobid=" + p.jobID + "&lang=" + lang);
      $content.append($header).append($webIframe);
      webDialog.setContent($content.html());
      webDialog.show();
      return false;
     });

     // now we are ready init of feedback
     CustVox._feedback_init(params);

  });
}
