// customer.js

// copyright  bpm consult ag, CH-Birsfelden
// contact    webdev@bpm.ch
// license    restricted

function bpminit(El){

  if (!Ext.isObject(El)) return;

  // accordion menu
  beeline.web.initAccordionGroup(El,'.groupContent');
  beeline.web.initAccordionNavigation(El,'.nav');

  // change skin
  beeline.web.initSkinChange(El);

  // add reflection to images
  beeline.web.addReflection(El);

  // close or open boxes
  beeline.web.animateBox(El,'.box');

  // nummeric input fields
  beeline.web.initNumericInputs(El,'input.int');

  // show advanced search after ajaxload
  var AdvancedSearch = El.select('.headerSearchAdvanced').item(0);
  if (Ext.isObject(AdvancedSearch)) {
    AdvancedSearch.fadeIn();
    AdvancedSearch.select('.closeSearch').each(function(CloseSearch){
      CloseSearch.on('click', function(){
        AdvancedSearch.hide();
      });
    });
  }

  // show advanced search if already exist
  var ExpandSearch = El.select('.headerSearchExpand').item(0);
  if (Ext.isObject(ExpandSearch)) {
    ExpandSearch.on('click', function(){
      var AdvancedSearch = El.select('.headerSearchAdvanced').item(0);
      if (Ext.isObject(AdvancedSearch)) {
        AdvancedSearch.fadeIn();
      }
    });
  }

   // detail: create window
  function createWindow(EventObj, content, src){
    EventObj.stopEvent();
    var Overlay = Ext.select('.overlay', true).item(0);
    if (Ext.isObject(Overlay)) {
      var OverlayContent = Overlay.select('.overlayContent').item(0);
      var id = Ext.id(OverlayContent);
      OverlayContent.dom.innerHTML = '';
      beeline.web.loadsrc(content, id, src);
      new beeline.web.alert({
        title: Overlay.select('.overlayTitle').item(0).dom.innerHTML,
        content: '<div class="ajaxContent">' + OverlayContent.dom.innerHTML + '</div><p class="alertboxButton"><span class="button"><input class="alertboxClose" type="reset" name="close" value="OK"/></span></p>'
      });
    }
    return false;
  }

// detail: show picture in window
  El.select('.showPicture').each(function(ShowPicture){
    var src = ShowPicture.dom.href;
    ShowPicture.on('click', function(EventObj){
      return createWindow(EventObj, 'img', src);
    });
  });

  // detail: show widget in window
  El.select('.showWidget').each(function(ShowWidget){
    var src = ShowWidget.dom.href;
    ShowWidget.on('click', function(EventObj){
    return createWindow(EventObj,'iframe',src);
    });
  });

  // detail: expand info box
  El.select('.detailInfoBoxExpand').each(function(El){
    var ExpandButton = El.first();
    var ExpandElements = El.parent().select('.detailInfoBoxMore');
    ExpandButton.on('click', function(){
      ExpandButton.hide();
      ExpandElements.show();
    });
  });

  // close or open main slider
  El.select('.mainSlider').each(function(Slider){
    Slider.first('span').on('click', function(event, target){
      El = Ext.get(target);
      if (El.hasClass('boxClose')) {
        El.parent().next().slideOut('t', { useDisplay: true });
        El.removeClass('boxClose');
        El.addClass('boxOpen');
      }
      else {
        El.parent().next().slideIn();
        El.removeClass('boxOpen');
        El.addClass('boxClose');
      }
    });
  });

  // show alert message
  var AlertMsg = Ext.get('alert');
  if ((Ext.isObject(AlertMsg))&&(AlertMsg.dom.innerHTML.replace(/^\s+|\s+$/g, '') != '')) {
    new beeline.web.alert({
      content: AlertMsg.dom.innerHTML + '<p class="alertboxButton"><span class="button"><input class="alertboxClose" type="reset" name="close" value="OK"/></span></p>',
      shadeBg: false
    });
    AlertMsg.dom.innerHTML = '';
  }

  // basket: add free text item
  var AddForm = El.select('.addForm').item(0);
  if (Ext.isObject(AddForm)) {
    var ShowAddForm = El.select('.showAddForm').item(0); 
    if (!Ext.isObject(ShowAddForm)) return; 
    ShowAddForm.on('click', function(){
      AddForm.slideIn();
      ShowAddForm.setStyle('visibility', 'hidden');
    });
    var HideAddForm = El.select('.hideAddForm').item(0);
    if (!Ext.isObject(HideAddForm)) return;
    HideAddForm.on('click', function(){
      AddForm.slideOut('t', { useDisplay: true });
      ShowAddForm.setStyle('visibility', 'visible');
    });
  }

  // quick tool tips
  El.select('.quicktip').each(function(e){
    beeline.web.createToolTip(e, 'quicktip', e.getAttribute('alt'), e.getAttribute('title'), new Array(10, -20));
  });

  // set focus
  if (El.select('.focus').item(0)) {
    var lastFocusElement = Ext.select('.focus').getCount() - 1;
    Ext.select('.focus').item(lastFocusElement).focus();
  }

  // result: add news alert
  El.select('.newsalertItem').each(function(Add){
    Add.on('click', function(event, target){
      Ext.get(target).parent('.newsalert').first('.newsalertAdd').show();
    });
  });

  // approval plan: overlay secure question (delete plan)
  El.select('.secure').each(function(e){
    e.on('click', function(event, target){
      event.stopEvent();
      var href = Ext.get(target).parent().getAttribute('href');
      var content = Ext.get('secure').dom.innerHTML.replace(/#/g, href);
      new beeline.web.alert({
        content: content,
        shadeBg: false
      });
    });
    e.on('keypress', function(event, target){
      event.stopEvent();
      var href = Ext.get(target).parent().getAttribute('href');
      var content = Ext.get('secure').dom.innerHTML.replace(/#/g, href);
      new beeline.web.alert({
        content: content,
        shadeBg: false
      });
    });
  });

  // approval plan: close or open slider
  El.select('.approvalCaptionShowhide').each(function(Button){
    Button.on('click', function(event, target){
      El = Ext.get(target);
      if (El.hasClass('boxClose')) {
        El.parent().next().slideOut('t', { useDisplay: true });
        El.removeClass('boxClose');
        El.addClass('boxOpen');
      }
      else {
        El.parent().next().slideIn();
        El.removeClass('boxOpen');
        El.addClass('boxClose');
      }
    });
  });

  // limit textarea to 450 chars
  El.select('.max450').each(function(Textarea){
    var limitNum = 449;
    Textarea.on('keypress', function(k, t){
      var key = k.getKey();
      if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13) || (key == 27) || (key == 116)) {
        return;
      }
      if (Ext.get(t).dom.value.length > limitNum) {
        k.stopEvent();
      }
      else {
        Ext.get(t).next('input.counter').dom.value = limitNum - Ext.get(t).dom.value.length;
      }
    });
  });

  // show flash movie
  El.select('.flashMovie').each(function(e){
    var flashdir = '/csp/shop/bpmweb/css/default/flash/';
    var flashfile = e.first('.flashLink').dom.innerHTML;
    if (flashfile.search(/\//) == -1) flashfile = flashdir + flashfile;
    var playervars = {
      video: flashfile,
      preview: e.first('img').getAttribute('src'),
      autoscale: 'false',
      videowidth: 400,
      videoheight: 182
    };
    var params = {
      scale: 'noscale',
      allowfullscreen: 'true',
      salign: 'tl',
      base: '.'
    };
    var attributes = {
      align: 'left'
    };
    swfobject.embedSWF(flashdir + 'flvplayer.swf', 'flash', '400', '232', '9.0.28', flashdir + 'expressInstall.swf', playervars, params, attributes);
  });

  // facebook integration: like it
  El.select('.detailLike').each(function(Like){
    var child = '<iframe src="http://www.facebook.com/widgets/like.php?href=' + document.URL + '" scrolling="no" frameborder="0"></iframe>';
    Ext.DomHelper.append(Like, child);
  });
  
  // checkout2: invoice address private company switch
var InvoicePrivate = El.select('.invoicePrivate').item(0);
var InvoiceCompany = El.select('.invoiceCompany').item(0);
  if (Ext.isObject(InvoicePrivate)) {
    function setPrivate(){
      InvoicePrivate.addClass('active');
      InvoiceCompany.removeClass('active');
      Ext.get('Addition2').dom.value = '';
      Ext.select('.private').each(function(e){
        e.setStyle('display', 'inline-block');
        if (e.parent().is('td')) 
          e.parent().setStyle('paddingTop', '10px');
      });
      Ext.select('.company').each(function(e){
        e.setStyle('display', 'none');
        if (e.parent().is('td')) 
          e.parent().setStyle('paddingTop', '0');
      });
    }
    function setCompany(){
      InvoiceCompany.addClass('active');
      InvoicePrivate.removeClass('active');
      if (Ext.get('Addition2').getValue() == '') {
        Ext.get('Addition2').dom.value = ' ';
      }
      Ext.select('.company').each(function(e){
        e.setStyle('display', 'inline-block');
        if (e.parent().is('td')) 
          e.parent().setStyle('paddingTop', '10px');
      });
      Ext.select('.private').each(function(e){
        e.setStyle('display', 'none');
        if (e.parent().is('td')) 
          e.parent().setStyle('paddingTop', '0');
      });
    }
    if (Ext.get('Addition2').getValue() == '') {
      setPrivate();
    }
    else {
      setCompany();
      if (Ext.get('Addition2').getValue() == ' ') {
        Ext.get('Addition2').on('focus', function(){
          Ext.get('Addition2').dom.value = ''
        });
      }
    }
    InvoiceCompany.on('click', setCompany);
    InvoicePrivate.on('click', setPrivate);
  }
  
  // checkout2: delivery address private company switch
  var DeliveryPrivate = El.select('.deliveryPrivate').item(0);
  var DeliveryCompany = El.select('.deliveryCompany').item(0);
  if (Ext.isObject(DeliveryPrivate)) {
    function setPrivate2(){
      DeliveryPrivate.addClass('active');
      DeliveryCompany.removeClass('active');
      Ext.get('Addition2-2').dom.value = '';
      Ext.select('.private2').each(function(e){
        e.setStyle('display', 'inline-block');
        if (e.parent().is('td')) 
          e.parent().setStyle('paddingTop', '10px');
      });
      Ext.select('.company2').each(function(e){
        e.setStyle('display', 'none');
        if (e.parent().is('td')) 
          e.parent().setStyle('paddingTop', '0');
      });
    }
    function setCompany2(){
      DeliveryCompany.addClass('active');
      DeliveryPrivate.removeClass('active');
      if (Ext.get('Addition2-2').getValue() == '') {
        Ext.get('Addition2-2').dom.value = ' ';
      }
      Ext.select('.company2').each(function(e){
        e.setStyle('display', 'inline-block');
        if (e.parent().is('td')) 
          e.parent().setStyle('paddingTop', '10px');
      });
      Ext.select('.private2').each(function(e){
        e.setStyle('display', 'none');
        if (e.parent().is('td')) 
          e.parent().setStyle('paddingTop', '0');
      });
    }
    if (Ext.get('Addition2-2').getValue() == '') {
      setPrivate2();
    }
    else {
      setCompany2();
      if (Ext.get('Addition2-2').getValue() == ' ') {
        Ext.get('Addition2-2').on('focus', function(){
          Ext.get('Addition2-2').dom.value = ''
        });
      }
    }
    DeliveryCompany.on('click', setCompany2);
    DeliveryPrivate.on('click', setPrivate2);
  }

  // facebook integration: activities
  var FacebookActivity = El.select('.facebookActivity').item(0);
  if (Ext.isObject(FacebookActivity)) {
    FacebookActivity.on('click', function(){
      var site = document.URL.split('/')[2];
      new beeline.web.alert({
        title: 'Facebook',
        content: '<iframe class="facebookActivites" src="http://www.facebook.com/widgets/activity.php?site=' + site + '"></iframe><p class="alertboxButton"><span class="button"><input class="alertboxClose" type="reset" name="close" value="OK"/></span></p>'
      });
    });
  }

  // wikipedia integration: get author request
  var WikiAuthor = El.select('.wikiAuthor').item(0);
  if (Ext.isObject(WikiAuthor)) {
    var author = WikiAuthor.dom.innerHTML;
    author = author.split(';')[0];
    author = author.split(' (')[0];
    if (author.search(/, /) != -1) {
      author = (author.split(', ')[1] + '_' + author.split(', ')[0]).replace(/ /g, '_');
    }
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'http://de.wikipedia.org/w/api.php?action=parse&prop=text&format=json&page=' + author + '&callback=getWikiJSON';
    Ext.select('head').item(0).appendChild(script);
  }

  // phononet integration: get tracks request
  var TracksID = El.select('.tracksContentID').item(0);
  if (Ext.isObject(TracksID)) {
    var id = TracksID.dom.innerHTML;
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'http://musikwyler.biderundtanner.ch/api.php?callback=getTracklist&articleId='+id;   
    Ext.select('head').item(0).appendChild(script);
  }

  // help: switch to wiki documentation
  var ShowHelp = El.select('.showHelp').item(0);
  if(Ext.isObject(ShowHelp)){
    var focused = false;
    ShowHelp.on('click', function(){
      ShowHelp.setStyle('display', 'none');
    });
    El.select('.help').each(function(Help){
      var Element = Help.parent();
      Element.on('mouseover', function(){
        if(Ext.get('showHelp').getStyle('display') == 'none' && focused == false){
          focused = true;
          var CurrentHelp = this.first('.help');
          CurrentHelp.setStyle('display', 'block');
          CurrentHelp.setHeight(this.getHeight());
          CurrentHelp.setWidth(this.getWidth());
          var lineHeight = this.getHeight() - 3;
          CurrentHelp.setStyle('line-height', lineHeight + 'px');
        }
      });
      Element.on('mouseleave', function(){
        if(Ext.get('showHelp').getStyle('display') == 'none'){
          this.first('.help').setStyle('display', 'none');
          focused = false;
        }
      });
      Element.on('click', function(){
        if(Ext.get('showHelp').getStyle('display') == 'none'){
          var CurrentHelp = this.first('.help');
          CurrentHelp.setStyle('display', 'none');
          Ext.get('showHelp').setStyle('display', 'block');
          var url = Ext.get('helpurl').dom.innerHTML + 'wikihelp=Web:' + CurrentHelp.dom.innerHTML;
          window.open(url, 'help');
        }
      });
    });
  }

  // cover drag and drop
  //El.select('.cover').each(function(Cover){
  //  Cover.drag2Storage();
  //});

    // show login
  var LoginForm = Ext.select('.headerLogin').item(0);
  if(Ext.isObject(LoginForm)) {

    var PwdInput = Ext.get('bpmformLogin').child('.password');
    var EmailInput = Ext.get('bpmformLogin').child('.focus'); 

    Ext.select('.headerLoginQuickExpand').item(0).on('click', function(){
      LoginForm.slideIn('t', { concurrent: true });
      EmailInput.dom.value='Email';
    });
	
    EmailInput.on('focus', function() {
      if (typeof EmailInput.oldvalue=='undefined'){
        EmailInput.oldvalue=EmailInput.dom.value;
      }
      if (EmailInput.oldvalue==EmailInput.dom.value){
        EmailInput.dom.value='';
      }   
    });
    EmailInput.on('blur',function(){
      if ((EmailInput.dom.value.length==0)&&(typeof EmailInput.oldvalue!='undefined')){
        EmailInput.dom.value=EmailInput.oldvalue;
      }
    })
    PwdInput.on('focus', function() {
      PwdInput.oldvalue=PwdInput.getStyle('background-image');
      PwdInput.setStyle('background-image','url(hubweb/css/default/images/formBg.png)');         
    });
    PwdInput.on('blur',function(){
      if ((PwdInput.dom.value.length==0)&&(typeof PwdInput.oldvalue!='undefined')){
        PwdInput.setStyle('background-image',PwdInput.oldvalue);
      }  
    });
	
    Ext.select('.headerLoginCancel').each(function(CancelButton){
	  CancelButton.on('click', function(){
	    Ext.get('bpmformLogin').child('.password').dom.type='text';
        LoginForm.slideOut('t', { concurrent: true, useDisplay: true });
      });
    });

	var url = document.URL;
	var searchbpmact = url.indexOf('bpmact');
	  if (searchbpmact!= -1) {
	    var o = url.substr(searchbpmact,12);
	    if (o == 'bpmact=Login') {
		 LoginForm.show();
		 Ext.get('bpmformLogin').child('.focus').dom.value='Email';
	     Ext.get('bpmformLogin').child('.password').dom.value='Password';
		}}
  }
  var SearchForm = Ext.select('.headerSearch').item(0);
  if(Ext.isObject(SearchForm)) {
  
  Ext.select('.headerSearchQuickText').on('focus', function(){
  Ext.get('quicksearch').child('.headerSearchQuickText').dom.value='';
  Ext.get('quicksearch').child('.headerSearchQuickText').setStyle('color', '#000000');
  });
  }
  
}

// ----------------------------------------------------------------------------

// wikipedia integration: get author callback
function getWikiJSON(JSONData) {
  var content = JSONData['parse']['text']['*'];
  content = content.replace(/\/wiki\//g, 'http://de.wikipedia.org/wiki/');  // wikipedia links
  content = content.replace(/\/w\//g, 'http://de.wikipedia.org/w/');  // wikipedia links without article
  content = content.replace(/wikimedia.orghttp:\/\/de.wikipedia.org/g, 'wikimedia.org'); // wikimedia links
  var WikiInfo = Ext.select('.wikiAuthor').item(0);
  WikiInfo.update(content);
  Ext.select('.wikiEmpty').item(0).setStyle('display', 'none');
  WikiInfo.select('a').each(function(Link){
    // isbn search
    if(Link.hasClass('mw-magiclink-isbn')) {
      var separator = '?';
      if(document.URL.search(/\?/) != -1) separator = '&';
      var parm = 'bpmkey=%2Fresult&bpmparm=%2Fresult%2C%2Fdetail&bpmquery=';
      Link.dom.href = document.URL + separator + parm + Link.getAttribute('href').split('/')[5];
    }
    else {
      // disable all external links
      //if(Link.hasClass('external') && Link.dom.href.search(/wikimedia.org/) == -1) Link.dom.href = '#';
      // open external links in a new tab
      if(Link.dom.href.search(/http/) != -1) Link.dom.target = '_blank';
    }
  });
  var Weblinks = Ext.get('Weblinks');
  if(Ext.isObject(Weblinks)) {
    Weblinks.parent().setStyle('display', 'none');
    Weblinks.parent().next('ul').setStyle('display', 'none');
  }
}

// phononet integration: get tracks callback
function getTracklist(JSONData) {
  var content = JSONData['content'];
  var TracksInfo = Ext.select('.tracksContentData').item(0);
  TracksInfo.update(content);
  Ext.select('.tracksContentEmpty').item(0).setStyle('display', 'none');
}

// clear advanced search
function clearAdvancedSearch(){
  var Obj = document.forms[1];
  for (i = 0; i < Obj.elements.length; i++) {
    if (Obj.elements[i].type == 'text') {
      Obj.elements[i].value = '';
    }
    if (Obj.elements[i].type == 'select-one') {
      Obj.elements[i].selectedIndex = 0;
    }
  }
}

// approval plan: copy defaults
function copyDefaults(id){
  var element, value, form = Ext.get('bpmlist').dom.elements;
  element = form.namedItem(id + '_Quantity');
  if (!element) return;
  value = form.namedItem('Quantity').value;
  if (element && !element.value && value) {
    element.value = value;
    element.onchange();
  }
  element = form.namedItem(id + '_OrderReference');
  if (!element) return;
  value = form.namedItem('OrderReference').value;
  if (element && !element.value && value) {
    element.value = value;
    element.onchange();
  }
  element = form.namedItem(id + '_Comment');
  if (!element) return;
  value = form.namedItem('Comment').value;
  if (element && !element.value && value) {
    element.value = value;
    element.onchange();
  }
  element = form.namedItem(id + '_Comment1');
  if (!element) return;
  value = form.namedItem('Comment1').value;
  if (element && !element.value && value) {
    element.value = value;
    element.onchange();
  }
  element = form.namedItem(id + '_Comment2');
  if (!element) return;
  value = form.namedItem('Comment2').value;
  if (element && !element.value && value) {
    element.value = value;
    element.onchange();
  }
}

// approval plan: check all
function checkallAP(val){
  list = Ext.get('bpmlist').dom.elements;
  for (var i = 0; i < list.length; i++) {
    var el = list[i];
    var name = el.name.split('_');
    if (name[1] == 'CHECK' && el.checked != val) {
      el.checked = val;
      el.onchange();
      copyDefaults(name[0]);
    }
  }
}

// check all articles
function checkall(val){
  list = Ext.get('bpmlist').dom.elements;
  for (var i = 0; i < list.length; i++) {
    var el = list[i];
    var name = el.name.split('_');
    if (name[1] == 'CHECK' && el.checked != val) {
      el.checked = val;
      //el.onchange();
    }
  }
  
  
}

