$(document).ready(function() {
	
	Shadowbox.init();
	
	$('.show_shadowbox').bind('click', function(ev) { return false; });
	
	
	var timetable = $('#timetable');
	if(timetable.length) {
	
	   var valid_start, valid_end, mouse_down, new_start = false;
	   var valid_selection = true;
	   var start, end;
	   var s_index, o_index;
	   var i_start, i_target;
	   
	   var lis = timetable.find('li').not('.left_round, .right_round');
	   
	   $('.selected').live('mouseover', function(ev) {
	       $(this).trigger('showpopup');
	   });
	   
	   lis
	       .bind('dblclick', function(ev) {
	           
	           start = $(this).prevAll().each(function() {
	               if(!$(this).is('.reserved') && !$(this).is('.blocked') && !$(this).is('.right_round') && !$(this).is('.left_round')) {
	                   $(this).addClass('selected');
	               } else {
	                   return false;
	               }
	           });
	           
	           end = $(this).nextAll().each(function() {
	               if(!$(this).is('.reserved') && !$(this).is('.blocked') && !$(this).is('.right_round') && !$(this).is('.left_round')) {
	                   $(this).addClass('selected');
	               } else {
	                   return false;
	               }
	           });
	           
	           $('.selected:not(".left_round, .right_round")')
	               .attr('bt-xtitle', "Start: "+$('.selected:not(".left_round, .right_round"):first').attr('data-begins')+", Slutt:"+$('.selected:not(".left_round, .right_round"):last').attr('data-ends')+get_price())
	               .attr('title', "Start: "+$('.selected:not(".left_round, .right_round"):first').attr('data-begins')+", Slutt:"+$('.selected:not(".left_round, .right_round"):last').attr('data-ends')+get_price());
	               
	           $(ev.target).trigger('showpopup');
	               	           
	               append_form();
	               
	           if($('#iexplorer_order').length) {
    	           $('#iexplorer_order').html("Start: "+$('.selected:not(".left_round, .right_round"):first').attr('data-begins')+", Slutt:"+$('.selected:not(".left_round, .right_round"):last').attr('data-ends')+get_price());
    	       		  
    	       }
    
	                   	       
	       })
	       .bind('mousedown', function(ev) {
	           ev.preventDefault();
	           lis.removeClass('selected');
	           mouse_down = true;
	           
	           target = $(ev.currentTarget);

	           if(!target.hasClass('reserved') && !target.hasClass('blocked')) {
	               valid_start = valid_selection = true;
	               target.addClass('selected');
	               start = target;
	               
	               $(ev.target)
	                   .attr('bt-xtitle', "Start: "+$('.selected:first').attr('data-begins')+", Slutt:"+$('.selected:last').attr('data-ends')+get_price())
	                   .attr('title', "Start: "+$('.selected:first').attr('data-begins')+", Slutt:"+$('.selected:last').attr('data-ends')+get_price())
	                   .trigger('showpopup');
	               
	               if($('#iexplorer_order').length) {
    	           $('#iexplorer_order').html("Start: "+$('.selected:not(".left_round, .right_round"):first').attr('data-begins')+", Slutt:"+$('.selected:not(".left_round, .right_round"):last').attr('data-ends')+get_price());
    	       		  
    	           }

	                   
	           }
	           
	           
	           
	       })
	       .bind('mouseover', function(ev) {	                 
	           if(mouse_down && valid_start) {
	               if(!$(ev.target).hasClass('reserved')) {
	               
	                   if(new_start) {
	                       start = $(ev.target);
	                       new_start = false;
	                   }
	                   
	                   i_start = lis.index(start);
	                   i_target = lis.index($(ev.target));
	                   
	                   
	                   lis
	                       .removeClass('selected')
	                       .filter(function(index){
	                       if(i_start < i_target) {
            	                   return index >= i_start && index <= i_target;
    	                      } else {
    	                           return index <= i_start && index >= i_target;
    	                   }
	                       }).addClass('selected');        
	               } else {
	                   new_start = true;   
	               }
	               
	               $('.selected')
	                   .attr('bt-xtitle', "Start: "+$('.selected:first').attr('data-begins')+", Slutt:"+$('.selected:last').attr('data-ends')+get_price())
	                   .attr('title', "Start: "+$('.selected:first').attr('data-begins')+", Slutt:"+$('.selected:last').attr('data-ends')+get_price())
	               
	               if($('#iexplorer_order').length) {
    	           $('#iexplorer_order').html("Start: "+$('.selected:not(".left_round, .right_round"):first').attr('data-begins')+", Slutt:"+$('.selected:not(".left_round, .right_round"):last').attr('data-ends')+get_price());
    	       		  
        	       }

	               
	           }
	           
	           // ie fix
	           if($('#iexplorer_order').length && !$(this).hasClass('reserved') && !$(this).hasClass('selected')) {
	           	   $('#iexplorer_order').html('&nbsp;');   		  
	           }
	           
	           if($('#iexplorer_order').length && $(this).hasClass('selected')) {
	               $('#iexplorer_order').html("Start: "+$('.selected:not(".left_round, .right_round"):first').attr('data-begins')+", Slutt:"+$('.selected:not(".left_round, .right_round"):last').attr('data-ends')+get_price());
	           }
	           
	           
	       })
	       .bind('mouseup', function(ev) {
	           mouse_down = false;
	           end = $(ev.currentTarget);
	           
	           if(valid_start) {
	               var start_index = lis.index(start);
	               var end_index = lis.index(end);
	               
	               selection = lis.filter(function(index){
	                   if(start_index < end_index){
    	                   return index >= start_index && index <= end_index;
    	               } else {
    	                   return index <= start_index && index >= end_index;
    	               }
    	               
	               });
	               
	               selection.each(function() {
	                   if($(this).hasClass('reserved')) {
	                       $(this).removeClass('selected');
	                   } else {
	                       $(this).addClass('selected');    
	                   }
	               });
	               
	               if(!valid_selection) {    
	                   lis.removeClass('selected');
	                   valid_start = mouse_down = false;    
	               } else {
	                   append_form();
	               }
	               
	           }
	       }).bind('showpopup', function(ev) {
	           try {
	               $(ev.target).btOn();
	          } catch(err) {
	           // firefox throws exception..
	       }
	       }).bind('hidepopup', function(ev) {
	           try {
	               $(ev.target).btOff();
        	   } catch(err) {
	          // firefox throws exception...
	           }
	       });
	       
	       timetable.bind('mouseleave', function(ev) {
	           valid_start = mouse_down = false;
	       });
	       
	       
	       $.fn.valid_selection = function() {
	           var valid = true;
	           $(this).each(function() {
	               if(!$(this).hasClass('round_right, round_left, reserved')) {
	                   valid = false;
	               }
	           });
	           
	           return valid;
	       }
	       
	       function append_form() {
	           $('.hidden_slots, .ghost').remove();
	           
	           form = $('#reservation_form');
    	       selected = $('.selected');
	                   
	          var append_string = '';
	                   
	          selected.each(function(ev) {
	               append_string += '<input type="hidden" name="slot" class="hidden_slots" value="'+$(this).attr('data-slot')+'" />';
	          });
	                   
	          var ghost_left = selected.filter(':first').prev(':not(".left_round, .right_round, .selected")');
	          var ghost_right = selected.filter(':last').next(':not(".left_round, .right_round, .selected")');
	                   
	                   
	           if(ghost_left.length && !ghost_left.hasClass('reserved')) {
	               append_string += '<input type="hidden" name="ghost" class="ghost" value="'+ghost_left.attr('data-slot')+'" />';
	           }
	                  
	           if(ghost_right.length && !ghost_right.hasClass('reserved')) {
	               append_string += '<input type="hidden" name="ghost" class="ghost" value="'+ghost_right.attr('data-slot')+'" />';
	           }
	                   
	           form.append(append_string);
	       }
	       
	       function get_price() {
	         if($('#timetable').length && $('#timetable').attr('data-price') && $('.selected').length) {   
             var tp = $('#timetable').attr('data-price');
             var c = $('.selected').length;
             var price;
             
             if(c >= 2) {
               price = Math.round(tp * c - (tp * c * ((5.5 + c * 1.475) / 100)));
             } else {
               price = tp * c;
             }
              
              return '<br /><strong>Pris:</strong> kr. '+price;
           }
	       
	       }
	       
	}
	
	
	
	
	
	
	// end drag'n drop slots
	
	
	
var last_tooltip = {};

$('.show_tooltip').bt({
	    trigger: 'none',
	    fill: '#F7F7F7', 
        strokeStyle: '#B7B7B7',
        positions: 'top',
        spikeLength: 10, 
        spikeGirth: 10, 
        padding: 8,
        closeWhenOthersOpen: true,
        cornerRadius: 0, 
        cssStyles: {
            fontFamily: '"lucida grande",tahoma,verdana,arial,sans-serif', 
            fontSize: '11px'
        }
	});

	
	$('.static_tooltip').bt({
	    trigger: 'none',
	    fill: '#F7F7F7', 
        strokeStyle: '#B7B7B7',
        positions: 'top',
        spikeLength: 10, 
        spikeGirth: 10, 
        padding: 8,
        closeWhenOthersOpen: true,
        cornerRadius: 0, 
        cssStyles: {
            fontFamily: '"lucida grande",tahoma,verdana,arial,sans-serif', 
            fontSize: '11px'
        }
	});


	
	$('#timetable, #timetable-reception').bind('mouseover', function(ev) {
	   $this = $(ev.target);
	   $jthis = $(this);
	   
	   if($this.hasClass('show_tooltip')) {
	       var id = $this.attr('data-order');
	       if(id != last_tooltip.id && !$(ev.target).attr('bt-xtitle') || ( $('#iexplorer_order').length || $('.iexplorer_booking').length)) {
    	       $.ajax({
    	        	url: '/intra/moterom/ajax_tooltip',
    	         	type: 'get',
    	         	data: 'order='+id, 
    	         	dataType: 'html',
    	         	success: function(html) {
    	       		  $(ev.target).attr('bt-xtitle', html);
    	       		  //$(ev.target).attr('alt', html);
    	       		  last_tooltip = {id: id, html: html};
    	       		  $(ev.target).trigger('showpopup');
    	       		  
    	       		  if($('#iexplorer_order').length) {
    	       		      var h3 = $(html).find('h3').text();
    	       		      var room = $(html).find('.room').text();
    	       		      var time = $(html).find('.time').text();
    	       		      $('#iexplorer_order').html(h3+", "+room+", "+time);
    	       		  
    	       		  }
    	       		  
    	       		  if($('.iexplorer_booking').length) {
    	       		      var h3 = $(html).find('h3').text();
    	       		      var room = $(html).find('.room').text();
    	       		      var time = $(html).find('.time').text();
    	       		      
    	       		      $this.closest('.venue-box').find('.iexplorer_booking:first').html(h3+", "+room+", "+time);

    	       		  }
    	       		  
    	       		      	       		  
    	         	}
    	       });
    	   } else {
	           if(!$(ev.target).attr('bt-xtitle')) {
	               $(ev.target).attr('bt-xtitle', last_tooltip.html);
	           }
	           
	           $(ev.target).trigger('showpopup');
	       }
	   }
	}).bind('showpopup', function(ev) {
	   try {
	       $(ev.target).btOn();
	   } catch(err) {
	       // firefox throws exception..
	   }
	}).bind('mouseout', function(ev) {
	   try {
	       $(ev.target).btOff();
	   } catch(err) {
	       // firefox throws exception...
	   }
	   
	   if($('.iexplorer_booking').length) {
	       $('.iexplorer_booking').html('&nbsp;');
	   }
	});
	
	
	$('.datepicker').datepicker({
    	duration: '',
        showTime: true,
        constrainInput: false,
        time24h:true,
        dateFormat: 'dd.mm.yy',
		onClose:function(text, instance) {
		    var matches = text.match(/(\d{2})\.(\d{2})\.(\d{4}) (\d{2}):(\d{2})/);
		    text = matches[2]+'/'+matches[1]+'/'+matches[3]+' '+matches[4]+':'+matches[5];
			var d = new Date(text);
			$(this).next('.real_date').val(d.strftime('%Y-%m-%dT%H:%M:%S'));
		}
	
	});
	
	$('.datepicker_notime').datepicker({
    	duration: '',
        showTime: false,
        constrainInput: false,
        time24h:true,
        dateFormat: 'dd.mm.yy',
		onClose:function(text, instance) {	
			var matches = text.match(/(\d{2})\.(\d{2})\.(\d{4})/);
			var text = matches[2]+'/'+matches[1]+'/'+matches[3];
			var d = new Date(text);
			
			$(this).next('.real_date').val(d.strftime('%Y-%m-%d'));
		}
	
	});

	
	$('.jq_delivery').bind('change', function(ev) {
		if($(this).hasClass('jq_company_address')) {
			$('#jq_delivery').show();
		} else {
			$('#jq_delivery').hide();
		}
	});
	
	// editor
	$('.tinymce').tinymce({
			// Location of TinyMCE script
			script_url : '/static/js/tiny_mce/tiny_mce.js',

			// General options
			theme : "advanced",
			plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

			// Theme options
			theme_advanced_buttons1 : "bold,italic,underline,justifyright,formatselect, |, cleanup,removeformat, |, media,fullscreen",
			theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,undo,redo,|,link,unlink,anchor,image,cleanup, ",
			theme_advanced_buttons3: "",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location : "bottom",
			theme_advanced_resizing : true,

			// Example content CSS (should be your site CSS)
			content_css : "css/content.css",

			// Drop lists for link/image/media/template dialogs
			template_external_list_url : "lists/template_list.js",
			external_link_list_url : "lists/link_list.js",
			external_image_list_url : "lists/image_list.js",
			media_external_list_url : "lists/media_list.js"
		});
		
});
