$(document).ready(function(){
	/*
	$(".overzicht_thumbs").hover(function() {
		//clearTimeout(tt);
		mouseOutImg($('.overzicht_thumbs'));
		var index = $(this).index('.overzicht_thumbs');
		tt=setTimeout('mouseOverImg(\''+index+'\');', 500);
	}, function() {
		clearTimeout(tt);
		mouseOutImg($(this));
	});
	*/
	
	$("a[rel='external']").click(function(){
	  this.target = "_blank";
	});
	
	$("#SearchZipcode").click(function(){
		if($(this).val()=='Zoeken op postcode'){
			$(this).val('');
		}
	});
	
	$("#SearchZipcode").blur(function(){
		if($(this).val()==''){
			$(this).val('Zoeken op postcode');
		}
	});
	
	$('#content_center form div.input input, #content_center form div.input textarea, .nieuwsbrief_input').focus(function(){
		$(this).addClass('focus');
	});
	$('#content_center form div.input input, #content_center form div.input textarea, .nieuwsbrief_input').blur(function(){
		$(this).removeClass('focus');
	});
	$('.nieuwsbrief_input').focus(function(){
		$(this).select();
	});
	
	if ($('#CustomerWebsite').val()=='') {
		$('#CustomerWebsite').val('http://');
	}
	
	$('#NewsitemDate, #NewsitemEnddate').datePicker({
		clickInput:true
	});
	
	$('#ReservationEndPeriod, #ReservationStartPeriod').datePicker({
		clickInput:true
	});
	$('#ReservationEndPeriod, #ReservationStartPeriod').dpSetRenderCallback(function($td, thisDate, month, year)
	{
		
		// disabled sunday
		if (thisDate.getDay() == 0) {
			var d = thisDate.getDate();
			$td.addClass('disabled');
		}
		// message at saturday
		if (thisDate.getDay() == 6) {
			var d = thisDate.getDate();
			$td.bind(
				'click',
				function()
				{
					setFlash('Let op! Wij zijn elke zaterdag tot 12.30 uur open.<br />Bezorgen of retour halen is helaas niet mogelijk op zaterdag.');
				}
			);
		}
	});
	
	var day_dif = 0;
	
	$('#ReservationStartPeriod').bind(
		'dpClosed',
		function(e, selectedDates)
		{
			var d = selectedDates[0];
			if (d) {
				d = new Date(d);
				// set start date
				$('#ReservationEndPeriod').dpSetStartDate(d.addDays(0).asString());
				// shift end date if isset
				newdate = adddays(d, day_dif);
				day = newdate.getDate();
				month = newdate.getMonth()+1;
				year = newdate.getFullYear();
				$('#ReservationEndPeriod').val(day+"/"+month+"/"+year);
				
				if (newdate.getDay() == 6) {
					setFlash('Let op! Wij zijn elke zaterdag tot 12.30 uur open.<br />Bezorgen of retour halen is helaas niet mogelijk op zaterdag.');
				}
			}
		}
	);
	$('#ReservationEndPeriod').bind(
		'dpClosed',
		function(e, selectedDates)
		{
			start = $('#ReservationStartPeriod').val().split('/');
			startdate = start[2]+'-'+start[1]+'-'+start[0];
			startdate = new Date(startdate);
			
			end = $('#ReservationEndPeriod').val().split('/');
			enddate = end[2]+'-'+end[1]+'-'+end[0];
			enddate = new Date(enddate);
			
			day_dif = days_between(startdate, enddate);
			
			/*
			var d = selectedDates[0];
			if (d) {
				d = new Date(d);
				$('#ReservationStartPeriod').dpSetEndDate(d.addDays(0).asString());
			}
			*/
		}
	);
	
	
	$('input[name=\'data[Reservation][delivery]\']').click(function(){
		if ($(this).val()==1) {
			$('#delivery_box').show();
		}
		else{
			$('#delivery_box').hide();
		}
	});
	
	checkBlockType();
	$('select[name=\'data[Block][boxtype]\']').change(function(){
		checkBlockType();
	});
	
	dropdownActions();
	toggleNews();
	toggleFaqs();
	toggleFaqView();
	toggleAvailableBranches();
	

	
//	googleGeoCode('edisonweg 1d, ijsselstein, nederland');

	
	$("#checkcoords").click(function(){		
		address = $("#BranchCheckStreetname").val()+' '+$("#BranchCheckNumber").val()+', '+$("#BranchCheckCity").val()+', Nederland';
		
		geocoder = new google.maps.Geocoder();
		geocoder.geocode( { 'address': address}, function(results, status){
			if(status == google.maps.GeocoderStatus.OK){
				$("#checkcoords_result").html('<p><strong>Adres gevonden:</strong> '+results[0].formatted_address+'</p>');
				$("#BranchLatlon").val(results[0].geometry.location);
				$("#savecoords_form").slideDown();
			}
			else{
				$("#checkcoords_result").html('<p><strong>Adres niet gevonden.</strong> Controleer de straatnaam en wijzig eventueel het nummer als het gaat om een reeks.<br />Bijvoorbeeld Teststraat 15-17, wijzigen naar Teststraat 15. Nog geen correct resultaat? Laat het huisnummer leeg.</p>');
			}
		});
		
		return false;
	});
	
	
//branches/mapzipcode	
	$("#SearchMapnewForm .submit input, #SearchMapnewFormCity .submit input").click(function(){
		//alert($(this).parent().parent().attr('id'));
		centlatlng = new google.maps.LatLng(52.132633, 5.291266);
		map.setCenter(centlatlng);
		
		map.setZoom(7);
		
		googleClearMarkers();
		
		//search on city name
		if($(this).parents('form').filter(':first').attr('id')=='SearchMapnewFormCity'){
			var address = $("#SearchCity").val();
			
			dataString = 'data[Search][city]='+address;
			action = webroot+'branches/findinradius';
			
			$.ajax({
				type: "POST",
				url: action,
				data: dataString,
				success: function(msg) {
					$("#markerselector").html(msg);
				},
				timeout: function(msg) {
					alert(msg);
				},
				error: function(xhr, ajaxOptions, thrownError) {
					alert(xhr.responseText);
				}
			});
			
			
		}
		//search on postalcode (latlon)
		else{
			var address = $("#SearchZipcode").val();
			radius = $('#SearchRadius').val();
			
			
			geocoder = new google.maps.Geocoder();
		

			geocoder.geocode( { 'address': address}, function(results, status){
				if (address.length !==6) {
					$("#markerselector").html('Vul een postcode in als 1234AB.');	
				}
				else if(status == google.maps.GeocoderStatus.OK){
					latlon = results[0].geometry.location;
					
					dataString = 'data[Coordinates][lat]='+results[0].geometry.location.lat()+'&data[Coordinates][lng]='+results[0].geometry.location.lng()+'&data[Coordinates][radius]='+radius;
	
					action = webroot+'branches/findinradius';
	
					//alert(latlon.toSource());
					//console.debug(latlon);
					
					$.ajax({
						type: "POST",
						url: action,
						data: dataString,
						success: function(msg) {
							$("#markerselector").html(msg);		      
						}
					});
	
				}
				else{
					$("#markerselector").html('Postcode onjuist.');	
				}
			});
			
		}
		
		
		
		
		return false;
	});
	
});

function setFlash(msg) {
	$('#flashMessage').remove();
	$('#container-center').before('<div id="flashMessage" class="message" style="display:none">'+msg+'</div>');
	$('#flashMessage').slideDown('fast');
}
function hideFlash() {
	$('#flashMessage').slideUp('fast');
}

function googleInit(){
	//declare infowindow object	for googlemaps
	infowindow = new google.maps.InfoWindow();
}

function googleGeoCode(address){
	geocoder = new google.maps.Geocoder();
	geocoder.geocode( { 'address': address}, function(results, status){
		if(status == google.maps.GeocoderStatus.OK){
			//alert(results[0].geometry.location);
			//googlePlaceMarker(name,results[0].geometry.location,popuptext);
			return results[0].geometry.location;
		}
		else{
			return 'error';
		}
	});
}

var markersArray = [];
function googlePlaceMarker(name,lat,lon,popuptext){
	
	var marker = new google.maps.Marker({
        map: map, 
        position: new google.maps.LatLng(lat,lon),
        title: name,
        icon: webroot+'img/branches/mapmarker3.png'
    });
    
    /*
    var infowindow = new google.maps.InfoWindow({
        content: popuptext,
        maxWidth: 300
    });
    */

    google.maps.event.addListener(marker, 'click', function() {
    	infowindow.setContent(popuptext); 
		infowindow.open(map,marker);
	});
	
	markersArray.push(marker);
}


function googleClearMarkers() {
	if(markersArray){
		for(i in markersArray){
			markersArray[i].setMap(null);
			
			//markersArray[i].infowindow.close();
		}
		markersArray.length = 0;
		infowindow.close();
	}
}


function gooogleCreateBranchMap(){
	googleLatLon = new google.maps.LatLng(52.132633, 5.291266);
	
	myOptions = {
		zoom: 7,
		center: googleLatLon,
		mapTypeId: google.maps.MapTypeId.TERRAIN,
		mapTypeControlOptions: {
		   mapTypeIds: []
		}

	};
	
	map = new google.maps.Map(document.getElementById("branche_map"),myOptions);
	
	google.maps.event.addListener(map, 'click', function() {
        infowindow.close();
    });

}

function googleZoomInToMarker(i){
	map.setZoom(9);
	google.maps.event.trigger(markersArray[i], 'click');
}


/*
function geocodeAndPutOnMap(name,inputaddress,popuptext){
	
	var address = inputaddress;
	geocoder.geocode( { 'address': address}, function(results, status){
	  if (status == google.maps.GeocoderStatus.OK) {
	    var marker = new google.maps.Marker({
	        map: map, 
	        position: results[0].geometry.location,
	        title: name,
	        icon: 'http://vertrigo/B/bo-rent/site/img/branches/mapicon.gif'
	    });
	    
	    var infowindow = new google.maps.InfoWindow({
	        content: popuptext
	    });

	    google.maps.event.addListener(marker, 'click', function() {
	      infowindow.open(map,marker);
		});
	  }
	  else {
	  	if(status=='ZERO_RESULTS'){
	  		//alert(address);
	  	}
	    alert("Geocode was not successful for the following reason: " + status);
	  }
	});
}
*/



function dropdownActions() {
	var tt;
	$("#navigatiebalk ul li a.head").mouseover(
		function () {
			hideSubNav();
			clearTimeout(tt);
			$subnav = $(this).parent().children('ul');
			showSubNav($subnav);
		}
	);
	$("#navigatiebalk ul li ul li a").mouseover(
		function () {
			clearTimeout(tt);
		}
	);
	$("#navigatiebalk ul li a").mouseout(
		function () {
			tt = setTimeout('hideSubNav()', 1000);
		}
	);
}

function hideSubNav() {
	$("#navigatiebalk ul li ul").hide();
}
function showSubNav(subnav) {
	subnav.show();
}
/*
function mouseOverImg (index) {
	obj.find('img')
		.addClass("hover")
		.stop()
		.animate({
			marginTop: '-52px', 
			marginLeft: '-72px',
			top: '50%',
			left: '50%',
			width: '144px', 
			height: '104px', 
			padding: '0px'
		}, 50); 
}
function mouseOutImg (obj) {
	obj.css({'z-index' : '0'}); 
	obj.find('img').removeClass("hover").stop()  
		.animate({
			marginTop: '0', 
			marginLeft: '0',
			top: '2px',
			left: '0',
			width: '72px',
			height: '52px', 
			padding: '0px'
		}, 100);
}
*/
function checkBlockType() {
	$val = $('select[name=\'data[Block][boxtype]\']').val();
	if ($val=='text') {
		$('#text-edit').show();
		$('#image-edit').hide();
	}
	else if($val=='image'){
		$('#image-edit').show();
		$('#text-edit').hide();
	}
	else{
		$('#text-edit').hide();
		$('#image-edit').hide();
	}
}

function checkCustomerPrivate() {
	if ($('input[name=\'data[Customer][is_private]\']:checked').val()==1) {
		$('#is_company_box').hide();
	}
	else{
		$('#is_company_box').show();
	}

	$('input[name=\'data[Customer][is_private]\']').click(function(){
		if ($(this).val()==1) {
			$('#is_company_box').hide();
		}
		else{
			$('#is_company_box').show();
		}
	});
}

function toggleNews() {
	url = window.location;
	h = url.hash.substring(1);
	$('.nieuws_description[id!="'+h+'"]').hide();
	$('.nieuws_content h2').click(function(){
		$(this).parent().children('.nieuws_description').toggle();
	});
}

function toggleFaqView() {
	$('#faq_box').hide();
	$('.faq_link').click(function(){
		$(this).parent().next('#faq_box').toggle();
		return false;
	});
}

function toggleFaqs() {
	$('.faqs_description').hide();
	$('.faqs_content .linkaj').click(function(){
		$(this).parent().children('.faqs_description').toggle();
	});
}

function toggleAvailableBranches() {
	$('.show_available_branches').hover(
		function(){
			$(this).parent().parent().children('.available_branches').fadeIn('fast');
		},
		function() {
			$('.available_branches').hide();
		}
	);
}

function createTableSortable(table, action) {
	$(table).sortable({ 
		items: 'tr', 
		placeholder: 'ui-state-highlight', 
		axis: 'y', 
		handle: '.handle',
		items: 'tr:not(.ui-state-disabled)',
		update: function(e, ui){
            $.ajax({
                type: "POST",
                url: webroot+action,
                data: "itemId=&newOrder="+$(table).sortable('toArray'),
                error: function(msg){
                    $("#JQresult").html(msg);
                },
                success: function(msg){
                    $("#JQresult").html(msg);
                }
            });
		}
	});
}

function multipleSelectFilter() {
	$(document).ready(function(){
		// unselect all subcategories
		$('#CategoryCategory option').attr("selected",false);
		// show the default subcategories
		displaySubcategories($('#ProductHeadCategory').val());
		// onchange action for headcategory
		$('#ProductHeadCategory').change(function(){
			displaySubcategories($(this).val());
		});
		// add a selected option
		$('#add_cat').click(function() {
			current_head = $('#ProductHeadCategory option:selected').html();
			$('#filtered_categories option:selected').each(function(index) {
				current_sub = $(this).html();
				$(this).clone().appendTo('#CategoryCategory').html(current_head+' - '+current_sub);
			});
			return false;
		});
		// delete a categoriy
		$('#delete_cat').click(function() {
			$('#CategoryCategory option:selected').remove();
			return false;
		});
		// select all options for posting
		$('#ProductAdminEditForm, #ProductAdminAddForm').submit(function(){
			$('#CategoryCategory option').attr("selected","selected");
		});
	});
	
	function displaySubcategories(parent_id) {
		$('select#filtered_categories option').remove();
		$('select#hidden_select option.parent_'+parent_id).clone().appendTo('#filtered_categories');
	}
}


function days_between(date1, date2) {

    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24;

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime();
    var date2_ms = date2.getTime();
    // Calculate the difference in milliseconds
    var difference_ms = Math.abs(date1_ms - date2_ms);
    
    // Convert back to days and return
    return Math.round(difference_ms/ONE_DAY);

}

function adddays(date1, adddays) {
    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime();
    // Calculate the difference in milliseconds
    
    // Convert back to days and return
    d = new Date(Math.round(date1_ms + adddays * ONE_DAY));
    return d;

}

