

jQuery(function($) {

	var PAGESIZE = 8;
	$(document).ready(function() {

		//main nav - top of page
		$("ul#nav li").mouseenter(function() {
			$("ul#nav li").each(function() {
				$(this).removeClass('over');
			});
			$(this).addClass('over');
		});
		$("ul#nav li").mouseleave(function() {
			$("ul#nav li").each(function() {
				$(this).removeClass('over');
			});
			$("ul#nav li.current").addClass('over');
		});
		
		//sidebar nav - top level
		$("ul#sidenav  > li > a").mouseenter(function() {
		
			$("ul#sidenav  > li > a").each(function() {
				$(this).removeClass('over');
				$("ul#sidenav > li ul#subnav").removeClass('over');
			});
			$(this).addClass('over');
			$(this).parent().find("ul").addClass('over');
		});
		$("ul#sidenav  > li > a").mouseleave(function() {
			$(this).removeClass('over');
			$("ul#sidenav > li a.current").addClass('over');
			$("ul#sidenav > li a.section").addClass('over');
			$("ul#sidenav > li.section ul#subnav").addClass('over');
			$("ul#sidenav > li.current ul#subnav").addClass('over');
		});
		
		//sidebar subnav - 2nd level
		$("ul#subnav li").mouseenter(function() {
		
			$("ul#subnav li").each(function() {
				$(this).removeClass('over');
			});
			$(this).addClass('over');
		});
		$("ul#subnav li").mouseleave(function() {
			$("ul#subnav li").each(function() {
				$(this).removeClass('over');
			});
			
			$("ul#subnav li.current").addClass('over');
		});
		

		/* ------- ------------ ------- */
		/* ------- COMMENT FORM ------- */
		/* ------- ------------ ------- */
		var commentFormNameDefault = $("label[for='PageCommentInterface_Form_PostCommentForm_Name']").text();
		var commentFormUrlDefault = $("label[for='PageCommentInterface_Form_PostCommentForm_CommenterURL']").text();
		var commentFormMessageDefault = $("label[for='PageCommentInterface_Form_PostCommentForm_Comment']").text();
		$("input#PageCommentInterface_Form_PostCommentForm_Name").val(commentFormNameDefault);
		$("input#PageCommentInterface_Form_PostCommentForm_CommenterURL").val(commentFormUrlDefault);
		$("textarea#PageCommentInterface_Form_PostCommentForm_Comment").val(commentFormMessageDefault);
		
		//Comment Form
		$("input#PageCommentInterface_Form_PostCommentForm_Name").focus(function(){	
			if($(this).val()==commentFormNameDefault){
			   $(this).val("");
			}
		});
		$("input#PageCommentInterface_Form_PostCommentForm_Name").blur(function(){		
			if($(this).val()==""){
			   $(this).val(commentFormNameDefault);
			}
		});
		
		$("input#PageCommentInterface_Form_PostCommentForm_CommenterURL").focus(function(){
			if($(this).val()==commentFormUrlDefault){
			   $(this).val("");
			}
		});
		$("input#PageCommentInterface_Form_PostCommentForm_CommenterURL").blur(function(){
			if($(this).val()==""){
			   $(this).val(commentFormUrlDefault);
			}
		});
		

		$("textarea#PageCommentInterface_Form_PostCommentForm_Comment").focus(function(){
			if($('textarea#PageCommentInterface_Form_PostCommentForm_Comment').val()==commentFormMessageDefault){
			   $('textarea#PageCommentInterface_Form_PostCommentForm_Comment').val("");
			}
		});
		$("textarea#PageCommentInterface_Form_PostCommentForm_Comment").blur(function(){
			if($('textarea#PageCommentInterface_Form_PostCommentForm_Comment').val()==""){
			   $('textarea#PageCommentInterface_Form_PostCommentForm_Comment').val(commentFormMessageDefault);
			}
		});		
	
		/* ------- ------------ ------- */
		/* ------- CONTACT FORM ------- */
		/* ------- ------------ ------- */
		//get default text values
		var contactFormNameDefault = $("input#Form_ContactForm_Name").val();
		var contactFormAddressDefault = $("input#Form_ContactForm_Address").val();
		var contactFormCityPostCodeDefault = $("input#Form_ContactForm_CityPostCode").val();
		var contactFormMobileDefault = $("input#Form_ContactForm_Mobile").val();
		var contactFormEmailDefault = $("input#Form_ContactForm_Email").val();
		var contactFormMessageDefault = $("textarea#Form_ContactForm_Message").val();
		
		//clear/reset field values on focus/blur
		$("input#Form_ContactForm_Name").focus(function(){	if($(this).val()==contactFormNameDefault) $(this).val(""); });
		$("input#Form_ContactForm_Name").blur(function(){	if($(this).val()=="") $(this).val(contactFormNameDefault); });
		
		$("input#Form_ContactForm_Address").focus(function(){ if($(this).val()==contactFormAddressDefault) $(this).val(""); });
		$("input#Form_ContactForm_Address").blur(function(){	if($(this).val()=="") $(this).val(contactFormAddressDefault); });
		
		$("input#Form_ContactForm_CityPostCode").focus(function(){	if($(this).val()==contactFormCityPostCodeDefault) $(this).val(""); });
		$("input#Form_ContactForm_CityPostCode").blur(function(){	if($(this).val()=="") $(this).val(contactFormCityPostCodeDefault); });
		
		$("input#Form_ContactForm_Mobile").focus(function(){	if($(this).val()==contactFormMobileDefault) $(this).val(""); });
		$("input#Form_ContactForm_Mobile").blur(function(){	if($(this).val()=="") $(this).val(contactFormMobileDefault); });
		
		$("input#Form_ContactForm_Email").focus(function(){	if($(this).val()==contactFormEmailDefault) $(this).val(""); });
		$("input#Form_ContactForm_Email").blur(function(){	if($(this).val()=="") $(this).val(contactFormEmailDefault); });
		
		$("textarea#Form_ContactForm_Message").focus(function(){	if($(this).val()==contactFormMessageDefault) $(this).val(""); });
		$("textarea#Form_ContactForm_Message").blur(function(){	if($(this).val()=="") $(this).val(contactFormMessageDefault); });	
		
		/* ------------------------------------------------ */
		/* --------------- GALLERY FILTERS ---------------- */
		/* ------------------------------------------------ */
		
		//Set the correct gallery url (hack-ish?)
		var galleryUrl = 'galleri';
		if($('input#locale').val() == 'fr_FR')
			galleryUrl = 'galerie';	
		
		//gallery filters options changed
		$('input[name="filter_video"]').click(function() {
			
			var show_video = $('input[name="filter_video"]:checked').val() == 1 ? 1 : 0;
			var show_photo = $('input[name="filter_photo"]:checked').val() == 1 ? 1 : 0;
			var filter_tag = $('#filter_tag').val();

			window.location.replace($('base').attr('href') + galleryUrl + "?start=0&v="+ show_video +"&p=" + show_photo + "&t=" + filter_tag);

			//Get the list of images that match the filters
			/*$.ajax({
				type: 'post',
				url: $('base').attr('href') + 'galleri',
				dataType: 'json',
				data: { 
					action: "filter", 
					video: show_video,
					photo: show_photo,
					tag: filter_tag,
				},
				success: function(data) {
					console.log('we have succeeded');
					
					//Generate Pagination links
					//$('#pagination').html(GeneratePagination('kok', data, cost_tags[ui.value], kitchen_tags[$("#kok-style-slider").slider( "value" )]));
					
					//Generate the thubnails from the returned json data
					//$('ul#photos').html(GenerateThumbnails(data));						
					
					//Generate Pagination links
					GeneratePagination();
					
					//Check if no thumbs are visible
					//GalleryImagesHidden();

				},
				error: function(xhr, status, e) {
				  //alert(xhr + status + e)
				  console.log(xhr, status, e);
				}
			});	*/		
		});
		
		
		//gallery filters options changed
		$('input[name="filter_photo"]').change(function() {
			
			var show_video = $('input[name="filter_video"]:checked').val() == 1 ? 1 : 0;
			var show_photo = $('input[name="filter_photo"]:checked').val() == 1 ? 1 : 0;
			var filter_tag = $('#filter_tag').val();

			window.location.replace($('base').attr('href') + galleryUrl +  "?start=0&v="+ show_video +"&p=" + show_photo + "&t=" + filter_tag);		
		});
		
		//gallery filters options changed
		$('#filter_tag').change(function() {
			
			var show_video = $('input[name="filter_video"]:checked').val() == 1 ? 1 : 0;
			var show_photo = $('input[name="filter_photo"]:checked').val() == 1 ? 1 : 0;
			var filter_tag = $('#filter_tag').val();

			window.location.replace($('base').attr('href') + galleryUrl + "?start=0&v="+ show_video +"&p=" + show_photo + "&t=" + filter_tag);		
		});
		
		//Set slideshow link on gallery page to open first image
		$('#start_slideshow').click(function() {
		
			var fireOnThis = $('ul#photos li:first a')[0];
			if( document.createEvent ) {
			  var evObj = document.createEvent('MouseEvents');
			  evObj.initEvent( 'click', true, true );
			  fireOnThis.dispatchEvent( evObj );

			} else if( document.createEventObject ) {
			  var evObj = document.createEventObject();
			  fireOnThis.fireEvent( 'on' + 'click', evObj );
			}
	
			/*var a = $('ul#photos li:first a')[0];
			var e = document.createEvent('MouseEvents');
			e.initEvent( 'click', true, true );
			a.dispatchEvent(e);*/
			return false;
		});

		
		$('a.Floaty').Floaty({
           vWidth: 660,
           vHeight: 525,
           BgColor: '#CCC',
           vThumbVer: 3,
		   vThumbSize: "small",
           imgClose: $('base').attr('href') + 'themes/JaggedGray/images/close.png'
       });	
	   
	   
	   /* ------------------------------------------------------- */
	   /* ----------------------- DEALERS ----------------------- */
	   /* ------------------------------------------------------- */
	   
	   
		/*$("div.dealer").each(function() {
			var address = $(this).find("input[name='full_address']").val();
			mapAddress(address, $(this).find(".googlemap").get(0));	
		});*/
		
		//dealers accordion
		//$("#dealers_list").accordion();	
		if($('div#dealers').length != 0) {
		
			$('div.dealer .dealer_heading').click(function() {
				$(this).parent().toggleClass('current');
				
				//We need to reload the map each time its displayed, otherwise the map position within the frame is wrong
				if($(this).parent().hasClass('current')) {
					var address = $(this).parent().find("input[name='full_address']").val();
					mapAddress(address, $(this).parent().find(".googlemap").get(0));	
				}
			});	
			
			//fetch the default dealer google map
			var address = $('div.dealer.current').find("input[name='full_address']").val();
			mapAddress(address, $('div.dealer.current').find(".googlemap").get(0));	


			
			//clear/reset default field values on focus/blur
			var dealersSearchDefault = $("input#tb_dealers_search").val();
			$("input#tb_dealers_search").focus(function(){	if($(this).val()==dealersSearchDefault) $(this).val(""); });
			$("input#tb_dealers_search").blur(function(){	if($(this).val()=="") $(this).val(dealersSearchDefault); });

			$('input[name="tb_dealers_search"]').autocomplete({		
				source: function(request, response) {
					$.ajax({
						url: $('base').attr('href') + "dealers",
						data: { action: 'loc',  term: $('input[name="tb_dealers_search"]').val()},
						dataType: "json",
						type: "POST",
						success: function( data ) {
							if(data.items != null) {
								response( $.map( data.items, function( item ) {
									return {
										label: item.City,
										value: item.Value
									}
								}));
							}
							
							//Re-position city list slightly
							var position = $('ul.ui-autocomplete').position();
							$('ul.ui-autocomplete').css('top', position.top - 13);
							$('ul.ui-autocomplete').css('left', position.left + 11);
							$('ul.ui-autocomplete').css('width', $('ul.ui-autocomplete').width() - 40);
						}
					});
				},	
				minLength: 2,
				select: function( event, ui ) {
					if(ui.item) {
						if(ui.item.value != -1) {
							//set the link location so if they click add the right id is sent
							$('input[name="company_parent_id"]').val(ui.item.value);
							$('input[name="tb_dealers_search"]').autocomplete( "close" );
							//$('input[name="tb_dealers_search"]').val(ui.item.label);
							
							//Re-direct to filter dealers
							window.location.replace($('base').attr('href') + "dealers?cty="+ ui.item.value);
						}
						else {
							$('input[name="tb_dealers_search"]').autocomplete( "close" );					
						}
				
						return false;
					}
				}
			});	
			/*$("#imap_dealers area[title]").tooltip();
			$("[title]").tooltip();
			$('map[name="imap_dealers"] area').each(function() {
				$(this).tooltip();
			});*/
		}

	
		//Map tooltips - Use the each() method to gain access to each elements attributes
		$('area').each(function()
		{
			var dealertype = $(this).attr('class');
			var tooltipColor = (dealertype == 'Craftsman' ? '#17756f' : '#6e1717');
			$(this).qtip(
			{
				content: $(this).attr('tooltip'), // Use the tooltip attribute of the area map
				tip: true, 
				style: {
				   width: 200,
				   background: tooltipColor,
				   color: 'white',
				   textAlign: 'center',
				   border: {
					 width: 1,
					 radius: 4,
					 color: tooltipColor
				  },
				  tip: 'leftTop',
				  name: 'red' // Inherit the rest of the attributes from the preset dark style
			 }
			});
		});	
			
		//education page - selectlist changed
		$('#change_edupage').change(function() {
			window.location.replace($('base').attr('href') + $('#change_edupage').val());		
		});	
		
		//Ordered lists need a class for each item
		var count = 1;
		$('ol li').each(function() {
			$(this).addClass('ordered_element_' + count);
			count++;
		});
		
		//Rotate polaroid images slightly and reset their css styles
		/*$('.polaroid-thumbnail-1').each(function() {
			$(this).rotateRight(5);
		});
		$('.polaroid-thumbnail-2').each(function() {
			$(this).rotateLeft(2);
		});*/
		
		
		//$("#tabs").tabs();
		$("ul#tabs li").click(function() {
			
			$("ul#tabs li").each(function() { $(this).removeClass('current'); });
			$(this).addClass('current over');
			
			$("#file-list .tb_content .tabcontent").each(function() { $(this).removeClass('current');  });
			$("#file-list .tb_content #" + $(this).attr('alt')).addClass('current');
		});
		
		$("ul#tabs li").hover(function() {
			$("ul#tabs li").each(function() { $(this).removeClass('over'); });
			$(this).addClass('over');
		}, function() {
			$(this).removeClass('over');
			$("ul#tabs li.current").addClass('over');
		});
		
				
	}); //end document.ready


	function mapAddress(address, el) {
		var geocoder = new google.maps.Geocoder();
		geocoder.geocode( { 'address': address}, function(results, status) {
		  if (status == google.maps.GeocoderStatus.OK) {	
			
			gmap(el, results[0].geometry.location);
			//return results[0].geometry.location.Ba + ',' + results[0].geometry.location.za;
		  } else {
			//console.log("Geocode was not successful for the following reason: " + status);
			return false;
		  }
		});
	}
	
	function gmap(el, latlng) {
		var map;	
		var myOptions = {
		  zoom: 16,
		  center: latlng,
		  mapTypeId: google.maps.MapTypeId.ROADMAP
		}
		map = new google.maps.Map(el, myOptions);
		var marker = new google.maps.Marker({
			position: latlng, 
			map: map, 
			title:"Title required"
		});
	}
});
