var fancybox = {
  options: {
    'padding': 0,
    'scrolling': 'no',
    'titlePosition': 'inside',
    'overlayShow': true,
    'overlayColor': '#000',
    'overlayOpacity': 0.8,
    'autoDimensions': true,
    'hideOnOverlayClick': false,
    'autoScale': false,
    'onComplete': function(){
      fancybox.modifyHeader();
    }
  },

  init: function(){
    var tempOptions = $.extend(fancybox.options, {
      'autoDimensions': true,
      'hideOnOverlayClick': false
    });
    $('a[rel*=fancybox]').each(function(){
      $(this).attr('href', $(this).attr('href') + ($(this).attr('href').indexOf('?') > 0 ? '&' : '?') + 'ajax=true')
        .not('#createAddress, .dynamicFancybox a, #weather-traffic a')
        .fancybox(tempOptions);
    });

    var fancyboxLoader = $('#fancybox-loader');
    if(fancyboxLoader.length)
    {
      $.fancybox($.extend(fancybox.options, {
        'autoDimensions'      : true,
        'hideOnOverlayClick'  : false,
    		'href'                : fancyboxLoader.attr('data-url'),
        'titlePosition'       : 'inside',
        'title'               : fancyboxLoader.attr('title'),
    		'type'                : 'iframe'
    	}));
    }

    $('#compare-craftsmen').each(function()
    {
      $(window).load(function()
      {
        parent.fancybox.resize($('#iframe').outerHeight());
        parent.$('#fancybox-inner').css({'width': $('#compare-craftsmen').width()});
        parent.$('#fancybox-wrap').css({'width': $('#compare-craftsmen').width() + 20});
        parent.$.fancybox.center();
        parent.$('#fancybox-title').css({'width': $('#compare-craftsmen').width() + 9})
      });
    });

    var tempOptions = $.extend(tempOptions, {
      'width': 560,
      'height': 450
    });

    $('#weather-traffic a').fancybox(tempOptions);
    fancybox.createAddressLink($('#createAddress'));
    $('.dynamicFancybox').each(function(){
      fancybox.createDynamicFancybox($(this));
    });
  },

  createDynamicFancybox: function(element){
    var tempOptions = $.extend(fancybox.options, {
      'onCleanup': function(link){
        link.data('holder').load($('#' + link.data('holder').attr('id') + '-url').attr('href'), function(holder){
          fancybox.createDynamicFancybox($(this));
        });
      }
    });
    element
      .find('.delete')
      .data('holder', element)
      .bind('click', function(e){

        var answer = confirm($(this).attr('title'));

        if(answer){
          if(!$(this).hasClass('refresh')){
            e.preventDefault();

            var link = $(this);
            var url = link.attr('href');

            if($.browser.msie){
              var timestamp = new Date();
              url = url + (url.indexOf('?') > 0 ? '&' : '?') + timestamp.getTime();
            }

            $.ajax({
              method: 'post',
              url: link.attr('href'),
              success: function(){

                var url = $('#' + link.data('holder').attr('id') + '-url').attr('href');

                if($.browser.msie){
                  var timestamp = new Date();
                  url = url + (url.indexOf('?') > 0 ? '&' : '?') + timestamp.getTime();
                }

                $.ajax({
                  method: 'post',
                  url: url,
                  success: function(data){
                    var holder = link.data('holder');
                    holder.html(data);

                    fancybox.createDynamicFancybox(holder);
                  }
                });
              }
            });
          }
        }else{
          e.preventDefault();
        }
      })
      .end()
      .find('a[rel*=fancybox]')
      .data('holder', element)
      .fancybox(tempOptions);
  },

  createAddressLink: function(element){

    var tempOptions = $.extend(fancybox.options, {
      'onCleanup': function(){
      	if($('#get_address_link').length){
          var link = $('#get_address_link').attr('href');

          if($.browser.msie){
            var timestamp = new Date();
            link = link + '?' + timestamp.getTime();
          }

          $('#order_address-holder').load(link, function(response){

            $(this).find('input.fhDynamic, select.fhDynamic').fhDynamicSelect({
              onComplete: function(holder){
                holder
                  .find('input[type=text], input[type=password], textarea')
                  .fhInputClear();
                holder.find('input, textarea, select')
                  .gzPrettyForms();
                fancybox.createAddressLink(holder.find('a[rel*=fancybox]'));
              }
            });

            $(this)
              .find('input[type=text], input[type=password], textarea')
              .fhInputClear();
            $(this)
              .find('input, textarea, select')
              .gzPrettyForms();
            fancybox.createAddressLink($(this).find('a[rel*=fancybox]'));

          });
      	}else{
      	  window.location = window.location;
      	}
      }
    });

    element.fancybox(tempOptions);
  },
  resize: function(height){
    $('#fancybox-inner').height( height );
    $('#fancybox-wrap').height( height + 45 );
    $.fancybox.center();
  },
  setTitle: function(title){
    $('#fancybox-title').html(title + '<span class="fancybox-title-icon"></span>');
  },
  modifyHeader: function(){

    if(!$('#fancybox-frame').length){
      $('#fancybox-title').append(' | <a href="#" id="fancybox-print">print</a>');
    }

    $('#fancybox-title')
      .append( $('<span></span>')
      .addClass( 'fancybox-title-icon' ))
      .css({
        'paddingLeft': 25,
        'width': $('#fancybox-title').width() - 11
      });
  },
  printIt: function(printThis){
  	var win = window.open();
  	self.focus();
  	win.document.open();
  	win.document.write('<'+'html'+'><'+'head'+'><'+'style'+'>');
  	win.document.write('body, td { font-family: Verdana; font-size: 10pt;}');
  	win.document.write('<'+'/'+'style'+'><'+'/'+'head'+'><'+'body'+'>');
  	win.document.write(printThis);
  	win.document.write('<'+'/'+'body'+'><'+'/'+'html'+'>');
  	win.document.close();
  	win.print();
  	win.close();
  }
};

var search = {
  init: function(){

    var extended = $('#search .extended');

    var postalCode = $('#postalcode');

    if(postalCode.val() == '' || postalCode.val() == postalCode.data('originalValue'))
    {
      $('#distance').attr('disabled', true).trigger('change');
    };

    $('#postalcode')
      .bind('focus', function(){
        $('#distance')
          .attr('disabled', false)
          .trigger('change')
          .prev()
          .removeClass('disabled');
      })
      .bind('blur', function(){
        if($(this).val() == $(this).data('originalValue')){
          $('#distance')
            .attr('disabled', 'disabled')
            .trigger('change')
            .prev()
            .addClass('disabled');
        }
      });
    $('#search .simple a')
      .css({
        'display': 'inline-block'
      })
      .bind('click', function(){
        $('#search').toggleClass('active');
        $(this).toggleClass('closed');
      });
  }
}

var chart = {
  init: function(){
    $('#quotation-chart').addClass('chart');

    $('.chart').each(function(i){

      var availableHeight = $(this).height() - 10;

      var columns = $(this).find('.bar');
      if(columns.length > 0)
        var width = Math.floor($(this).width() / columns.length);
      else
        return false;

      var difference = $(this).width() - (columns.length * width);
      columns.each(function(i){

        $(this).css({
          'width': (width + (difference > 0 ? 1 : 0 ) - 1)
        });

        $(this).find('> a').each(function(i){

          var re = new RegExp(/chart\[([0-9\,\ ]+)\]/);
          var chart = re.exec($(this).attr('rel'));

          if(chart){
            var dimensions = chart[1].split(',');

            var height = Math.round(availableHeight / 100 * (100 - (100 / dimensions[2] * dimensions[0])));

            $(this).css({
              'width': (width + (difference > 0 ? 1 : 0 ) - 1),
              'textIndent': (width + (difference > 0 ? 1 : 0 ) - 1),
              'height': height + 10,
              'lineHeight': height + 10
            });
          }

          $(this).next().hide();

        });
        difference--;
      });
    });

    tip.setChartTip();
  },

  craftsmanStats: function(gDataTable, options)
  {
    options = $.extend({
      width: 500,
      height: 240,
      chartArea: {
        width: 420,
        height: 200
      },
      colors: ['#008ae8'],
      legend: 'none'
    }, options);

    var craftsmanChart = new google.visualization.ColumnChart(document.getElementById('craftsman_charts'));
    craftsmanChart.draw(gDataTable, options);
  }
}

var carousel = {
  carousel: null,

  init: function(){
    if($('.carousel-holder').length > 0) {
      $('.carousel-holder .carousel')
        .filter(
          function() {return $('#tabs.js').length < 1;}
        )
        .each(function() {
          carousel.setCarousel($(this));
        });
    }
  },

  setCarousel: function(el)
  {
    el.jcarousel({
        scroll: 3,
        initCallback: function(carouselHolder){
          el.find('.carousel-next').bind('click', function(e) {
            e.preventDefault();
            carouselHolder.next();
          });
          el.find('.carousel-prev').bind('click', function(e) {
            e.preventDefault();
            carouselHolder.prev();
          });
        },
        buttonNextHTML: null,
        buttonPrevHTML: null
    });
  }
}

var tabs = {
  init: function()
  {
    var tabElements = $('#tabs.js');
    if(tabElements.length)
    {
      tabElements.tabify();

      $('#tabs.js a').bind('click', function()
      {
        var el = $(this);
        tabs.checkForCarousel($(el.attr('href')).find('.carousel-holder .carousel'));
      });

      tabElements.find('.active a').trigger('click');
    }
  },

  checkForCarousel: function(elements)
  {
    setTimeout(function()
    {
      elements.each(function()
      {
        carousel.setCarousel($(this));
      });
    }, 500);
  }
}

var rating = {

  init: function(){
    $('.reference-rating').each(function(){
      var temp = $(this).gzRating({
        id: $(this).attr('id'),
        average: $('#' + $(this).attr('id').substr(0, $(this).attr('id').length - 7)).attr('value'),
        maximum: 10,
        onClick: function(rating, id){
          var input = id.substr(0, id.length - 7);

          $('#' + input).val(rating);
          $('#' + input + '-checkbox').attr('checked', false).trigger('change');
        },
        numbers: true,
        step: 1,
        amount: 10,
        initCallback: rating.callback,
        imagePath: url + 'wsCorePlugin/images/',
        image: 'rating.png',
        width: 20,
        height: 18
      });
    });
  },

  callback: function(rating){
    var name = rating.element.attr('id').substr(0, rating.element.attr('id').length - 7);

    $('#' + name + '-checkbox')
      .data('name', name)
      .bind('change', function(){
        if($(this).attr('checked')){
          rating.setAverage(0);
          $('#' + $(this).data('name')).val('0');
        }
        $(this).next().trigger('click');
      })
      .bind('click', function(){
        if($(this).attr('checked')){
          rating.setAverage(0);
          $('#' + $(this).data('name')).val('0');
        }
      });
  }
}

var tip = {

  init: function(){
    tip.simpleTip();
    tip.setStatusTip();
    tip.setReferences();
    tip.setWidgetTip();
  },

  simpleTip: function(){
    $('a[rel^=tipContent]').each(function(){
      var tipText = $(this).attr('rel').split(':')[1];
      $(this).qtip({
        content: tipText,
        show: 'mouseover',
        hide: {
          fixed: true,
          delay: 300
        },
        position: {
          corner: {
            target: 'topMiddle',
            tooltip: 'bottomMiddle'
          },
          adjust: {
            x: 0,
            y: 1
          }
        },
        style: {
          background: '#ffffff',
          border: {
            radius: 3,
            width: 0,
            color: '#7fc4f3'
          },
          color: '#000000',
          tip: {
            corner: 'bottomMiddle',
            color: '#7fc4f3',
            size: {
              x: 20,
              y : 8
            }
          },
          title: {
            'color': '#ffffff',
            'overflow': 'hidden',
            'background': '#7fc4f3',
            'font-size': '12px'
          },
          width: 200
        }
      });
    });
  },

  setReferences: function(){
    $('a[rel^=tipUrl]').each(function(){
      var referenceUrl = $(this).attr('rel').split(':')[1];
      if($(this).parent().hasClass('compare-grade'))
      {
        var cornerTarget = 'bottomMiddle',
            cornerTooltip = 'topMiddle',
            cornerHeight = 1
      }
      else
      {
        var cornerTarget = 'topMiddle',
            cornerTooltip = 'bottomMiddle',
            cornerHeight = -10
      }
      $(this).qtip({
        content: {
          url: referenceUrl
        },
        show: 'mouseover',
        hide: {
          fixed: true,
          delay: 300
        },
        position: {
          corner: {
            target: cornerTarget,
            tooltip: cornerTooltip
          },
          adjust: {
            x: 0,
            y: cornerHeight
          }
        },
        style: {
          background: '#ffffff',
          border: {
            radius: 3,
            width: 0,
            color: '#7fc4f3'
          },
          color: '#000000',
          tip: {
            corner: cornerTooltip,
            color: '#7fc4f3',
            size: {
              x: 20,
              y : 8
            }
          },
          title: {
            'color': '#ffffff',
            'overflow': 'hidden',
            'background': '#7fc4f3',
            'font-size': '12px'
          },
          width: 200
        }
      });
    });
  },

  setChartTip: function(){
    $('.chart').each(function(i){

      var columns = $(this).find('.bar');
      columns.each(function(i){

        $(this).find('> a').each(function(i){

          $(this).qtip({
            content: {
              text: $(this).next().html()
            },
            show: 'mouseover',
            hide: {
              fixed: true,
              delay: 300
            },
            position: {
              corner: {
                 target: 'topMiddle',
                 tooltip: 'bottomMiddle'
              }
            },
            style: {
              background: '#ffffff',
              border: {
                radius: 3,
                width: 0,
                color: '#7fc4f3'
              },
              color: '#000000',
              tip: {
                corner: 'bottomMiddle',
                color: '#7fc4f3',
                size: {
                  x: 20,
                  y : 8
                }
              },
              title: {
                'color': '#ffffff',
                'overflow': 'hidden',
                'background': '#7fc4f3',
                'font-size': '12px'
              },
              width: 200
            }
          });

        });
      });
    });
  },

  setWidgetTip: function(){

    $('.widget-qtip').each(function(i){

      $(this).qtip({
        content: {
          text: $(this).next().html()
        },
        show: 'mouseover',
        hide: {
          fixed: true,
          delay: 300
        },
        position: {
          corner: {
             target: 'bottomMiddle',
             tooltip: 'topRight'
          }
        },
        style: {
          background: '#ffffff',
          border: {
            radius: 3,
            width: 0,
            color: '#7fc4f3'
          },
          color: '#000000',
          tip: {
            corner: 'topRight',
            color: '#7fc4f3',
            size: {
              x: 20,
              y : 8
            }
          },
          title: {
            'color': '#ffffff',
            'overflow': 'hidden',
            'background': '#7fc4f3',
            'font-size': '12px'
          },
          width: 240
        }
      });

    });
  },

  setStatusTip: function(){
    $('#profile-status, .profile-status').qtip({
      content: {
        text: $('#profile-status-content')
      },
      show: {
        delay: 500
      },
      hide: {
        fixed: true,
        delay: 300
      },
      position: {
        corner: {
           target: 'topMiddle',
           tooltip: 'bottomMiddle'
        }
      },
      style: {
        background: '#ffffff',
        border: {
          radius: 3,
          width: 0,
          color: '#7fc4f3'
        },
        color: '#000000',
        padding: 0,
        tip: {
          corner: 'bottomMiddle',
          color: '#7fc4f3',
          size: {
            x: 20,
            y : 8
          }
        },
        width: 300
      }
    });
  }
}

var subscriptionChoice = {
  init: function(){
    if($('#subscription-choice').length > 0){
      $('#subscription-choice > li').click(function(){
        $(this).find('.trigger').attr('checked', true).trigger('change');
      });
    }
  }
}

var orders = {
  init: function(){
    var tables = $('.table');
    if(tables.length)
    {
      tables.each(function()
      {
        var sortCheckboxes = tables.find('table-sort :checkbox');
        var checkboxes = tables.find('.table-results :checkbox');
        
        tables.find('.table-sort :checkbox').bind('click', function()
        {
          checkboxes.attr('checked', $(this).attr('checked')).trigger('change');
        });
        checkboxes.bind('click', function()
        {
          if(!$(this).attr('checked'))
          {
            sortCheckboxes.attr('checked', false).trigger('change');
          }
        });
      });
    }
    if($('#orders').length > 0){

      $('.order-sort input[type=checkbox]').click(function(){
        $('#orders input[type=checkbox]').attr('checked', $(this).attr('checked')).trigger('change');
      });
      $('#orders input[type=checkbox]').click(function(){
        if(!$(this).attr('checked')){
          $('.order-sort input[type=checkbox]').attr('checked', false).trigger('change');
        }
      });
    }
  }
}

var categoriesChoice = {
  amount: 0,
  amountLeft: 0,
  mainCategory: null,
  options: null,
  singleTemplate: '',
  multipleTemplate: '',

  init: function(){
    var _this = this;
    this.choicesLeftHolder = $('#categories-choice-amount');
    if(this.choicesLeftHolder.length > 0){
      this.singleTemplate = categoriesMessages.templateSingle;
      this.multipleTemplate = categoriesMessages.templateMultiple;
      this.amount = "" + this.choicesLeftHolder.html().match(new RegExp("--[0-9]+--", "g"));
      this.amountLeft = this.amount = this.amount.substr(2, this.amount.length - 4);
      this.options = $('#categories-choice input[type=checkbox]');

      this.setMainCategory();
      this.checkCategories();
      this.setCheck();
      this.setChoicesLeft();

      $('#craftsman_register_main_category_id').change(function(){
        _this.resetChoices();
      });
    }
  },

  checkCategories: function(){
    var _this = this;
    this.options.filter(function(){
      if($(this).attr('checked')){
        if($(this).val() != _this.mainCategory){
          if(!_this.amountLeft > 0){
            $(this).attr('checked', false);
            $(this).trigger('change');
            _this.choicesLeftHolder.addClass('error');
          }else{
            _this.amountLeft--;
          }
          return true;
        }
      }
      return false;
    });
  },

  setCheck: function(){
    var _this = this;
    this.options.bind('click', function(e){
      if($(this).attr('checked')){
        if(!_this.amountLeft > 0){
          $(this).attr('checked', false);
          $(this).trigger('change');
          _this.choicesLeftHolder.addClass('error');
        }else{
          $(this).trigger('change');
          _this.amountLeft--;
        }
      }else{
        $(this).trigger('change');
        _this.amountLeft++;
      }
      _this.setChoicesLeft();
    });
  },

  setChoicesLeft: function(){
    this.choicesLeftHolder.removeClass('error');
    if(this.amountLeft == 1){
    	this.choicesLeftHolder.html(this.singleTemplate.replace(new RegExp("--1--", "g"), this.amountLeft));
    }else{
    	this.choicesLeftHolder.html(this.multipleTemplate.replace(new RegExp("--0--", "g"), this.amountLeft));
    }
  },

  resetChoices: function(){
    this.options.attr('checked', false).attr('disabled', false).trigger('change');
    this.setMainCategory();
    this.amountLeft = this.amount;
    this.setChoicesLeft();
  },

  setMainCategory: function(){
    var _this = this;
    this.mainCategory = $('#craftsman_register_main_category_id').val();
    this.options.filter(function(){
      if($(this).val() == _this.mainCategory)
        return true;
      return false;
    })
    .attr('checked', 'checked')
    .attr('disabled', 'disabled')
    .trigger('change');
  }
}

var tellafriend = {
  init: function(){
    if($('#multi-input').length > 0){
      $('#add-friend').bind('click', function(e){
        e.preventDefault();

        var li = $('#multi-input').find('li');
        var newLi = $(li[li.length - 1]).clone();

        newLi.find('input').val('').fhInputClear();

        $('#multi-input').append(newLi);

        parent.fancybox.resize($('#iframe').outerHeight());
      });
    }
  }
}

var faq = {
  init: function(){

    $('.faq-questions a.trigger').each(function(){

      if($(this).hasClass('active')){

      }

      $(this).bind('click', function(e){
        e.preventDefault();

        $(this).toggleClass('active').next().toggleClass('active');
      });
    });

    $('.faq-questions .description a').live('click', function(){
      $(this).attr('target', '_blank');
    });

  }
};

var fileDelete = {
  init: function(){
    // If it doesn't have the 'follow-link' class:
    $('li .delete:not(.follow-link)').live('click', function(e){
      var answer = confirm($(this).attr('title'));

      if(answer){
        if(!$(this).hasClass('refresh')){
          e.preventDefault();
          var deleteElement = $(this);

          var attributes = deleteElement.attr('rel').replace(/^\s+|\s+$/g,"").split(',');

          for(var i = 0; i < attributes.length; i++){
            var value = attributes[i].split(':');
            if(value[0] == 'target') deleteElement.data('target', value[1]);
          }
          if(deleteElement.data('target')){
            $(deleteElement.data('target')).val('1');
          }
          $(this).closest('li').remove();

          if($(this).attr('href') != ''){

            var url = $(this).attr('href');

            if($.browser.msie){
              var timestamp = new Date();
              url = url + (url.indexOf('?') > 0 ? '&' : '?') + timestamp.getTime();
            }

            $.ajax({
              url: url
            });
          }
        }
      }else{
        e.preventDefault();
      }
    });
  }
}

var tips = {
  init: function(){
    $('#tips ul').cycle({
      next: '#tips .next',
      prev: '#tips .prev',
      speed: 200,
      timeout: 5000
    });
  }
}

var textareas = {
  init: function(){
    $('#inquiry_text, #inquiry_answer_text').autoResize({
      extraSpace: 10
    });
    if($('#report_abuse_text').length)
    {
      $('#report_abuse_text').limit('500','#character-counter');
    }
  }
}

var teaserSwitch = {
  init: function(){
    $('.teaser-switch #sub-teaser-link').bind("click", function(e){
      e.preventDefault();
      $('.teaser-switch').toggleClass('active');
    });
  }
}

var fhHover = {
  init: function(){
    $('#latest-orders, #latest-references, #orders')
      .find('li')
      .not('.no-hover')
      .fhHover();
  }
}

var werkspotConnect = {
  init: function()
  {
    if($('.coop-highlight').length)
    { 
      if($('.coop-highlight li').length > 5)
      {
        
        $('.coop-highlight')
          .find('li')
          .filter(function(index)
          {
            return index > 4;
          })
          .hide()
          .end()
          .end()
          .append('<li class="coop-footer"><a href="#">Lees verder</a></li>')
          .find('.coop-footer')
          .bind('click', function()
          {
            $(this)
              .siblings()
              .show()
              .end()
              .hide();
          });
      }
    }
  }
}

var compareCraftsmen =
{
  init: function()
  {
     var len = $('.companyguide #results').length;

     if (len === 0)
     {
       var len = $('.companyguide #quotation-results').length;
     }

    if (len === 0)
    {
      var len = $('#conversations').length;
    }

     if(len > 0)
     {
      var $compareBtn = $('.compare-btn');
      var theList     = $('#orders .gzPrettyForms-checkbox + .emptyLabel');

      if (theList.length === 0)
      {
        var theList   = $('#conversations .gzPrettyForms-checkbox + .emptyLabel');
      }

      $(theList).bind('click', function()
      {
        var $input = $(this).parent().find('input');
        var $checked = $('#orders .gzPrettyForms-checkbox:checked').length;

        if ($checked === 0)
        {
          var $checked = $('#inquiries .gzPrettyForms-checkbox:checked').length;
        }

        if ($('#checked-craftsman'))
        {
          var checkedCraftsmen = parseInt($('#checked-craftsmen').val());
        }

        if(!$input.attr('checked'))
        {
          $checked = checkedCraftsmen + 1;

          if($checked <= 3 && $checked >= 2)
          {
            $input.attr('checked', true).trigger('change');
          }
          else if($checked > 3)
          {
            alert('Je kunt tot 3 vakmannen vergelijken.');
          }
          else if($checked < 2)
          {
            $input.attr('checked', true).trigger('change');
          }
        }
        else
        {
          $checked = checkedCraftsmen - 1;

          $input.attr('checked', false).trigger('change');
        }

        if ($checked < 4)
        {
          $('#checked-craftsmen').val($checked);

          $.ajax({
            url: $input.attr('data-url'),
            cache: false
          });
        }

      });
    }
  }
}

var promoSale = {
  init: function()
  {
    var displayPossibilities = $('#display-possibilities-form');
    if(displayPossibilities.length)
    {
      var checkboxes = displayPossibilities.find(':checkbox');
      var price = $('#display-possibilities-options-price span');
      var totalPriceSpan = $('.total-price');

      displayPossibilities.change(function()
      {
        var amount = displayPossibilities.find('#display-possibilities-options :checkbox:checked').length;

        var totalPrice = (amount * parseFloat(price.attr('data-price'))).toFixed(2);

        price.html(String(totalPrice).replace('.', ','));
        totalPriceSpan.html((amount * parseFloat(price.attr('data-price'))).toFixed(2).replace('.', ','));
      });
      displayPossibilities.change();

      displayPossibilities.submit(function()
      {
        if ($('#payment_method_collection').is(':checked') && !$('#collection_accept').is(':checked'))
        {
          alert($('#collection_accept').attr('data-failure'));
          return false;
        }
      });
    }

    $('#display-possibilities li.infobox.clickable').click(function()
    {
      document.location.href = $(this).find('a').attr('href');
    });

    if (String(window.location.hash).indexOf('promosubscription') == 0)
    {
      $('a.promosubscription-link').click();
    }
  }
}

var adUnit = {
  init: function(){

    $('#tertiary-column .ad').each(function(){
      var $this = $(this),
          width = $this.find('object, img, td > div').outerWidth(true); // True = including margin

      if(width === 180){
        $this.removeClass('style');
      }
    });

    $('.ad.block').each(function(){
      var $this = $(this),
          height = $this.outerHeight();

      if(height < 30){
        var tr = $this.parent().parent();

        if(tr.is('tr')) {
          tr.remove();
        } else {
          $this.remove();
        }
      }
    });

  }
}

$(window).load(function(){

  var iframe = $('#iframe');
  if(iframe.length > 0){
    if(iframe.attr('data-title'))
    {
      parent.fancybox.setTitle(iframe.attr('data-title'));
    }
    if($.browser.msie && $.browser.version < 8){
      iframe.hover(function(){
        parent.fancybox.resize(iframe.outerHeight());
      });
    }else{
      parent.fancybox.resize(iframe.outerHeight());
    }
  }

  adUnit.init();

});

var choices = {
  init: function()
  {
    var iframe = $('#iframe');
    var input = $('input:checked.choices');
    if(input.val() == 'other');
    {
      input.nextAll('.choice-other').show();
      if(iframe.length > 0){
        parent.fancybox.resize($('#iframe').outerHeight());
      }
    }
    $('input.choices').change(function()
    {
      $('.choice-other').hide();
      if($(this).is(':checked'))
      {
        $(this).nextAll('.choice-other').show();
      }
      if(iframe.length > 0){
        parent.fancybox.resize($('#iframe').outerHeight());
      }
    });
  }
}

$(document).ready(function(){
  subscriptionChoice.init();
  categoriesChoice.init();
  fancybox.init();
  $('input[type=text], input[type=password], textarea').fhInputClear();
  if($.browser.msie)
  {
    $('input, textarea, select')
      .filter(function()
      {
        return ($(this).parents('#iframe').length == false)
      })
      .gzPrettyForms();
  }
  else
  {
    $('input, textarea, select').gzPrettyForms();
  }
  fileDelete.init();
  chart.init();
  faq.init();
  carousel.init();
  tabs.init();
  rating.init();
  tip.init();
  orders.init();
  tellafriend.init();
  tips.init();
  textareas.init();
  teaserSwitch.init();
  fhHover.init();
  werkspotConnect.init();
  compareCraftsmen.init();
  promoSale.init();
  choices.init();
  $('.hidden-trigger').trigger('click');

  if($.fn.fhEllipses){
    $('p.truncated-text')
      .find('.read-more')
      .live('click', function(e){
        if($(this).parent().next().hasClass('truncated-full-text')){
          e.preventDefault();
          $(this).parent()
            .hide()
            .next()
            .show();

          if($(this).parent().parent().parent().parent().parent().attr('id') == 'compare-craftsmen')
          {
            parent.fancybox.resize($('#compare-craftsmen').outerHeight() + 10);
          }
        }
      })
      .end()
      .fhEllipses({
        lines: 5,
        readMoreElement: 'a.read-more'
      });
  }

  $('a.fancybox-close').live('click', function(e){
    e.preventDefault();
    if($(this).hasClass('fancybox-redirect')) {
      parent.window.location = $(this).attr('href');
    } else {
      parent.$.fancybox.close();
    }
  });

  $('.print').bind('click', function(){
    window.print();
  });

  $('.ajax-link').bind('click', function(e){
    $.ajax({
      url: $(this).attr('data-url')
    });
  });

  $('.phone').bind('click', function(e){
    $.ajax({
      url: $(this).attr('data-url')
    });
    e.preventDefault();
    $(this).hide().next().show();
  });

  $('.mail').bind('click', function(e){
    $.ajax({
      url: $(this).attr('data-url')
    });
    e.preventDefault();
  });

  if($('input.date').length > 0){
    $('input.date').datePicker({
      startDate: startDate
    });
  }
  $('p.date').fhPrettyDate({ interval: 1000 });
  $('input.fhDynamic, select.fhDynamic').fhDynamicSelect({
    onComplete: function(holder){
      holder
        .find('input[type=text], input[type=password], textarea')
        .fhInputClear()
        .end()
        .find('input, textarea, select')
        .gzPrettyForms();
      fancybox.createAddressLink(holder.find('a[rel*=fancybox]'));
    }
  });

  search.init();

  $('.collapse-trigger').live('click', function(e)
  {
    e.preventDefault();
    var el = $(this);
    $('#' + el.attr('data-trigger-id')).toggle();
    el.toggleClass('active');
  });

	$("#fancybox-print").live('click', function(){
		fancybox.printIt($('#fancybox-inner').html());
  });

  $('a[rel*=external]').live('click', function(){
    $(this).attr('target', '_blank');
  });
  
  $('a[rel*=self]').live('click', function(){
    $(this).attr('target', '_top');
  });

  $('#facebook a').not('.facebook-internal').attr('target', '_blank');

  $('.confirm').live('click', function(e){
    var answer = confirm($(this).attr('title'));

    if(!answer){
      e.preventDefault();
    }
  });

  if($('#form-warning').length)
  {
    $('.flush').click(function()
    {
      window.onbeforeunload = null;
    });

    var formWarningSet = false;

    $('form').change(function()
    {
      if (!formWarningSet)
      {
        formWarningSet = window.onbeforeunload = function()
        {
          return windowUnloadMessage;
        }
      }
    });
  }

  $('.gaq_push').live('click', function(e){
    var element = $(this);
    if(_gaq)
    {
      _gaq.push([element.attr('data-action'), element.attr('data-variable')]);
    }
  });
});

