
jQuery(function($) {
    var blank = new Image();
    blank.src = jQuery('base').attr('href') + 'themes/ekebybruk/images/spacer.gif';
	var KITCHEN = 0;
	var BATHROOM = 1;
	var STORAGE = 2;
	var UTESPA = 3;
	var PAGESIZE = 9;
	var bookingCategory;
	var selRowId;
	var selStaffRowId;
	
	var kitchen_tags = Array();
	kitchen_tags[0]="";
	kitchen_tags[1]="Lantligt";
	kitchen_tags[2]="Klassiskt";
	kitchen_tags[3]="Modernt";
	
	var cost_tags = Array();
	cost_tags[0]="";
	cost_tags[1]="Låg";
	cost_tags[2]="Mellan";
	cost_tags[3]="Hög";
	
	var bathroom_tags = Array ('Badkar', 'Duschar', 'Kranar', 'Porslin', 'Kakel', 'Möbler', 'Bastu', 'Ekebys handgjorda kakel' );
     
    $(document).ready(function() {
        var badBrowser = (/MSIE ((5\.5)|6)/.test(navigator.userAgent) && navigator.platform == "Win32");
        if (badBrowser) {
            // get all pngs on page
            $('img[src$=.png]').each(function() {
               if (!this.complete) {
                  this.onload = function() { fixPng(this) };
               } else {
                  fixPng(this);
               }
            });
        }
        
        $("#nav img").mouseenter(function() {
            var src = $(this).attr('src');
            src = src.replace('\-normal','\-over');
            $(this).attr('src',src);

        });
		
        $("#nav a.link img").mouseleave(function() {
            var src = $(this).attr('src');
            src = src.replace('\-over','\-normal');
            $(this).attr('src',src);
			
			var src = $("#nav a.current img").attr('src');
            src = src.replace('\-normal','\-over');

        });


        // frog
        $("#frog").flash(
            {
                swf: jQuery('base').attr('href') + 'themes/ekebybruk/flash/groda_ekeby.swf',
				width: 150,
                params: {
                    wmode: 'transparent'


                }
                
            }
        );
        // frog meditation
        $("#frog-meditation").flash(
            {
                swf: jQuery('base').attr('href') + 'themes/ekebybruk/flash/groda_meditation.swf',
				width: 300,
				height: 200,
                params: {
                    wmode: 'transparent'
                }
                
            }
        );
        // frog king
        $("#frog-king").flash(
            {
                swf: jQuery('base').attr('href') + 'themes/ekebybruk/flash/groda_king.swf',
				width: 250,
                params: {
                    wmode: 'transparent'
                }
                
            }
        );
        // frog tittut
        $("#frog-tittut").flash(
            {
                swf: jQuery('base').attr('href') + 'themes/ekebybruk/flash/groda_tittut.swf',
				width: 250,
                params: {
                    wmode: 'transparent'
                }
                
            }
        );

		
		//Initialise the banner slideshow	
		$("#slides").sfSlideShow(
			{
				controlPanel: 0,
				speed: 5000,
				fadeDuration: 'slow',
				//width:960,
				//height:421
				height:376,
				width:899,
				playstop: 1
			}
		); 

		//Inspiration list
		$("#inspiration-add").click(function() {		
		
			//Set a cookie to show they have clicked this so they don't need the popup help
			$.cookie('EkebyPopupHelp', 1, { expires: 24, path: '/' });			
			$('#inspiration-add-popup').hide();
			AddToInspirationList();
		});
		$("#banner-inspiration #options .delete").click(function() {
			$("#inspiration-list ul li").remove();
			$.cookie('EkebyInspirationList', null, { expires: -1, path: '/' });	
			$("#inspiration-list").hide();
			$("#inspiration-content #default-content").show();	
			
		});
		$("#banner-inspiration #options .send").click(function() {
		
			//$("#inspiration-list").hide();
			$("#email-inspiration").show();	
		});
		

		$("#banner-inspiration #options #sendlist").click(SendInspirationList);
		BuildInspirationList();
		
		//Booking Category Choice click
		$("#booking-cat-kitchen").click(function() {
		
			$("#booking-cat-kitchen").css('font-weight', 'bold');
			$("#booking-cat-bathroom").css('font-weight', 'normal');
			$("#booking-cat-storage").css('font-weight', 'normal');
			$("#booking-cat-utespa").css('font-weight', 'normal');
			BookingStep1(KITCHEN);
			return false;
		});
		$("#booking-cat-bathroom").click(function() {
			$("#booking-cat-kitchen").css('font-weight', 'normal');
			$("#booking-cat-bathroom").css('font-weight', 'bold');
			$("#booking-cat-storage").css('font-weight', 'normal');
			$("#booking-cat-utespa").css('font-weight', 'normal');
			BookingStep1(BATHROOM);
			return false;
		});
		$("#booking-cat-storage").click(function() {
		
			$("#booking-cat-kitchen").css('font-weight', 'normal');
			$("#booking-cat-bathroom").css('font-weight', 'normal');
			$("#booking-cat-storage").css('font-weight', 'bold');
			$("#booking-cat-utespa").css('font-weight', 'normal');
			BookingStep1(STORAGE);
			return false;
		});
		$("#booking-cat-utespa").click(function() {
			$("#booking-cat-kitchen").css('font-weight', 'normal');
			$("#booking-cat-bathroom").css('font-weight', 'normal');
			$("#booking-cat-storage").css('font-weight', 'normal');
			$("#booking-cat-utespa").css('font-weight', 'bold');
			BookingStep1(UTESPA);
			return false;
		});
		
		//Initialse grid object without the url - this will be set when a date is selected
		jQuery("#bookingslots").jqGrid({ 
			datatype: "json", 
			colNames:['Personal', 'Datum', 'Tid'], 
			colModel:[ {name:'StaffMember',index:'StaffMember', sortable:false}, 
						{name:'BookingDate',index:'BookingDate', sortable:false}, 
						{name:'BookingTime',index:'BookingTime', sortable:false}					
			], 
			rowNum:8, 
			pager: '#bookingslots-pager', 
			sortname: 'id', 
			viewrecords: true, 
			sortorder: "desc", 
			loadonce: false, 
			caption: 'Välj ett alternativ', 
			sortable:false,
			pgbuttons:true,
			pginput:true,
			viewrecords:false,
			width:330,
			height:'auto',
			forceFit:true,
			scroll:false,
			scrollOffset:0,
			onSelectRow: function(id){ 
			  if(id){ 
					$('#booking-slots-grid').show();
					selRowId = id;
					$('#nextpage1').show();
			  } 
		   }


		}); 
		
		//Initialise the staff grid
		//Note: initialise the grid without the url - the grid will be populated when the user chooses from bathroom, kitchen, etc
		jQuery("#staffgrid").jqGrid({ 
			datatype: "json", 
			colNames:['Personal'], 
			colModel:[ {name:'StaffMember',index:'StaffMember', sortable:false}
			], 
			rowNum:8, 
			sortname: 'id', 
			viewrecords: true, 
			sortorder: "desc", 
			loadonce: false, 
			caption: 'Välj personal', 
			sortable:false,
			pgbuttons:false,
			pginput:false,
			viewrecords:false,
			width:330,
			height:'auto',
			forceFit:true,
			scroll:false,
			scrollOffset:0,
			onSelectRow: function(id){ 
				if(id){ 
					selStaffRowId = id;
					var selDate = $('#datepicker').val();
					
					//If there is a selected date then just reload the booking slots grid
					if(selDate.length > 0) {
						
						$("#bookingslots").setGridParam({
							type: 'POST',
							url:'home/boka-tid',
							postData:{ 
								action: 'get_booking_slots',
								dt: formatDate($("#datepicker").datepicker("getDate")),
								cat: bookingCategory,
								staff: selStaffRowId
							}
						}).trigger('reloadGrid');
						$('#nextpage1').hide();
					}
					else {
						//show the date selector
						//$("#datepicker").datepicker( "show" );
						$('#choose-booking-date').show();
						$("#datepicker").focus();
					}
				} 
		   }


		}); 		
		
		$("#datepicker").datepicker( {
			onSelect: function(dateText, inst) { 
				$('#booking-slots-grid').show();

				$("#bookingslots").setGridParam({
					type: 'POST',
					url:'home/boka-tid', /*?action=get_booking_slots&dt=' + formatDate($("#datepicker").datepicker("getDate")) +
						'&cat=' + bookingCategory,*/
					postData:{ 
						action: 'get_booking_slots',
						dt: formatDate($("#datepicker").datepicker("getDate")),
						cat: bookingCategory,
						staff: selStaffRowId
					}
				}).trigger('reloadGrid');
				$('#nextpage1').hide();
			},
			dateFormat: 'yy-mm-dd'
		});
		//$("#datepicker").datepicker($.datepicker.regional['sv']);
		
		$('#prevday').click(function() {		
			var dt = $("#datepicker").datepicker("getDate");
			dt.setDate(dt.getDate() - 1);
			$("#datepicker").datepicker("setDate", dt);
			
			$("#bookingslots").setGridParam({
				url:'home/boka-tid',
				postData:{ 
					action: 'get_booking_slots',
					dt: formatDate($("#datepicker").datepicker("getDate")),
					cat: bookingCategory						
				}
			}).trigger('reloadGrid');
			$('#nextpage1').hide();
			return false;
		});
		$('#nextday').click(function() {		
			var dt = $("#datepicker").datepicker("getDate");
			dt.setDate(dt.getDate() + 1);
			$("#datepicker").datepicker("setDate", dt);
			$("#bookingslots").setGridParam({
				url:'home/boka-tid',
				postData:{ 
					action: 'get_booking_slots',
					dt: formatDate($("#datepicker").datepicker("getDate")),
					cat: bookingCategory						
				}

			}).trigger('reloadGrid');
			$('#nextpage1').hide();
			return false;
		});
		//Previous Page buttons
		$('#prevpage1').click(function() {	
			$("#booking-start").show();
			$("#BookingForm").hide();
			$('#nextpage1').hide();
			return false;
		
		});
		$('#prevpage2').click(function() {	
			$("#booking-step1").show();
			$("#booking-step2").hide();
			$("#booking-step3").hide();
			return false;		
		});
		$('#prevpage3').click(function() {	
			$("#booking-step1").hide();
			$("#booking-step2").show();
			$("#booking-step3").hide();
			$("#BookingError").hide();
			return false;		
		});
		
		//Next page buttons
		$('#nextpage1').click(function() {	
			$("#booking-step1").hide();
			$("#booking-step2").show();
			return false;		
		});
			
		$("#Form_BookingForm").validate({
			submitHandler: function(form) {
				$("#booking-step1").hide();
				$("#booking-step2").hide();
				$("#booking-step3").show();
				$("#CustomerName").text($("#Form_BookingForm input[name=FirstName]").val() + " " + 
											$("#Form_BookingForm input[name=LastName]").val());
				$("#CustomerAddress").text($("#Form_BookingForm input[name=StreetAddress]").val() + ", " + 
											$('#Form_BookingForm input[name=PostCode]').val() + " " + 
											$('#Form_BookingForm input[name=City]').val() );
				$("#CustomerTelephone1").text($('#Form_BookingForm input[name=Phone1]').val());
				$("#CustomerTelephone2").text($('#Form_BookingForm input[name=Phone2]').val());
				$("#CustomerEmail").text($('#Form_BookingForm input[name=Email]').val());
				$("#booking-conf-date").text(formatDate($("#datepicker").datepicker("getDate")));
				$("#booking-conf-staffmember").text($('#bookingslots').getCell(selRowId, 'StaffMember'));
				//form.submit();
				
				return false;
			 }
		});
		
		$("#BookingConfirm").click(ConfirmBooking);
		
		var defaultKokStyle;		
		if($.inArray($(document).getUrlParam("s"), kitchen_tags))
			defaultKokStyle = $.inArray($(document).getUrlParam("s"), kitchen_tags); 
		else
			defaultKokStyle = 0;
		
		$("#kok-style-slider").slider({ 
			step: 1, 
			min: 0, max: 3,
			value: defaultKokStyle,
			change: function(event, ui) {	

				//Set a cookie to remember their selection
				$.cookie('EkebyKokStyle', ui.value, { expires: 0.5, path: '/' });	

				//Get the list of images that match the filters
				$.ajax({
					url: $('base').attr('href') + 'home/kok',
					dataType: 'json',
					data: { action: "filter", s: kitchen_tags[ui.value], c: cost_tags[$("#kok-cost-slider").slider( "value" )] },
					success: function(data) {
						//Generate the thubnails from the returned json data
						$('ul#photos').html(GenerateThumbnails(data));						
						
						//Generate Pagination links
						$('#pagination').html(GeneratePagination('kok', data, cost_tags[$("#kok-cost-slider").slider( "value" )], kitchen_tags[ui.value]));
						
						//Check if no thumbs are visible
						GalleryImagesHidden();

					},
					error: function(xhr, status, e) {
					  //alert(xhr + status + e)
					  console.log(xhr, status, e);
					}
				});	
			
				/*$('ul#photos li').each(function(){
					var val = $(this).find('.thumbnail').attr('tags');
					
					var tags = val.split(",");
					if(ui.value == 0 || $.inArray(kitchen_tags[ui.value], tags) != -1) { 
					
						//Now check the cost slider has the required cost
						var costSliderVal = $("#kok-cost-slider").slider( "value" );
						var costTags = $(this).find('.thumbnail').attr('cost');
						costTags = costTags.split(",");
						
						console.log('SliderVal: ' + costSliderVal + ';' + cost_tags[costSliderVal]);
						console.log('costTags: ' + costTags);
						console.log('InArray: ' + $.inArray(cost_tags[costSliderVal], costTags));
						
						if(costSliderVal == 0 || $.inArray(cost_tags[costSliderVal], costTags) != -1) // val == costSliderVal) 
							$(this).show();	
						else
							$(this).hide();
					}
					else 
						$(this).hide();					
				});
				
				GalleryImagesHidden();*/
			}
		});
			
		var kokCost = decodeURIComponent( $(document).getUrlParam("c") );	
		var defaultKokCost;		
		if($.inArray(kokCost, cost_tags))
			defaultKokCost = $.inArray(kokCost, cost_tags); 
		else
			defaultKokCost = 0;
		
		$("#kok-cost-slider").slider({ 
			step: 1, 
			min: 0, max: 3,
			value: defaultKokCost,
			change: function(event, ui) {
			
				//Set a cookie to remember their selection
				$.cookie('EkebyKokCost', ui.value, { expires: 0.5, path: '/' });			

				//Get the list of images that match the filters
				$.ajax({
					url: $('base').attr('href') + 'home/kok',
					dataType: 'json',
					data: { action: "filter", s: kitchen_tags[$("#kok-style-slider").slider( "value" )], c: cost_tags[ui.value] },
					success: function(data) {
						
						//Generate the thubnails from the returned json data
						$('ul#photos').html(GenerateThumbnails(data));						
						
						//Generate Pagination links
						$('#pagination').html(GeneratePagination('kok', data, cost_tags[ui.value], kitchen_tags[$("#kok-style-slider").slider( "value" )]));
						
						//Check if no thumbs are visible
						GalleryImagesHidden();

					},
					error: function(xhr, status, e) {
					  //alert(xhr + status + e)
					  console.log(xhr, status, e);
					}
				});			
			
				/*$('ul#photos li').each(function(){
					//console.log('Val:' + val + '; UI Val: ' + ui.value);
					var val = $(this).find('.thumbnail').attr('cost');
					costTags = val.split(",");
					if(ui.value == 0 || $.inArray(cost_tags[ui.value], costTags) != -1) {
						
						//Now check if it has the required style tag
						var styleSliderVal = $("#kok-style-slider").slider( "value" );
						var imgTags = $(this).find('.thumbnail').attr('tags');
						
						var tags = imgTags.split(",");
						if(styleSliderVal == 0 || $.inArray(kitchen_tags[styleSliderVal], tags) != -1) 
							$(this).show();
						else {
							$(this).hide();	
							//console.log('Style slider: ' + styleSliderVal);
							//console.log('Style text: ' + kitchen_tags[styleSliderVal]);
							//console.log('Tags: ' + tags[0]);
							//console.log('In array: ' + $.inArray(kitchen_tags[styleSliderVal], tags));
						}
					}	
					else {
						$(this).hide();
					}	
				});
				
				GalleryImagesHidden();*/
				
			} 
		});
		
			
		var badCost = decodeURIComponent( $(document).getUrlParam("c") );	
		var defaultBadCost;		
		if($.inArray(badCost, cost_tags))
			defaultBadCost = $.inArray(badCost, cost_tags); 
		else
			defaultBadCost = 0;
			
		$("#bad-cost-slider").slider({ 
			step: 1, 
			min: 0, max: 3,
			value: defaultBadCost,
			change: function(event, ui) {
			
				//Set a cookie to remember their selection
				$.cookie('EkebyBadCost', ui.value, { expires: 0.5, path: '/' });
			
				var checkedTags = '';
				$("#bad-style-filter input:checked").each( function() {
					checkedTags += $(this).val() + ',';
					checkedTags = checkedTags.substring(0, checkedTags.length-1);
				});
			
				//Get the list of images that match the filters
				$.ajax({
					url: $('base').attr('href') + 'home/bad',
					dataType: 'json',
					data: { action: "filter", s: checkedTags, c: cost_tags[ui.value] },
					success: function(data) {
						
						//Generate the thubnails from the returned json data
						$('ul#photos').html(GenerateThumbnails(data));
						
						
						//Generate Pagination links
						$('#pagination').html(GeneratePagination('bad', data, cost_tags[ui.value], checkedTags));
						
						//Check if no thumbs are visible
						GalleryImagesHidden();

					},
					error: function(xhr, status, e) {
					  //alert(xhr + status + e)
					  console.log(xhr, status, e);
					}
				});
			
				/*$('ul#photos li').each(function(){
					var val = $(this).find('.thumbnail').attr('cost');
					costTags = val.split(",");
					if(ui.value == 0 || $.inArray(cost_tags[ui.value], costTags) != -1) { //val == ui.value) {
						
						//Now check if it has the required style tag
						var checkedTags = Array();
						$("#bad-style-filter input:checked").each( function() {
							checkedTags.push($(this).val());
						});
						
						var imgTags = $(this).find('.thumbnail').attr('tags');							
						imgTags = imgTags.split(",");
						
						var showImage = false;
						for(var i = 0; i < imgTags.length; i++) {
							//console.log('Tag:' + imgTags[i]);
							if($.inArray(imgTags[i], checkedTags) != -1) {
								showImage = true;
								break;
							}
						}
						if(showImage)
							$(this).show();			
						else
							$(this).hide();	
					}	
					else {
						$(this).hide();
					}	
					//count++;
				});*/
			} 
		});	


		var badStyle = decodeURIComponent( $(document).getUrlParam("s") );	
		
		styleTags = badStyle.split(",");
		$("#bad-style-filter input").each( function() {
			if($.inArray( $(this).val(), styleTags) != -1)
				$(this).attr('checked', 'checked');
		});	
		
		
		var defaultBadCost;		
		if($.inArray(badCost, cost_tags))
			defaultBadCost = $.inArray(badCost, cost_tags); 
		else
			defaultBadCost = 0;		
		
		$("#bad-style-filter input:checkbox").click(function() {
			var checkedTags = '';
			$("#bad-style-filter input:checked").each( function() {
				checkedTags += $(this).val() + ',';
			});
			//Remove trailing comma
			checkedTags = checkedTags.substring(0, checkedTags.length-1);
			//console.log('checkedTags:' + checkedTags);
			
		
			//Set a cookie to remember their selection
			$.cookie('EkebyBadStyle', checkedTags, { expires: 0.5, path: '/' });
				
			//Get the list of images that match the filters
			$.ajax({
				url: $('base').attr('href') + 'home/bad',
				dataType: 'json',
				data: { action: "filter", s: checkedTags, c: cost_tags[$("#bad-cost-slider").slider( "value" )] },
				success: function(data) {
					
					//Generate the thubnails from the returned json data´
					$('ul#photos').html(GenerateThumbnails(data));
									
					//Generate Pagination links
					$('#pagination').html(GeneratePagination('bad', data, cost_tags[$("#bad-cost-slider").slider( "value" )], checkedTags));
					
					//Check if no thumbs are visible
					GalleryImagesHidden();

				},
				error: function(xhr, status, e) {
				  //alert(xhr + status + e)
				  console.log(xhr, status, e);
				}
			});
			
			/*$('ul#photos li').each(function(){
				var imgTags = $(this).find('.thumbnail').attr('tags');							
				imgTags = imgTags.split(",");
				
				var showImage = false;
				for(var i = 0; i < imgTags.length; i++) {
					//console.log('Tag:' + imgTags[i]);
					if($.inArray(imgTags[i], checkedTags) != -1) {
						showImage = true;
						break;
					}
				}
				
				if(showImage) {
					//Now check the cost slider has the required cost
					var costSliderVal = $("#bad-cost-slider").slider( "value" );
					var val = $(this).find('.thumbnail').attr('cost');
					costTags = val.split(",");
					if(costSliderVal == 0 || $.inArray(cost_tags[costSliderVal], costTags) != -1) 
						$(this).show();	
					else
						$(this).hide();				
				}			
				else
					$(this).hide();		
			});
			GalleryImagesHidden();*/
		});
		
		
		$("#gallery .lnk-inspiration").each(function() {
			$(this).click(function(){
				AddToInspirationList($(this).attr("number"));
			});

		});
		$('#inspiration-add-popup').click(function(){
			
			//Set a cookie to show they have clicked this so they don't need the popup help
			$.cookie('EkebyPopupHelp', 1, { expires: 24, path: '/' });		
			$('#inspiration-add-popup').hide();
		});
		
		
		//This button is only to be shown in the galleries, not the inspiration list gallery
		//if ( $("#inspiration_gallery").length <= 0 ) {
		//	$('#lightboxInspirationAdd').show();
			//$("#lightboxInspirationAdd").click(function() {
			//	console.log('Done:' + $('#lightboxImage').attr("alt"));
			//	AddToInspirationList($('#lightboxImage').attr("alt"))
			//});
		//}
		//else {
			//console.log('Not Done:' + $('#lightboxImage').attr("alt"));
		//}
		
		
		var cookie = $.cookie('EkebyPopupHelp');
		if(cookie == null)
			$('#inspiration-add-popup').show();
		else
			$('#inspiration-add-popup').hide();
			
		//Play Stop Buttons	
		$('.sfSlideShow .playstop div.rwd').hover(function() {
			$(this).toggleClass('over');
		});	
		$('.sfSlideShow .playstop div.pause').hover(function() {
			$(this).toggleClass('over');
		});	
		$('.sfSlideShow .playstop div.play').hover(function() {
			$(this).toggleClass('over');
		});	
		$('.sfSlideShow .playstop div.fwd').hover(function() {
			$(this).toggleClass('over');
		});		
		
		//Slides list - set display to list-item
		/*$('ul#slides li').each(function() {
			$(this).css('display', 'list-item');
		});*/
		/*$('ul#slides li img').each(function() {
			$(this).load(function() {
				$('ul#slides li').each(function() {
					console.log('hello');
					$(this).parent().css('display', 'list-item');
				});
			});
		});*/
		//$('ul#slides li:first').find('img').css('width', '100px');
		$('#firstslide').load(function() {
			//console.log('hello');
			$('ul#slides li').each(function() {
				$(this).css('display', 'list-item');
			});
		});

		
		//Dialog window to show user how to add to inspiration list
		// increase the default animation speed to exaggerate the effect
		/*$.fx.speeds._default = 1000;
			$( "#dialog" ).dialog({
				autoOpen: true,
				show: "blind",
				hide: "explode",
				draggable: false,
				resizable: false,
				position: [1160,100], 
				height: 100,
				width: 150
			});
		

		$('#inspiration-add').qtip({
		   content: "Click here to add to your inspiration list!", // Set the tooltip content to the current corner
		   position: {
			  corner: {
				 tooltip: "leftBottom", // Use the corner...
				 target: "topRight" // ...and opposite corner
			  }
		   },
		   show: {
			  when: true, // Don't specify a show event
			  ready: true // Show the tooltip when ready
		   },
		   hide: {
				when: { event: 'click' }
		   },
		   style: {
			  border: {
				 width: 5,
				 radius: 10
			  },
			  padding: 10, 
			  width: 150,
			  textAlign: 'center',
			  tip: true, // Give it a speech bubble tip with automatic corner detection
			  name: 'cream' // Style it according to the preset 'cream' style
		   }
		});
		$('div.qtip').click(function() {
			$('div.qtip').hide();
		});*/

		
		gmap();
		
		//Suppliers re-directs on dropdown selected
		$('#supplier_list').change(function() {	
			window.location.replace(jQuery('base').attr('href') + "home/leverantorer?id=" + $('#supplier_list').val() + '#content');
		});
		$('#supplier_categories').change(function() {
			window.location.replace(jQuery('base').attr('href') + "home/leverantorer?cat=" + $('#supplier_categories').val() + '#content');
		});
		if($('#_supplier_id').val() != "")
			$('#supplier_list').val($('#_supplier_id').val());
		if($('#_supplier_cat').val() != "")
			$('#supplier_categories').val($('#_supplier_cat').val());
		

	});

	function gmap() {
		if(jQuery("#googlemap").length) {
			var latlng = new google.maps.LatLng(59.848649,17.607248);
			var myOptions = {
				zoom: 16,
				center: latlng,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			};

			map = new google.maps.Map(document.getElementById("googlemap"), myOptions);
			var marker = new google.maps.Marker({
				position: latlng, 
				map: map, 
				title:"Ekeby Bad & Kök, Ekebyvägen 10, Uppsala, Sverige "
			});
		}
	}

	function formatDate(dateObj) {
		return dateObj.getFullYear() + "-" 
				+ (dateObj.getMonth()+1) + "-" 
				+ dateObj.getDate();	
	}
	
	function BookingStep1(selBookingCategory) {
		/*var KITCHEN = 0;
		var BATHROOM = 1;
		var STORAGE = 2;
		var UTESPA = 3;*/
		switch(selBookingCategory) {
			case 0:
				$('#booking-step1-heading').text('Boka tid för köksplanering');
				break;
			case 1:
				$('#booking-step1-heading').text('Boka tid för badrumsplanering');
				break;
			case 2:
				$('#booking-step1-heading').text('Boka tid för förvaringsplanering');
				break;
			case 3:
				$('#booking-step1-heading').text('Boka tid för planering av utespa');
				break;
					
		}
		bookingCategory = selBookingCategory;
		
		
		$("#staffgrid").setGridParam({
			type: 'POST',
			url:'home/boka-tid',
			postData:{ 
				action: 'get_staff',
				cat: bookingCategory						
			}
		}).trigger('reloadGrid');
		
		//Hide other sections of form
		$("#booking-start").hide();
		$("#booking-step2").hide();
		$("#booking-step3").hide();
		$("#booking-step4").hide();
		$("#choose-booking-date").hide();
		$('#booking-slots-grid').hide();
		$('#datepicker').datepicker("setDate",null);
		
		
		//Show necessary elements of form
		$("#BookingForm").show();
		$("#booking-step1").show();
	}
	
	
	/*function GetBookingSlots(date){
		jQuery.ajax({
			type: "GET",
			url: jQuery('base').attr('href') + "home/boka-tid",
			data: 	"action=get_booking_slots&dt=" + date,
			success: function(html){
				
				//alert(html);
			}
		});
	}*/



	/*
	* Add an image id to the inspiration list in the banner and update the cookie contents
	*/
	function AddToInspirationList(imageId) {
		var cookie = $.cookie('EkebyInspirationList');
		var EkebyInspirationList;
		if( cookie == null)  EkebyInspirationList = new Array();
		else EkebyInspirationList = $.cookie('EkebyInspirationList').split(",");
		
		//Find the id of the current top image if the parameter is not an integer
		if(imageId == null || imageId.toString().search(/^[0-9]+$/) != 0){	
			var zIndex = 0;
			$("ul#slides li").each(function(){
				if(parseInt($(this).css('z-index')) > zIndex) {
					zIndex = parseInt($(this).css('z-index'));
					//console.log('Inside zIndex: ' + zIndex);
					imageId =$(this).find('img').attr('alt');
				}
			});
		}
		 
		//check if the item is already in the inspiration list
		if($.inArray(imageId, EkebyInspirationList) == -1) {
			//Add to the inspiration banner
			if(imageId != "") {
				$("#inspiration-list ul").append(
					"<li>" + "Bild nr " + imageId + "</li>"
				);
			}	
			$("#inspiration-content #default-content").hide();
			$("#inspiration-list").show();
			
			//Add to the cookie
			EkebyInspirationList.push(imageId);
			$.cookie('EkebyInspirationList', EkebyInspirationList, { expires: 7, path: '/' });	
		}

	}
	
	/*
	* Build the inspiration list in the banner from the cookie contents
	*/
	function BuildInspirationList() {
		var cookie = $.cookie('EkebyInspirationList');
		if( cookie != null) { 
			var EkebyInspirationList = $.cookie('EkebyInspirationList').split(",");
			EkebyInspirationList.forEach(function(element, index, array) {
				$("#inspiration-list ul").append(
					"<li>" + "Bild nr " + element + "</li>"
				);
			});
			$("#inspiration-list").show();
			$("#inspiration-content #default-content").hide();
		}
		else {
			$("#inspiration-list").hide();
			$('#email-inspiration-error').hide();
			$("#inspiration-content #default-content").show();		
		}
	}
	
	function SendInspirationList() {
			
		$.ajax({
			type: 'POST',
			url: jQuery('base').attr('href') + "home/boka-tid",
			/*data: 	"action=send_inspiration" +
				"&mail_list=" + $("#email-inspiration input[name=email]").val() +
				"&img_list=" + $.cookie('EkebyInspirationList'),*/
			//dataType : 'html',
			data : { 
				action: 'send_inspiration', 
				mail_list: $("#email-inspiration input[name=email]").val(),
				img_list: $.cookie('EkebyInspirationList')	
			},
			success: function (response) {
				if(response == 1) {
					$('#email-inspiration-sent').show();
					$('#email-inspiration').hide();
				}
				else {
					$('#email-inspiration-error').text(response);
					$('#email-inspiration-error').show();
					$('#email-inspiration').hide();
				}
				
			},	
			complete: function () {

			},	
			error: function(xhr, status, e) {
				$('#email-inspiration-error').show();
				$('#email-inspiration').hide();
			  //alert(xhr + status + e)
			  //console.log(xhr, status, e);
			}			
		});

		return false;	
	}
	
	function ConfirmBooking(){
		//alert('here');
		jQuery.ajax({
			type: "POST",
			url: jQuery('base').attr('href') + "home/boka-tid",
			data : { 
				action: 'book_slot', 
				id: selRowId,
				fn: $("#Form_BookingForm input[name=FirstName]").val(),
				ln: $("#Form_BookingForm input[name=LastName]").val(),
				st: $("#Form_BookingForm input[name=StreetAddress]").val(),
				pc: $("#Form_BookingForm input[name=PostCode]").val(),
				cty: $("#Form_BookingForm input[name=City]").val(),
				ph1: $("#Form_BookingForm input[name=Phone1]").val(),
				ph2: $("#Form_BookingForm input[name=Phone2]").val(),
				em: $("#Form_BookingForm input[name=Email]").val(),
				notes: $('#freetext').val(),
				sms: $("#booking-step3 input[name=SendSMS]").is(':checked'),
				email: $("#booking-step3 input[name=SendEmail]").is(':checked'),
				img_list: $.cookie('EkebyInspirationList')	
				
			},
			/*data: 	"action=book_slot&id="+ selRowId +
				"&fn=" + $("#Form_BookingForm input[name=FirstName]").val() +
				"&ln=" + $("#Form_BookingForm input[name=LastName]").val() +
				"&st=" + $("#Form_BookingForm input[name=StreetAddress]").val() +
				"&pc=" + $("#Form_BookingForm input[name=PostCode]").val() +
				"&cty=" + $("#Form_BookingForm input[name=City]").val() +
				"&ph1=" + $("#Form_BookingForm input[name=Phone1]").val() +
				"&ph2=" + $("#Form_BookingForm input[name=Phone2]").val() +
				"&em=" + $("#Form_BookingForm input[name=Email]").val() +
				"&notes=" + $('#freetext').val() +
				"&sms=" + $("#booking-step3 input[name=SendSMS]").is(':checked') +
				"&email=" + $("#booking-step3 input[name=SendEmail]").is(':checked'),*/
			success: function(response){
				//alert(response);
				if(response.indexOf('Error') != -1) {
					$("#BookingError").show();
					$("#BookingError").text(response);
				}
				else {
					$("#booking-step3").hide();						
					$("#booking-step4").show();
				}
			},
			error : function(response) {
				alert('error' + response);
			}
		});		
	}
	
	function GalleryImagesHidden() {

		//Check if all items have been hidden
		var allhidden = true;
		$('ul#photos li').each(function(){
			if($(this).css('display') != 'none') {
				allhidden = false;
			}
		});
		
		if(allhidden) {
			$('div#noimages').show();
			$('div#pagination').hide();
		}
		else {
			$('div#pagination').show();
			$('div#noimages').hide();	
		}
	}
	
	function GenerateThumbnails(data) {

		var listHtml = '';
		var countItems = data.count > PAGESIZE ? PAGESIZE : data.count;
		
		//Create thumbnails for the first 9 images
		for(var i = 0; i < countItems; i++) {
			listHtml += '' +  
'<li>' + 
	'<div class="frame">' + 
		'<div>&nbsp;</div>' + 
		'<img class="thumbnail fimg" src="' + $('base').attr('href') + data.items[i].Filename + '" alt="' + data.items[i].Number + '"  />' + 
		'<a class="lnk-lightbox" rel="lightbox[fullsize]" href="' + $('base').attr('href') + data.items[i].FullsizeImageUrl + '" title="' + data.items[i].Description + '" name="' + data.items[i].Number + '">' + 
			'<img src="' + $('base').attr('href') + 'themes/ekebybruk/images/spacer.gif" />' + 
		'</a>' + 
		'<a class="lnk-inspiration" number="' + data.items[i].Number + '" href="javascript:void(0)">' + 
			'<img src="' + $('base').attr('href') + 'themes/ekebybruk/images/spacer.gif" />' + 
		'</a>' + 
	'</div>		' + 
'</li>';
						
		}
		return listHtml;		
	}
	
	function GeneratePagination(page, data, costTags, styleTags) {

		var pagesHtml = '';
		var pages = Math.ceil(data.count/PAGESIZE);
		if(pages > 1) {
			
			pagesHtml += '<p>';
			/*if(data.current_page > 1) {
			
				previousPageLink = $('base').attr('href') +'home/'+page+'/?start='+ (data.current_page - 2) * PAGESIZE + 
					'&c=' + costTags + '&s=' + styleTags;
				pagesHtml += '<a href="' + previousPageLink + '">&laquo; Före</a>&nbsp;';
			}*/
			for(var x = 1; x <= pages; x++) {
				if(x == 1) pagesHtml += '&nbsp;<strong>'+x+'</strong>';
				else {
					pageLink = $('base').attr('href') +'home/'+page+'/?start=' + ((x-1)*PAGESIZE) 
						+ '&c=' + costTags
						+ '&s=' + styleTags;
					pagesHtml += '&nbsp;<a href="'+pageLink+'" title="Sida '+x+'">'+x+'</a>';
				}
			}
			//if(data.current_page != pages) {
			nextPageLink = $('base').attr('href') +'home/'+page+'/?start='+ PAGESIZE + 
				'&c=' + costTags + '&s=' + styleTags;
		
			pagesHtml += '&nbsp;<a href="'+ nextPageLink + '">Nästa &raquo;</a> ';
			//}						
		}
		return pagesHtml;
	}


	//https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/forEach
	//forEach is a recent addition to the ECMA-262 standard; as such it may not be present in all browsers. You can work around this by
	//inserting the following code at the beginning of your scripts, allowing use of forEach in implementations which do not natively 
	//support it. This algorithm is exactly the one used in Firefox and SpiderMonkey.
	if (!Array.prototype.forEach)
	{
	  Array.prototype.forEach = function(fun /*, thisp*/)
	  {
		var len = this.length >>> 0;
		if (typeof fun != "function")
		  throw new TypeError();

		var thisp = arguments[1];
		for (var i = 0; i < len; i++)
		{
		  if (i in this)
			fun.call(thisp, this[i], i, this);
		}
	  };
	}

     
    function fixPng(png) {
        // get src
        var src = png.src;
        // set width and height
        if (!png.style.width) { png.style.width = $(png).width(); }
        if (!png.style.height) { png.style.height = $(png).height(); }
        // replace by blank image
        png.onload = function() { };
        png.src = blank.src;
        // set filter (display original image)
        png.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
    }

});

