if(!window.console) {
    window.console = {log : function(){}};
}

function to_px(val) {
    return(measurement_ratio*val);
}
function to_mm(val) {
  return(Math.round(val/measurement_ratio));
}

function set_element_properties(id, data) {
  $('#'+id).data('properties', data);
}



var planner = {
  base_url: "/planer-aplikacija/",
  
  create_door_sections: function(num, doors_sections) {
    $('.door_section').draggable('destroy');
    $('.door_section').remove();
    section_height = cabinet_height / num;
    $('.doors').each(function() {
      for (var i=0; i < num; i++) {
        $(this).append('<div class="door_section" style="height:'+to_px(section_height)+'px;"></div>');
      };
    });
    if (doors_sections != undefined) {
      ids = doors_sections.split(',');
      $('.door_section').each(function(i, door_section) {
        el = $('#pattern_'+ids[i]);
        if (el.length > 0) {
          planner.set_pattern_to_door_section(el, $(door_section));
        }
      });
    }
    $('.door_section').droppable({
      // accept: '.pattern',
    	hoverClass: 'ui-state-highlight',
    	drop: function(event, ui) {
        console.log('pattern dropped');
        planner.set_pattern_to_door_section(ui.draggable, $(this));
        $("#cabinet_inside").trigger('change');    
      }
    });
    $("#cabinet_inside").trigger('change');
  },
  
  set_pattern_to_door_section: function(element, door_section) {
    console.log(door_section, element);
    door_section.css('background', "url("+$('img', element).attr('src')+")");
    door_section.data('properties', {pattern_id: element.attr('id')});
  },
  
  planner_outside_setup: function(num, doors_sections) {
    $('.pattern').draggable({
      cancel: 'a.ui-icon',
        helper: 'clone',
        revert: 'invalid',
        containment: '#planner',
        zIndex: 10000,
        cursor: 'move',
        appendTo: 'body'
      });
      planner.create_door_sections(num, doors_sections);
      $('#planner_door_sections_num').change(function() {
        planner.create_door_sections($(this).val());
      });
  },  
  
  add_trash: function() {
    $('#cabinet_inside_outer').append('<div id="trash"><img src="/site_media/images/trash.png" alt="Smeće" /></div>');
    $("#trash").droppable({
        revert: 'invalid',
      	accept: '#cabinet_inside .element',
      	hoverClass: 'trash_accept',
      	tolerance: 'touch',
      	drop: function(event, ui) {
          ui.draggable.hide('scale', {percent: 0}, 250, function() {
            $(this).appendTo('#trash');
            $("#cabinet_inside").trigger('change');      
          });
        }
    });
  },
  
  draggable_options: {
    cancel: 'a.ui-icon',
    revert: 'invalid',
    containment: '#planner',
    zIndex: 10000,
    helper: 'original',
    cursor: 'move',
    snap: '.modul, .element',
    snapTolerance: 10,
    appendTo: 'body',
    helper: 'clone'
  },
  
  
  copy_properties: function(src, dst) {
      dst.data('properties', src.data('properties'));
  },
  
  vertical_span_value: function(vertical_span) {
    if (vertical_span) {
        return([1, to_px(vertical_span)]);
    } else {
        return(false);
    }
  },
  
  resize_element: function(element, original_element) {
    if (original_element == undefined) {
      original_element = element;
    }
    h = original_element.data('properties')['h'];
    w = original_element.data('properties')['w'];
    element.css({width:Math.round(to_px(modul_width)), height: to_px(h)});
    if (element.hasClass('centered')) {
      element.find('img').each(function(argument) {
        $(this).css({height:to_px(h)});
        orig_w = original_element.data('properties').element_type.image_width;
        orig_h = original_element.data('properties').element_type.image_height;
        render_w =  orig_w * to_px(h)/orig_h;
        $(this).css({width:render_w});
        lft = -(render_w - to_px(modul_width))/2
        $(this).css({left:lft});
      });
    } else if (element.hasClass('left_aligned')) {
      $('img', element).css({height:to_px(h)});
    }
  },
  
  make_element_draggable: function(element) {
    element.draggable($.extend({}, planner.draggable_options, {
        grid: planner.vertical_span_value(element.data('properties').element_type.vertical_span),
        start: function(ev, ui) {
          $(this).toggle();
        },
        stop: function(ev, ui) {
          $(this).toggle();
        }
    }));
  },
  
  add_element_to_modul: function(element, pos, modul) {
    console.log(element, pos, modul);
    if (element.data('in_modul')) {
        cloned_element = element;
    } else {
        cloned_element = element.clone();
    }
    // copy properties and set width and height
    if (!cloned_element.data('properties')) {
        this.copy_properties(element, cloned_element);
        this.resize_element(cloned_element);
    }
    // align left
    left_position = 0;
    // align element top and bottom
    top_position = Math.round(pos.top-modul.offset().top-to_px(chipboard_thickness));
    cloned_element.appendTo(modul).css({left:left_position, top:top_position});
    if (top_position < 0) {
        cloned_element.css('top', 0);
    } else if (top_position+cloned_element.height() > modul.height()) {
        cloned_element.css('top', modul.height()-cloned_element.height());
    }
    // TODO: if element overlaps other element in modul, try to add it before or after
    // TODO: span to grid
    
    // cloned_element.draggable($.extend({}, planner.draggable_options, {
    //     grid: this.vertical_span_value(cloned_element.data('properties')['vertical_span'])
    // }));
    planner.make_element_draggable(cloned_element);
    cloned_element.data('in_modul', true);
    console.log("before trigger", cloned_element.id);
    console.log(cloned_element.data('properties'));
    
    $("#cabinet_inside").trigger('change');
  },
  
  serialize: function() {
    console.log("serialize cabinet planner");
    var res = {}
    $('#cabinet_inside .modul').each(function(i, modul) {
      $(modul).find('.element').each(function(i2, element) {
        el = $(element);
        res['modul_set-'+i+'-element_set-'+i2+'-position_y'] = to_mm(parseFloat(el.css('top')));
        res['modul_set-'+i+'-element_set-'+i2+'-element_type_id'] = el.data('properties').element_type.id;
        res['modul_set-'+i+'-element_set-'+i2+'-height'] = el.data('properties').h;
      });
    });
    res['corpus_pattern'] = $('#corpus_pattern').val();
    res['handle'] = $('#handle').val();
    res['planner_door_sections_num'] = $('#planner_door_sections_num').val();
    // res['cabinet_backside'] = $('#cabinet_backside').val();
    var door_sections = [];
    $('.door_section').each(function(i, door_section) {
      el = $(door_section);
      door_sections.push(el.data('properties') ? el.data('properties').pattern_id.match(/\d+/)[0] : '0');
    });
    res['doors_sections'] = door_sections.join(',');
    console.log(res);
    return (res);
  },
  
  post_cabinnet: function() {
    $('#planner_price_loading').show();
    data = this.serialize();
    $.post(planner.base_url + 'update', data, function (resp, textStatus) {
      $('#price').html(resp);
      $('#planner_price_loading').hide();
    });
  },
  
  planner_inside_setup: function() {
    planner.add_trash();
    $("#cabinet_inside .modul").droppable({
      	accept: '.element',
      	hoverClass: 'ui-state-highlight',
      	drop: function(event, ui) {
            planner.add_element_to_modul(ui.draggable, ui.offset, $(this));
        }
    });
    $("#planner_element_types .element").draggable($.extend({}, planner.draggable_options, {
        start: function(ev, ui) {
          original_element = $('#'+ui.helper.attr('id'));
          $(this).draggable('option', 'grid', planner.vertical_span_value(original_element.data('properties').element_type.vertical_span));
          planner.resize_element(ui.helper, original_element);
        }
    }));
    $("#cabinet_inside .element").each(function() {
      planner.make_element_draggable($(this));
    })
    
    $("#cabinet_inside").bind('change', function(e) { 
      planner.post_cabinnet();
    });
    
    
  },
  
  selectmenu_format: function(text) {
    var newText = text.replace(/^img:([^ ]+) /, '<img src="$1" alt="" />');
    return newText;
	}
  
};

$(function() {  
  
  $('#planner_commit_commit').click(function(argument) {
    $('#planner_commit_commit').attr('disabled', 'disabled')
    $('#planner_commit_loading').show();
    data = planner.serialize();
    console.log(data);
    $.post(planner.base_url + 'update', data, function (resp, textStatus) {
      console.log(resp);
      window.location = planner.base_url + "make_quote";
      $('#planner_commit_commit').attr('disabled', '')
    });
  });
  
  // tabs
  $("#tabs").tabs({
  });
  
  // price info
  $('#price_info').appendTo($('#tabs .ui-tabs-nav'))

	$('.ui-button').hover(
		function(){ 
			$(this).addClass("ui-state-hover"); 
		},
		function(){ 
			$(this).removeClass("ui-state-hover"); 
		}
	).mousedown(function(){
		$(this).addClass("ui-state-active"); 
	})
	.mouseup(function(){
			$(this).removeClass("ui-state-active");
	});
  
  
  
  $('#corpus_pattern').selectmenu({
		style:'dropdown',
    menuWidth: 545,
		maxHeight: 200,
		width: 545,
		format: planner.selectmenu_format
	}).change(function() {
	 $("#cabinet_inside").trigger('change');
	});
  $('#cabinet_backside').selectmenu({
		style:'dropdown',
    menuWidth: 545,
		maxHeight: 200,
		width: 545
	}).change(function() {
	 $("#cabinet_inside").trigger('change');
	});
  $('#handle').selectmenu({
		style:'dropdown',
    menuWidth: 385,
		maxHeight: 300,
		width: 385,
		format: planner.selectmenu_format
	}).change(function() {
	 $("#cabinet_inside").trigger('change');
	});
  $('#planner_door_sections_num').selectmenu({
		style:'dropdown',
    menuWidth: 385,
		maxHeight: 300,
		width: 385,
		format: planner.selectmenu_format
	});
	
	$('#id_cabinet_type option').each(function() {
	  el=$(this); 
	  el.html('img:/site_media/images/' + el.attr('value') +'.gif '+ el.html()); 
  });
	$('#id_cabinet_type').selectmenu({
    menuWidth: 400,
		width: 400,
		style:'dropdown',
		format: planner.selectmenu_format
  });

  $("a.lightbox").fancybox({ 'zoomSpeedIn': 250, 'zoomSpeedOut': 250,'overlayOpacity':0.5, 'overlayShow': true, 'padding':0 }); 
  
	$("#help-dialog").dialog({
    bgiframe: true,
		modal: true,
		width: 460,
		height: 600,
		buttons: {
			"Zatvori": function() {
				$(this).dialog('close');
			}
		}
	});
	$('#help-dialog-link').click(function(argument) {
    $("#help-dialog").dialog('open');
  });
});


