/* Diplomica Javascript
   (c) 2011 n@work Internet Informationssysteme GmbH
*/


function consoleFake() {
    return {'debug':function() {} }
}

if (typeof(console)=='undefined') {
    var console = new consoleFake();
}


$.cookie("katalogSichtbar","-");

function toggleKatalogSearchField(event) {
    var showBox = $.cookie("katalogSichtbar");
    if(showBox!='+') {
        toggleKatalog(event);
    }
}

function toggleKatalog(event) {
    event.stopImmediatePropagation();
    event.preventDefault();
    var showBox = $.cookie("katalogSichtbar");
    //console.debug('click showbox='+showBox);

    if (showBox=='+') {
	//console.debug('to hide');
        katalogVerbergen();
        $.cookie("katalogSichtbar",'-');
    } else {
	//console.debug('to show');
        katalogZeigen();
        $.cookie("katalogSichtbar",'+');
    }
}

function katalogZeigen() {
    var box = $('#katalog_box');
    box.removeClass('katalog_baum_closed');
    box.slideDown(400, function() {box.find('.katalog_baum_liste').children().css('position', 'relative');});
    $('#katalogschalter img').attr('src','/fileadmin/resources/img/katalog_close.gif');
}

function katalogVerbergen() {
    var box = $('#katalog_box');
    box.find('.katalog_baum_liste').children().css('position', 'static');
    box.slideUp(400, function() {box.addClass('katalog_baum_closed')})
    $('#katalogschalter img').attr('src','/fileadmin/resources/img/katalog_open.gif');
}

function viewbox(id,numrows) {
    //console.debug('viewboxConstructor');
    var self = this;
    var data = $(id).find('.hiddendata');
    var items = $(data).find('.thesis');
    var currentSlot = 0;
    var numrows = numrows;
    var maxSlots = 0;
    //console.debug(maxSlots);
    var display = $(id).find('.viewboxdisplay');
    //console.debug(display);
    var dotsContainer = $(id).find('.dots')

    this.initControls = function(rows) {
       numrows = rows;
       maxSlots = Math.ceil(items.length/numrows)-1;
       //console.debug(maxSlots);
       var dot = $(dotsContainer).children()[0];
       $(dotsContainer).empty();
       for (i=0; i<=maxSlots; i++) { $(dot).clone().appendTo(dotsContainer).find('a').addClass('dot-'+i+' dot').attr('title', i) }
       if (maxSlots == 0) {
           $(id).find('.controls').hide();
       }
    }

    this.clearDisplay = function() {
       //console.debug('clearDisplay');
       display.animate({opacity: '0'}, 
                       'fast', 
                       function() {display.empty(); self.show();}
       );
    }

    this.show = function() {
       for (var i=0; i<numrows; i++) {
          $(items[currentSlot*numrows+i]).clone().appendTo(display);
       }
       display.animate({opacity: '1'});
       //console.debug("x1x");
       $($($(dotsContainer).children()[currentSlot]).children()[0]).addClass('control_arrow_active');
       //console.debug("x2x");
    }

    this.next = function() {
       //console.debug('next');
       if (currentSlot < maxSlots) {
           $($($(dotsContainer).children()[currentSlot]).children()[0]).removeClass('control_arrow_active');	
           currentSlot += 1;
           //console.debug(currentSlot);	
           self.clearDisplay();
           //self.show();
       }
    }
   
    this.previous = function() {
       //console.debug('previous');
       if (currentSlot > 0) {
           $($($(dotsContainer).children()[currentSlot]).children()[0]).removeClass('control_arrow_active');	
           currentSlot -= 1;
           //console.debug(currentSlot);
           self.clearDisplay();
           //self.show();
       }
    }

    this.move = function(event) {
       currentSlot = Number(event.currentTarget.title);
       //console.debug(currentSlot);
       $(dotsContainer).children().children().removeClass('control_arrow_active');
       self.clearDisplay();
    }

    return {
    // public methods
       'init': function(rows) {
           // optional parameter rows
           if (rows === undefined) {
              rows = numrows
           }
           //console.debug('viewbox init');
           self.initControls(rows);
           $.each($(dotsContainer).children(),function() { $($(this).children()[0]).removeClass('control_arrow_active') });
           self.clearDisplay();
           //self.show();
       },
       'get_data': function() {return data},
       'next' : function(event) {
           event.preventDefault();
	   self.next();
       },
       'previous' : function(event) {
           event.preventDefault();
           self.previous();
       },
       'move' : function(event) {
           event.preventDefault();
           self.move(event);
       }
    };
}
viewboxes = {};

function viewboxInit(id) {
   viewboxInitWithNumRows(id,5)
}

function viewboxInitWithNumRows(id,numrows) {

    //console.debug('viewbox factory start');
    //console.debug(id);
    box = new viewbox(id,numrows);
    box.init();
    viewboxes[id.attr('id')] = box;
    $(id).find('.next').click(box.next);
    $(id).find('.prev').click(box.previous);
    $(id).find('.dot').click(box.move);
    //console.debug('viewbox factory end');
}

function viewBoxTreeLevel0Fix() {
    posdiff = Math.abs($('#bestsellerViewBox').offset().top - $('#neueArbeitenViewBox').offset().top);
    if (posdiff > 50) {
       viewboxes['bestsellerViewBox'].init(3);
    } else if (posdiff > 10) {
       $('#bestsellerViewBox').prev().remove();
    }
}


function initHelpdeskCallback(data) {
   if (!$.cookie('diplomicahelp')) {
     var helpcache = String(new Date().getTime()) + ':' + data['status'];
     $.cookie('diplomicahelp',helpcache);
   }
   if (data['status'] == 'open') {
      $('#hotlinetoggle').removeClass('hotline_closed').addClass('hotline_open');
   } else {
      $('#hotlinetoggle').removeClass('hotline_open').addClass('hotline_closed');
   }
}

function initHelpdesk() {
   //console.debug('initHelpdesk');
   var helpcache = $.cookie('diplomicahelp');
   // helpcache format: <datetime_in_millis>:(open|closed)
   if (helpcache) {
      helpcache = helpcache.split(':');
      if (new Date().getTime()-helpcache[0] < 900000) {
         //console.debug('initHelpdeskcached');
         return initHelpdeskCallback({'status':helpcache[1]});
      }
   }
   $.getJSON('/zwkjson/initHelpdesk',initHelpdeskCallback);
}

function initWKStoreData(data) {
   if (!$.cookie('diplomicawkdata')) {
      var sdata = " ";
      for (var i = 0; i<data['items'].length; i++) {
          var item = data.items[i];
          sdata=sdata + item.arbid+':*:'+item.titel+':*:'+item.coverurl+':*:'+item.url+':@:';
      }
      $.cookie('diplomicawkdata',sdata);
   }
}
     
function initWKGetData() {
   var data = {items:Array()}
   var sdata = $.cookie('diplomicawkdata');
   if (!sdata) {
      sdata = ":@:";
   }
   var lines = sdata.split(':@:');
   for (var i=0 ; i<(lines.length-1); i++) {
      var item = lines[i].split(':*:');
      data['items'].push({arbid:item[0],titel:item[1],coverurl:item[2],url:item[3]})
   }
   data['count']=data['items'].length;
   return data;
}


function initWKCallback(data) {
   //console.debug('initWKCallback');
   initWKStoreData(data);

   count = data['count'];
   $('#meta_wk > span').html('Ihr Warenkorb: '+count+' Artikel');
   var wklist = $('#meta_wk + div')
   wklist.empty();
   if (count == 0) {
        wklist.html('<h6>Ihr Warenkorb ist leer</h6>');
   } else {
	var text = "";
  	for (itemnr=0; itemnr < data['items'].length; itemnr++) {
           var item = data['items'][itemnr]; 
           text = text + '<div class="thesis clearfix">';
	   text = text + '<span class="book-thumb"><a href="' +item['url']+ '"><img width="30" height="43" src="' +item['coverurl']+ '" alt="' +item['titel']+ '" /></a></span>';
	   text = text + '<div class="book-infos"><span class="title"><a href="' +item['url']+ '">' + item['titel'] + '</a></span></div> </div>';
	}
        text = text + '<a class="kasse" rel="nofollow" href="/zwkorder">Zur Kasse gehen</a>';
        wklist.html(text);
   }
}

function initWK() {
   //console.debug('initWK');
   if ($.cookie('diplomicawkdata') && !$.cookie('initWKDoReload'))  {
      //console.debug('initWK cached');
      initWKCallback(initWKGetData());
   } else {
      $.cookie('diplomicawkdata',null);
      $.cookie('initWKDoReload',null);
      $.getJSON('/zwkjson/initWK',initWKCallback);
   }
}

$(document).ready(
   function () {
      $('.katalog_baum_liste').children().css('position', 'static');
      $('#katalog_box').hide();
      $('#katalogschalter').click(toggleKatalog);
      $('.searchfield').click(toggleKatalogSearchField);
      initHelpdesk();
      initWK();
   }
);

/* ******************************************
   Schlagwortsuche per Javascript in Suchfeld
   ******************************************* */

function search(sword) {
   document.suchen['suchstr:ustring:utf-8'].value=sword;
   document.suchen.suchen.click();
}

/* ******** 
    Helper 
   ******** */


