/**
 * @author: Alan Whitelaw <alan.whitelaw@broxap.com>
*/

(function ($) {
  $(function () {

    if ($('#configurator').length > 0) {
      
/** Functions *****************************************************************/
      
      function updateBasket() {
        
        total_price = 0.00;
        total_weight = 0.00;
        
        $('#mini_basket table tbody').empty();
        $('#mini_basket table tfoot').empty();
        $('#mini_basket #form_items').empty();
        
        $.each(Basket, function () {
          
          row_price = this['details']['price'] * this['qty'];
          row_weight = this['details']['weight'] * this['qty'];
          
          table_rows = $('<tr></tr>');
          $(table_rows)
            .append('<td>' + this['sku'] + '</td>')
            .append('<td>' + this['details']['name'] + '</td>')
            .append('<td>' + price_display(this['details']['price']) + '</td>')
            .append('<td>' + this['qty'] + '</td>')
            .append('<td>' + price_display(row_price) + '</td>')
            .append('<td>&nbsp;</td>');
          
          $('#mini_basket table tbody').append(table_rows);
          
          basketstr = this['details']['productid'] + 'x' + this['details']['optionid'] + 'x0x0xN'
          $('#mini_basket #form_items').append($('<input type="hidden" name="cfg[' + basketstr + ']" value="' + this['qty'] + '" />'));
          
          total_price += row_price;
          total_weight += row_weight;
          
        });
        
        ns_rail_length = 0;
        os_rail_length = 0;
        
        qty_355 = 0;
        qty_455 = 0;
        
        $(cfg.data).each(function (i,v) {
          if (v.side == 'ns') {
            ns_rail_length += v.dimensions.W * 1;
          }
          if (v.side == 'os') {
            os_rail_length += v.dimensions.W * 1;
          }
          if(v.dimensions.D == 355) {
            qty_355++
          }
          if(v.dimensions.D == 455) {
            qty_455++
          }
          
        });
        
        if (os_rail_length != 0 || ns_rail_length != 0) {
          
          rail_price = 0;
          
          callbacksToComplete = 0;
          if (os_rail_length != 0 && ns_rail_length != 0) {
            callbacksToComplete = 2;
          } else {
            callbacksToComplete = 1;
          }
          
          // DIRTY - using floor price to determine if there is a floor
          if (cfg.floor_price > 0) {
            var sync = {
              callbacksToComplete: callbacksToComplete,
              callbacksCompleted: 0,
              rail_price: 0,
              callback: function (){
                
                this.callbacksCompleted++;
                
                if(this.callbacksCompleted == this.callbacksToComplete) {
                  
                  $.ajax({
                    type: "GET",
                    url: "/_inc/configurator/product2json.php",
                    data: "product=" + "UFRB1",
                    dataType: 'json',
                    success: function (result) {
                      
                      result.price = result.price * 1
                      
                      string_to_append = '<tr>'
                      string_to_append += '<td>' + result.sku + '</td>'
                      string_to_append += '<td>' + result.name + '</td>'
                      string_to_append += '<td>' + price_display(result.price) + '</td>'
                      string_to_append += '<td>' + cfg.data.length * 2 + '</td>'
                      string_to_append += '<td>' + price_display(cfg.data.length * 2 * result.price) + '</td>'
                      string_to_append += '<td>&nbsp;</td>'
                      string_to_append += '</tr>'
                      
                      $('#mini_basket table tbody').append(string_to_append)
                      
                      basketstr = result.id + 'x0x0x0xN'
                      $('#mini_basket #form_items').append($('<input type="hidden" name="cfg[' + basketstr + ']" value="' + cfg.data.length * 2 + '" />'));
                      
                      total_price += cfg.data.length * 2 * result.price
                      total_price += sync.rail_price;
                      
                      display_price(total_price, total_weight)
                    }
                  });
                  
                }
              }
            };
            
            function fetch_rail(rail_length) {
              rail_length = Math.ceil(rail_length / 250) * 250;
              rail_length < 750 ? rail_length = 750 : rail_length = rail_length
              rail_length > 4000 ? rail_length = 4000 : rail_length = rail_length
              part_no = "UFR-" + rail_length;
              
              $.ajax({
                type: "GET",
                url: "/_inc/configurator/product2json.php",
                data: "product=" + part_no,
                dataType: 'json',
                success: function (result) {
                  
                  result.price = result.price * 1
                  
                  string_to_append = '<tr>';
                  string_to_append += '<td>' + result.sku + '</td>'
                  string_to_append += '<td>Rail</td>'
                  string_to_append += '<td>' + price_display(result.price ) + '</td>'
                  string_to_append += '<td>1</td>'
                  string_to_append += '<td>' + price_display(result.price) + '</td>'
                  string_to_append += '<td>&nbsp;</td>'
                  string_to_append += '</tr>'
                  
                  $('#mini_basket table tbody').append(string_to_append)
                  
                  basketstr = result.id + 'x0x0x0xN'
                  $('#mini_basket #form_items').append($('<input type="hidden" name="cfg[' + basketstr + ']" value="1" />'));
                  
                  sync.rail_price += result.price
                  sync.callback();
                }
              });
            }
            if (ns_rail_length > 0) {
              fetch_rail(ns_rail_length)
            }
            if (os_rail_length > 0) {
              fetch_rail(os_rail_length)
            }
            
          } else {
            
            if(qty_355 > 0 || qty_455 > 0) {
              if (qty_355 > 0 && qty_455 > 0) {
                callbacksToComplete = 2
              } else {
                callbacksToComplete = 1
              }
            } else {
              callbacksToComplete = 0
            }
            
            var sync = {
              callbacksToComplete: callbacksToComplete,
              callbacksCompleted: 0,
              fixing_price: 0,
              callback: function (){
                
                this.callbacksCompleted++;
                
                if(this.callbacksCompleted == this.callbacksToComplete) {
                  
                  total_price += this.fixing_price;
                  display_price(total_price, total_weight)
                  
                }
              }
            };
            
            function fetch_universal_fixing_kit(qty_unit_depth, fixing_sku) {
              
              $.ajax({
                type: "GET",
                url: "/_inc/configurator/product2json.php",
                data: "product=" + fixing_sku,
                dataType: 'json',
                success: function (result) {
                  
                  result.price = result.price * 1
                  
                  string_to_append = '<tr>'
                  string_to_append += '<td>' + result.sku + '</td>'
                  string_to_append += '<td>' + result.name +'</td>'
                  string_to_append += '<td>' + price_display(result.price) + '</td>'
                  string_to_append += '<td>' + qty_unit_depth + '</td>'
                  string_to_append += '<td>' + price_display(result.price * qty_unit_depth) +'</td>'
                  string_to_append += '<td>&nbsp;</td>'
                  string_to_append += '</tr>'
                  
                  $('#mini_basket table tbody').append(string_to_append)
                  
                  basketstr = result.id + 'x0x0x0xN'
                  $('#mini_basket #form_items').append($('<input type="hidden" name="cfg[' + basketstr + ']" value="' + qty_unit_depth + '" />'));
                  
                  sync.fixing_price += result.price * qty_unit_depth
                  sync.callback();
                  
                }
              });
            }
            
            if (qty_355 > 0) {
              fetch_universal_fixing_kit(qty_355, '612-0849')
            }
            if (qty_455 > 0) {
              fetch_universal_fixing_kit(qty_455, '612-0850')
            }
            
          }
          
        } else {
          
          display_price(total_price, total_weight)
          
        }
        
      }
      
      function display_price(total_price, total_weight) {
        
        // cfg object tracks floor and it's price
        total_price = total_price + cfg.floor_price;
        
        total_price = price_display(total_price)
        
        var price_summary = '<tr>'
        price_summary += '<td colspan="4">&nbsp;</td>'
        price_summary += '<td><strong>Total Price (ex. VAT):</strong></td>'
        price_summary += '<td><strong>' + total_price + '</strong></td>'
        price_summary += '</tr>'
        
        var weight_summary = '<tr>'
        weight_summary += '<td colspan="4">&nbsp;</td>'
        weight_summary += '<td><strong>Total Weight:</strong></td>'
        weight_summary += '<td><strong>' + total_weight + 'kg</strong></td>'
        weight_summary += '</tr>'
        
        $('#mini_basket table tfoot')
          .append(price_summary)
          //.append(weight_summary)
        
        $('#cfg_price span').html(total_price);
        $('#cfg_weight span').html(total_weight);
      }
      
      function price_display(p) {
        return '&pound;' + parseFloat(p).toFixed(2);
      }
      
      function redrawIsometric() {
        
        $('.' + cfg.side + ' .iso_items').empty();
        
        function ascn(a,b) {return a.pos - b.pos;}
        function dscn(a,b) {return b.pos - a.pos;}
        
        cfg.isometric.sort(ascn);
        
        hide_warn();
        
        $('#cfg_warn').text('Loading').show();
        var this_side_items = 0;
        var shown = 0;
        $(cfg.isometric).each(function (i,v){
          if (v.side == cfg.side) {
            this_side_items++;
          }
        });
        
        if (this_side_items == 0) {
          $('#cfg_warn').fadeOut();
        }
        
        $(cfg.isometric).each(function (i,v) {
          
          var object_height = $('.product_helper[title="' + v.sku + '"]').css('height').replace('px','');
          
          if ($('.' + cfg.side + '.arch').css('top')) {
          
            var top_below = v.pos * 1 > $('.' + cfg.side + '.arch').css('top').replace('px','');
            var bottom_below = (v.pos * 1 + object_height * 1) > $('.' + cfg.side + '.arch').css('top').replace('px','');
            
            if (!top_below && bottom_below) {
              skuparts = v.sku.split('-');
              
              if (skuparts[1] == '03') {
                show_warn('Depending on your van there may not be space for Jerry Cans either side of the wheel arch.');
              }
            }
          }
          
          if (v.side == cfg.side) {
            var src_to_add = v.sku;
            
            if (cfg.side == 'ns') {
              img_to_add = $('<img src="/_images/_products3d/' + src_to_add + '.png" id="iso_' + cfg.side + '_' + i + '" class="" />');
            } else {
              img_to_add = $('<img src="/_images/_products3d/' + src_to_add + '(os).png" id="iso_' + cfg.side + '_' + i + '" class="" />');
            }
            
            img_to_add.hide();
            
            img_to_add.bind("load",function () {
              
              iso_side_i_width = $(this).width();
              iso_side_i_height = $(this).height();
              
              iso_side_i_width_px = iso_side_i_width * cfg.isometric_ratio;
              iso_side_i_height_px = iso_side_i_height * cfg.isometric_ratio;
              
              $(this).css({'width': iso_side_i_width_px + 'px'});
              
              offset_percent = v.pos / (cfg.van_length / 10);
              
              var half_isometric_width = cfg.isometric_width / 2;
              
              offset_px = half_isometric_width * offset_percent;
              
              center_offeset_top = half_isometric_width - (iso_side_i_height_px / 2);
              center_offeset_left = half_isometric_width - (iso_side_i_width_px / 2);
              $(this).css('top', center_offeset_top + (offset_px * 0.5773));
              
              if (cfg.side == 'ns') {
                $(this).css('left', center_offeset_left - offset_px);
              } else {
                $(this).css('left', center_offeset_left + offset_px);
              }
              
              $(this).show();
              
              shown++;
              if (shown == this_side_items) {
                $('#cfg_warn').fadeOut();
              }
              
            });
            
            $('#isometric_' + cfg.side + ' .iso_items').append(img_to_add);
          }
        });
        
        save.save_to_db();
        
      }
      
      /**
       * Function for showing an note
       */
      function show_note(message) {
        $('#cfg_note').text(message);
        $('#cfg_note').show();
      };
      
      /**
       * Function for hinding a note
       */
      function hide_note() {
        $('#cfg_note').hide();
      };
      
      /**
       * Function for showing an warning (used for jerry can straddle)
       */
      function show_warn(message) {
        $('#cfg_warn').text(message);
        $('#cfg_warn').show();
      };
      
      /**
       * Function for hinding an warning (used for jerry can straddle)
       */
      function hide_warn() {
        $('#cfg_warn').hide();
      };
      
      /**
       * Function for flashing an error
       */
      function show_error(message) {
        
        var error = $('<div class="cfg_error"></div>').append(message);
        
        $('#configurator_container').append(error);
        
        setTimeout(function () {
          $('.cfg_error').fadeOut();
        }, 5000);
        
      };
      
      /**
       * function for changing side
       */
      function change_side(side) {
        if (side == 'ns') {
          var otherside = 'os';
        } else {
          var otherside = 'ns';
        }
        if(!$('#b_' + side).hasClass('selected')) {
          $('#b_' + side).addClass('selected');
          $('#b_' + otherside).removeClass('selected');
          cfg.side = side;
          $('.' + side).show('fast');
          $('.' + otherside).fadeOut();
          
          update_size_selected();
          
          if (side == 'ns') {
            $('#configurator_products img.product, #configurator_products img.option').each(function (i,e) {
              var src = $(e).attr("src").replace("(os)", "");
              $(e).attr("src", src);
            });
          } else {
            $('#configurator_products img.product, #configurator_products img.option').each(function (i,e) {
              if ($(e).attr("src").indexOf('(os)') == '-1') {
                var src = $(e).attr("src").match(/[^\.]+/) + "(os).png";
                $(e).attr("src", src);
              }
            });
          }
        }
        redrawIsometric();
      }
      
      /**
       * show hide all js required areas.
       */
      function is_compatable() {
        if (
            !is_ie6() &&
            !is_touch_device() &&
            !$.browser.opera
            ) {
          return true;
        } else {
          return false;
        }
      }
        function is_ie6() {
          if ($.browser.msie && $.browser.version < 7) {
            return true;
          } else {
            return false;
          }
        }
        function is_touch_device() {
          try {  
            document.createEvent("TouchEvent");  
            return true;  
          } catch (e) {  
            return false;
          }
        }
      
      /**
       * Function to see if there are items on side
       * @param side
       */
      function countItemsOnSide(side) {
        count = 0;
        
        $(cfg.isometric).each(function (i,v) {
          if (v.side == side) {
            count++;
          }
        });
        
        return count;
      }
      
      /**
       * Functionality for all zee drag and drop
       */
      function update_size_selected() {
        
        $('#b_355').removeClass('selected');
        $('#b_455').removeClass('selected');
        
        if (cfg.side == 'os') {
          if (cfg.os_depth != '') {
            if (cfg.os_depth == 355) {
              $('#b_355').addClass('selected');
              $('.options_455').hide();
              $('.options_355').show();
            } else {
              $('#b_455').addClass('selected');
              $('.options_355').hide();
              $('.options_455').show();
            }
          }
        } else {
          if (cfg.ns_depth != '') {
            if (cfg.ns_depth == 355) {
              $('#b_355').addClass('selected');
              $('.options_455').hide();
              $('.options_355').show();
            } else {
              $('#b_455').addClass('selected');
              $('.options_355').hide();
              $('.options_455').show();
            }
          }
        }
      }
      /*
      JSON.stringify = JSON.stringify || function (obj) {
        var t = typeof (obj);
        if (t != "object" || obj === null) {
            // simple data type
            if (t == "string") obj = '"'+obj+'"';
            return String(obj);
        }
        else {
            // recurse array or object
            var n, v, json = [], arr = (obj && obj.constructor == Array);
            for (n in obj) {
                v = obj[n]; t = typeof(v);
                if (t == "string") v = '"'+v+'"';
                else if (t == "object" && v !== null) v = JSON.stringify(v);
                json.push((arr ? "" : '"' + n + '":') + String(v));
            }
            return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
        }
      };
      */
      function add_floor() {
        if (floor_id != '') {
          $.ajax({
            type: "GET",
            url: "/_inc/configurator/product2json.php",
            data: "floor=" + floor_id,
            dataType: 'json',
            success: function (result) {
              if (result) {
                var floor_row = '<tr id="floor_row">'
                  floor_row += '<td>' + result.sku + '</td>'
                  floor_row += '<td>' + result.name + '</td>'
                  floor_row += '<td>' + price_display(result.price) + '</td>'
                  floor_row += '<td>1</td>'
                  floor_row += '<td>' + price_display(result.price) + '</td>'
                  floor_row += '<td><img class="delete_floor" src="/_template/images/cfg_icon_delete.jpg" /></td>'
                  floor_row += '</tr>';
                
                $('#mini_basket table thead').append(floor_row);
                
                floorbasketstr = floor_id + 'x0x0x0xN'
                
                $('#mini_basket #floor_item').append($('<input type="hidden" name="cfg[' + floorbasketstr + ']" value="1" />'));
                
                cfg.floor_price = result.price * 1;
                
                $('#cfg_price span').html(price_display(result.price));
              }
            }
          });
        }
      }
      
      function name2json(product_name) {
        
        product_name = product_name.replace(/\: /g, '":"')
        product_name = product_name.replace(/\, /g, '","')
        product_name = product_name.replace(/\mm/g, '')
        
        return $.parseJSON('{"' + product_name + '"}')
        
      }
      
      save = {
        save_to_db: function () {
          $.ajax({
            type: "POST",
            url: "/_inc/configurator/save.php",
            data: {
              category: cfg.van,
              data: cfg.data
            },
            dataType: 'json',
            success: function (result) {
              save.default_callback(result);
              save.callback(result);
              save.callback = function () {}
            }
          })
        },
        default_callback: function (result) {
          if (result && result.key) {
            $('#configurator_key').text(result.key);
          }
        },
        callback: function () {}
        
      };
      
      function build_settings(saved_data) {
        
        $.each(saved_data, function(i, v) {
          if (v.side == 'os') { cfg.os_depth = v.dimensions.D; }
          if (v.side == 'ns') { cfg.ns_depth = v.dimensions.D; }
        });
        
        if(cfg.ns_depth != "") {
          if (cfg.ns_depth == 455) {
            $('.ns.rail, .ns.obstruction').css('width', Math.round(cfg.rail_455_width) + 'px');
          } else {
            $('.ns.rail, .ns.obstruction').css('width', Math.round(cfg.rail_355_width) + 'px');
          }
        }
        
        if(cfg.os_depth != "") {
          if (cfg.os_depth == 455) {
            $('.os.rail, .os.obstruction').css('width', Math.round(cfg.rail_455_width) + 'px');
          } else {
            $('.os.rail, .os.obstruction').css('width', Math.round(cfg.rail_355_width) + 'px');
          }
        }
        
        update_size_selected();
        
        change_side('os');
        
      }
      
      function draw_floor_plan(saved_data) {
        
        var css_ns_depth = '50px';
        if (cfg.ns_depth == 355) {
          css_ns_depth = (cfg.rail_355_width - 3) + 'px';
        } else {
          css_ns_depth = (cfg.rail_455_width - 3) + 'px';
        }
        var css_os_depth = '50px';
        if (cfg.os_depth == 355) {
          css_os_depth = (cfg.rail_355_width - 3) + 'px';
        } else {
          css_os_depth = (cfg.rail_455_width - 3) + 'px';
        }
        
        $.each(saved_data, function(i, v) {
          
          if (v.side == 'os') {
            var css_rules = { position: 'absolute', left: 'auto', right: 0, top: v.pos + 'px', display: 'block', background: '#747578', width: css_os_depth }
          } else {
            var css_rules = { position: 'absolute', left: 0, right: 'auto', top: v.pos + 'px', display: 'block', background: '#747578', width: css_ns_depth }
          }
          
          var class_to_add = v.sku.split('-');
          
          var newDiv = $('<div class="product_helper ' + class_to_add[0] + ' floorplan_object ui-draggable"><div class="bolt bolt_1"></div><div class="bolt bolt_2"></div></div>')
            .attr('title', v.sku)
            .attr('id', v.iso_id)
            .css(css_rules);
          $("#floorplan_diagram_inner").append(newDiv);
          
        });
      }
      
      function basket_from_data(saved_data) {
        
        $.each(saved_data, function (i, v) {
          
          isFound = false;
          $.each(Basket, function () {
            if (this['sku'] == v.sku) {
              this['qty']++;
              isFound = true;
            }
          });
          if (!isFound) {
            row = {
              'sku' : v.sku,
              'details' : {
                'productid': v.productid,
                'optionid': v.optionid,
                'name': v.name,
                'price': v.price,
                'weight': v.weight
              },
              'qty' : 1
            };
            Basket.push(row);
          }
          
        });
        
      }
      
      function isometric_from_data(saved_data) {
        
        $.each(saved_data, function (i, v) {
          
          cfg.isometric.push({
            'iso_id': v.iso_id,
            'side': v.side,
            'sku': v.sku,
            'pos': v.pos,
            'productid': v.productid,
            'optionid': v.optionid,
            'name': v.name,
            'price': v.price,
            'weight': v.weight
          });
          
        });
        
      }
      
/** Load **********************************************************************/

      if (is_compatable()) {
        $('.nojs').hide();
        $('.js').show();
        $('#configurator_container').lightbox_me();
      } else {
        $('.touch_error').text('This configurator does not currently support your browser.');
      }
      
      /**
       * Configurator Object
       */
      function Configurator() {
        this.side = '';
        this.ns_depth = '';
        this.os_depth = '';
        
        this.product_id = 0;
        
        this.isometric = [];
        
        this.id = '';
        this.van = $('#category_id').text();
        this.data = [];
        
        this.van_length = $('#interior_length').text();
        if ($.browser.msie) {
          var tmp_van_width = document.getElementById('floorplan_diagram_inner').currentStyle.width;
          this.van_width = tmp_van_width.replace("px","");
        } else {
          this.van_width = $('#floorplan_diagram_inner').width();
        }
        
        this.interior_length = this.van_length;
        this.interior_width = $('#interior_width').text();
        
        this.rail_355_width = ((355 / this.interior_width) * this.van_width);
        this.rail_455_width = ((455 / this.interior_width) * this.van_width);
        
        if ($.browser.msie) {
          isometric_width = document.getElementById('configurator_right').currentStyle.width;
          isometric_width = isometric_width.replace("px","");
        } else {
          isometric_width = $('#isometric').width();
        }
        
        // This should use width but IE sucks... http://bugs.jquery.com/ticket/4464
        // isometric_image_width = $('#isometric img').attr('width');
        isometric_image_width = $('#isometric img').attr('alt');
        
        $('#isometric img').css({
          'width': isometric_width + 'px'
        });
        
        // hack
        $('#configurator_right').css({
          height: '640px'
        });

        this.isometric_width = isometric_width;
        this.isometric_ratio = isometric_width / isometric_image_width;
        
        this.floor_price = 0.00;
        
        $('#isometric_os .background').bind("load",function () {
          $('#cfg_warn').fadeOut();
        });
        
        $('#isometric_ns .background').bind("load",function () {
          $('#cfg_warn').fadeOut();
        });
        
      }
      Configurator.prototype.addProduct = function (product) {
        
        isFound = false;
        $.each(Basket, function () {
          if (this['sku'] == product.sku) {
            this['qty']++;
            isFound = true;
          }
        });
        if (!isFound) {
          row = {
            'sku' : product.sku,
            'details' : {
              'productid': product.productid,
              'optionid': product.optionid,
              'name': product.name,
              'price': product.price,
              'weight': product.weight
            },
            'qty' : 1
          };
          Basket.push(row);
        }
        
        updateBasket();
        
      }
      Configurator.prototype.removeProduct = function (item) {
        
        $.each(cfg.data, function (i,v){
          if (v.iso_id == $(item).attr('id')) {
            spliceid = i
          }
        })
        cfg.data.splice(spliceid,1);
        
        $.each(Basket, function (i,v) {
          
          if (item.attr('title') == this['sku']) {
            if (this['qty'] > 1) {
              this['qty']--;
            } else {
              Basket.splice(i,1);
            }
          }
          
        });
        
        updateBasket();
      }
      var cfg = new Configurator;
      change_side('os');
      
      function Product() {
        this.sku = '';
        this.productid = '';
        this.optionid = '';
        this.name = '';
        this.price = '';
      }
      var dragged = new Product;
      
      Basket = new Array;
      
      var floor_id = $('#floor_id').text();
      add_floor(floor_id);
      
      /*- Load from DB -*/
      if ($('#cfg_data').text().length > 0) {
        
        saved_config = $.parseJSON($('#cfg_data').text())
        
        cfg.data = saved_config;
        
        build_settings(saved_config);
        
        draw_floor_plan(saved_config);
        
        basket_from_data(saved_config);
        
        isometric_from_data(saved_config);
        
        updateBasket();
        
        redrawIsometric();
        
      }
      
      /*
      jQuery('#cfg_note')
        .hide()
        .ajaxStart(function () {
            jQuery(this).text('loading');
            jQuery(this).show(0);
            console.log('loading!', jQuery(this));
        })
        .ajaxStop(function () {
            jQuery(this).hide();
            console.log('done!');
        })
        */

/** Event Handlers ************************************************************/
      
      /**
       * Close Modal
       */
      $('.modal_close').click(function () {
        $('#configurator_container').trigger('close');
      });
      
      /**
       * User tries to delete floor
       */
      $('.delete_floor').live('click', function () {
        
        confirmed = confirm('Please note that this floor is a bespoke design to fit your vehicle and to make fitting time a lot quicker when installing your units.')
        
        if (confirmed) {
          
          $('#mini_basket #floor_row').remove();
          
          $('#floor_item input').remove();
          
          cfg.floor_price = 0.00;
          
          $('.floor_note').hide();
          
          updateBasket();
          
        }
      });
      
      /**
       * Hook up the re-launch button
       */
      $('.launch_configurator, .tab_configurator').click(function (e) {
        e.preventDefault();
        $('#configurator_container').lightbox_me();
      });
      
      /**
       * Stop other images being dragged
       */
      $( "#isometric img" ).liveDraggable({ disabled: true });
      
      /**
       * Hook to Buy this kit
       */
      $('#b_buy_this_kit').click(function () {
        if (Basket.length > 0) {
          // $('#mini_basket form').submit();
          $('#mini_basket').scrollTo();
        } else {
          show_error('There are no products in your basket');
        }
      });
      
      /**
       * Hook to change view
       */
      $('#b_change_view, #b_change_side').click(function () {
        if(cfg.side.length) {
          if (cfg.side == 'ns') {
            change_side('os');
          } else {
            change_side('ns');
          }
        } else {
          show_error('Please choose a side, under your floorplan first')
        }
      });
      
      /**
       * hook to view basket
       */
      $('#cfg_price p').click(function () {
        $('#mini_basket').scrollTo();
      });
      
      /**
       * event handler for hiding product more info when clicking away.
       *
      $('html').click(function (e) {
        if (!$(e.target).closest('.configurator_product').length) {
          $('.select_options').hide();
        }
      });
      */
      /**
       * controls for products in the product area
       * removed because position is buggy in IE
       * 
      $('.configurator_product').hover(function (e) {
        $(this).find('.title_window').toggle();
        $(this).find('.title_window').css('top', $(this).offset().top - 200).css('left', $(this).offset().left - 420);
      });
      */
      $('.configurator_product').click(function (e) {
        
        $('.select_options').hide();
        
        if (!$(e.target).closest('.close_options').length) {
          
          if(cfg.side == '') {
            show_error('Please choose a side to work on.')
            $('#configurator_container').scrollTo();
          } else {
            var depth_set = false;
            if (cfg.side == 'ns') {
              if (cfg.ns_depth != '') { depth_set = true; }
            } else {
              if (cfg.os_depth != '') { depth_set = true; }
            }
            if (depth_set) {
              $(this).find('.select_options').toggle();
              $('#configurator_container').scrollTo();
            } else {
              show_error('Please choose depth for ths side you are working on.')
              $('#configurator_container').scrollTo();
            }
          }
        }
      });
      
      /**
       * event handler for changing to working on ns
       */
      $('#b_ns').click(function (e) {
        e.preventDefault();
        change_side('ns');
      });
      
      /**
       * event handler for changing to working on os
       */
      $('#b_os').click(function (e) {
        e.preventDefault();
        change_side('os');
      });
      
      /**
       * Function for changing width of side
       */
      $('#b_355').click(function (e) {
        e.preventDefault();
        if(!$(this).hasClass('selected')) {
          if (cfg.side != '') {
            if(countItemsOnSide(cfg.side) == 0) {
              $(this).addClass('selected');
              $('#b_455').removeClass('selected');
              if (cfg.side == 'os') {
                cfg.os_depth = 355;
              } else {
                cfg.ns_depth = 355;
              }
              $('.' + cfg.side + '.rail, .' + cfg.side + '.obstruction').css('width', cfg.rail_355_width + 'px');
              $('.options_455').hide();
              $('.options_355').show();
            } else {
              show_error('You cannot change the wdth of a side once it has products on it.');
            }
          } else {
            show_error('Please choose a side to work on.');
          }
        }
        
      });
      
      /**
       * Function for changing width of side
       */
      $('#b_455').click(function (e) {
        e.preventDefault();
        if(!$(this).hasClass('selected')) {
          if (cfg.side != '') {
            if(countItemsOnSide(cfg.side) == 0) {
              $(this).addClass('selected');
              $('#b_355').removeClass('selected');
              if (cfg.side == 'os') {
                cfg.os_depth = 455;
              } else {
                cfg.ns_depth = 455;
              }
              $('.' + cfg.side + '.rail, .' + cfg.side + '.obstruction').css('width', cfg.rail_455_width + 'px');
              $('.options_355').hide();
              $('.options_455').show();
            } else {
              show_error('You cannot change the wdth of a side once it has products on it.');
            }
          } else {
            show_error('Please choose a side to work on.');
          }
        }
        
      });
      
      $(".option").hover(
        function() {
          $(this).css('border', '2px solid orange');
        },
        function() {
          $(this).css('border', '2px solid #CCCCCC');
        }
      );
      
      $(".select_options_inner .enlarge_image").click(function(e) {
        e.preventDefault();
        $('body').append('<div id="enlarged_image"><h2>&nbsp;</h2><p class="close_enlarge"><img alt="Close" src="/_template/images/cfg_close_options.jpg"></p><img src="' + $(this).attr('href') + '" />');
      });
      
      $('.close_enlarge').live('click', function(e) {
        $('#enlarged_image').remove();
      });
      
      function mySide(object) {
        var side = '';
        $(cfg.isometric).each(function (i,e) {
          if (e.iso_id == $(object).attr('id')) {
            side = e.side;
          }
        });
        return side;
      }
      
      $('.floorplan_object').live('mouseenter mouseleave', function (event) {
        if (event.type == 'mouseover') {
          $(this).append('<img src="/_template/images/cfg_delete_item.jpg" class="delete_item" class="delete_item" />');
        } else {
          $(this).find('img').remove();
        }
      });
      
      $('.delete_item').live('click', function (event) {
        
        var itemtoremoveid = $(this).parent().attr('id');
        
        cfg.removeProduct($(this).parent());
        cfg.isometric.each(function (v,i) {
          
          if (itemtoremoveid == v.iso_id) {
            spliceid = i;
          }
        });
        
        $(this).parent().remove()
        
        cfg.isometric.splice(spliceid,1);
        redrawIsometric();
      });
      
      $(".floorplan_object").liveDraggable({
        revert: 'invalid',
        start: function (e,u) {
          
          if (mySide($(this)) != cfg.side) {
            $(this).addClass('invalid');
          } else {
            $(this).addClass('valid');
          }
          
          $(this).css('background', 'none');
          
          $('#drop_delete').show()
        },
        drag: function (e,u) {
          $(this).removeClass('valid');
          
          if ($(u.helper.children('.bolt_1')).collidesWith(".arch").length > 0 || $(u.helper.children('.bolt_2')).collidesWith(".arch").length > 0) {
            show_note('The product is clashing with the wheel arch. Try to straddle the arch');
          } else {
            hide_note();
          }
          
          if ( // drop conditions!
            ( $(u.helper.children(".bolt_1")).collidesWith(".rail").length > 0 &&
              $(u.helper.children(".bolt_2")).collidesWith(".rail").length > 0
            ) &&
            ( $(u.helper.children(".bolt_1")).collidesWith(".arch").length == 0 &&
              $(u.helper.children(".bolt_2")).collidesWith(".arch").length == 0
            ) &&
            $(u.helper).collidesWith(".product_helper").length == 0 &&
            !$(this).hasClass('invalid')
            ) {
            $(this).addClass('valid');
          } else {
            $(this).removeClass('valid');
          }
        },
        stop: function () {
          $(this).css('background', '#747578');
          $('#drop_delete').hide();
          hide_note();
        }
      });
      
      $(".option").draggable({
        start: function (e,u) {
          dragged.sku = $(this).attr('alt');
          $(this).addClass('valid');
        },
        drag: function (e,u) {
          $(this).removeClass('valid');
          
          if ($(u.helper.children('.bolt_1')).collidesWith(".arch").length > 0 || $(u.helper.children('.bolt_2')).collidesWith(".arch").length > 0) {
            show_note('The product is clashing with the wheel arch. Try to straddle the arch');
          } else {
            hide_note();
          }
          
          if ( // drop conditions!
            ( $(u.helper.children(".bolt_1")).collidesWith(".rail").length > 0 &&
              $(u.helper.children(".bolt_2")).collidesWith(".rail").length > 0
            ) &&
            ( $(u.helper.children(".bolt_1")).collidesWith(".arch").length == 0 &&
              $(u.helper.children(".bolt_2")).collidesWith(".arch").length == 0
            ) &&
            $(u.helper).collidesWith(".product_helper").length == 0
            ) {
            $(this).addClass('valid');
          } else {
            $(this).removeClass('valid');
          }
        },
        helper: function (e,u) {
          if (cfg.side == 'os') {
            return $('<div class="product_helper ' + $(this).attr('alt').substring(0,$(this).attr('alt').indexOf("-")) + '"><div class="bolt bolt_1"></div><div class="bolt bolt_2"></div></div>');
          } else {
            return $('<div class="product_helper ' + $(this).attr('alt').substring(0,$(this).attr('alt').indexOf("-")) + '"><div class="bolt bolt_1"></div><div class="bolt bolt_2"></div></div>');
          }
          
        },
        appendTo: 'body',
        cursorAt: {
          top: 20,
          left: 20
        },
        stop: function () {
          hide_note();
        }
      });
      
      $("#floorplan_diagram_inner").droppable({
        accept: '.valid',
        drop: function (e,u) {
          
          var floorplan_diagram_top = $('#floorplan_diagram_inner').offset().top;
          
          var local_offset = u.offset.top - floorplan_diagram_top;
          
          var css_ns_depth = '50px';
          if (cfg.ns_depth == 355) {
            css_ns_depth = (cfg.rail_355_width - 3) + 'px';
          } else {
            css_ns_depth = (cfg.rail_455_width - 3) + 'px';
          }
          var css_os_depth = '50px';
          if (cfg.os_depth == 355) {
            css_os_depth = (cfg.rail_355_width - 3) + 'px';
          } else {
            css_os_depth = (cfg.rail_455_width - 3) + 'px';
          }
          
          if ($(u.draggable).is('img')) {
            // dropped an option for the first time
            if (cfg.side == 'os') {
              var css_rules = { position: 'absolute', left: 'auto', right: 0, top: local_offset, display: 'block', background: '#747578', width: css_os_depth }
            } else {
              var css_rules = { position: 'absolute', left: 0, right: 'auto', top: local_offset, display: 'block', background: '#747578', width: css_ns_depth }
            }
            var newDiv = $(u.helper).clone(false)
              .removeClass('ui-draggable-dragging')
              .addClass('floorplan_object')
              .addClass('ui-draggable')
              .attr('title', u.draggable.attr('alt'))
              .attr('id', 'floor_' + cfg.product_id)
              .css(css_rules);
            $(this).append(newDiv);
            
            $('.select_options').fadeOut();
            
            $.ajax({
              type: "GET",
              url: "/_inc/configurator/product2json.php",
              data: "option=" + dragged.sku,
              dataType: 'json',
              success: function (result) {
                hide_note();
                
                iso_id = 'floor_' + cfg.product_id;
                cfg.product_id++;
                
                dragged.productid = result.js_productid;
                dragged.optionid = result.js_optionid;
                dragged.name = result.name;
                dragged.price = result.price;
                dragged.weight = result.weight;
                
                cfg.data.push({
                  'iso_id': iso_id,
                  'side': cfg.side,
                  'sku': dragged.sku,
                  'pos': local_offset,
                  'productid': result.js_productid,
                  'optionid': result.js_optionid,
                  'name': result.name,
                  'price': result.price,
                  'weight': result.weight,
                  'dimensions': name2json(result.name)
                });
                
                cfg.addProduct(dragged);
                
                cfg.isometric.push({
                  'iso_id': iso_id,
                  'side': cfg.side,
                  'sku': dragged.sku,
                  'pos': local_offset,
                  'productid': result.js_productid,
                  'optionid': result.js_optionid,
                  'name': result.name,
                  'price': result.price,
                  'weight': result.weight
                });
                
                redrawIsometric();
                
              }
            });
            
          } else {
            // updating the position of an existing object
            if (cfg.side == 'os') {
              var css_rules = { position: 'absolute', left: 'auto', right: '0', top: local_offset, display: 'block', width: css_os_depth }
            } else {
              var css_rules = { position: 'absolute', left: '0', right: 'auto', top: local_offset, display: 'block', width: css_ns_depth }
            }
            $(u.draggable).css(css_rules);
            
            cfg.isometric.each(function (v,i) {
              if (v.iso_id == u.draggable.attr('id')) {
                v.pos = local_offset;
              }
            });
            
            cfg.data.each(function (v,i) {
              if (v.iso_id == u.draggable.attr('id')) {
                v.pos = local_offset;
              }
            });
            
            redrawIsometric();
            
          }
          
        }
      });
      
      $("#drop_delete").droppable({
        drop: function (e,u) {
          $(u.draggable).remove();
          $('#drop_delete').hide();
          cfg.removeProduct(u.draggable);
          cfg.isometric.each(function (v,i) {
            if (u.draggable.attr('id') == v.iso_id) {
              spliceid = i;
            }
          });
          cfg.isometric.splice(spliceid,1);
          cfg.data.each(function (v,i) {
            if (u.draggable.attr('id') == v.iso_id) {
              spliceid = i;
            }
          });
          cfg.data.splice(spliceid,1);
          redrawIsometric();
        }
      });
      
      $('.product_row').mouseover(function () {
        $(this).css({background: '#ccc'});
      });
      $('.product_row').mouseout(function () {
        $(this).css({background: 'inherit'});
      });
      
      $('#b_save').click(function () {
        
        save.callback = function () {
          window.location.href = '/user/my_account_overview.php';
        }
        save.save_to_db();
      });
      
      $('#b_email').click(function () {
        
        save.callback = function (result) {
          if (result) {
            window.location.href = '/pages/email_configuration.php?key=' + $('#configurator_key').text() + '&category=' + $('#category_id').text() + '&configuration=' + result.result;
          } else {
            show_error('Nothing to share, add products to your floorplan.');
          }
        }
        save.save_to_db();
      });
      
    }
  });
  

/** Plugins *******************************************************************/

  (function ($){
    /**
     * scrollTop
     * @returns {bool}
     */
    $.fn.scrollTo = function () {
      $('html, body').animate({
        scrollTop: $(this).offset().top
      },
      'fast');
      return true;
    };
    
    /**
     * livedraggable
     * @description allows objects created in the future to be dragged.
     */
    $.fn.liveDraggable = function (opts) {
      this.live("mouseover", function () {
        if (!$(this).data("init")) {
          return $(this).data("init", true).draggable(opts);
        } else {
          return $(this);
        }
      });
    };

    /**
     * collidesWith
     * @returns {int} number of items it colides with
     */
    $.fn.collidesWith = function (elements) {
      var rects = this;
      var checkWith = $(elements);
      var c = $([]);
      if (!rects || !checkWith) { return false; }
      
      rects.each(function () {
        var rect = $(this);
        // define minimum and maximum coordinates
        var rectOff = rect.offset();
        var rectMinX = rectOff.left;
        var rectMinY = rectOff.top;
        var rectMaxX = rectMinX + rect.outerWidth();
        var rectMaxY = rectMinY + rect.outerHeight();
        
        checkWith.not(rect).each(function () {
          var otherRect = $(this);
          var otherRectOff = otherRect.offset();
          var otherRectMinX = otherRectOff.left;
          var otherRectMinY = otherRectOff.top;
          var otherRectMaxX = otherRectMinX + otherRect.outerWidth();
          var otherRectMaxY = otherRectMinY + otherRect.outerHeight();
          
          // check for intersection
          if ( rectMinX >= otherRectMaxX ||
            rectMaxX <= otherRectMinX ||
            rectMinY >= otherRectMaxY ||
            rectMaxY <= otherRectMinY ) {
            return true; // no intersection, continue each-loop
          } else {
            // intersection found, add only once
            if(c.length == c.not(this).length) { c.push(this); }
          }
        });
      });
      // return collection
      return c;
    }
  })(jQuery);
})(jQuery);  
