var VillasToGo = window.villasToGo || {};

VillasToGo.Common = {
	
	initialize: function() {
		jQuery.ajaxSetup({
			'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
		});

		jQuery.fn.submitWithAjax = function() {
			this.submit( function() {
				$.post($(this).attr("action"), $(this).serialize(), null, "script");
				return false;
			});
		};
		
	}
	
}

$( VillasToGo.Common.initialize );

$(function() {

    // Shared destination select
    $('#country_id').change(function() {
        var url = '/admin/destination_select/update_destination_children_options?update_id=region_id&value=' + this.value;

        $.ajax({
            type: 'GET',
            dataType: 'script',
            url: url
          });

    });

    $('#region_id').change(function() {
        var url = '/admin/destination_select/update_destination_children_options?update_id=town_id&value=' + this.value;

        $.ajax({
            type: 'GET',
            dataType: 'script',
            url: url
          });

    });

    $('#ad-search-button').click(function() {
        $('#loading-dialog-message').dialog({
			modal: true
		});
    });



    // Initialise date pickers
    $(".ui_date_picker").datepicker({ dateFormat: 'dd/mm/yy', maxDate: '+2Y', changeMonth: true, changeYear: true });

    $('#departure_date').datepicker({dateFormat: 'd/m/yy', maxDate: '+2Y', changeMonth: true, changeYear: true, onSelect: setSearchDepartureDate});


    $(".optional_extra_link").click(function(event) {
        event.preventDefault();

        $.ajax({
            type: 'GET',
            dataType: 'script',
            url: this.href
          });
    });

    $(".shortlist_link_ajax").click(function(event) {
        event.preventDefault();

        $.ajax({
            type: 'GET',
            dataType: 'script',
            url: this.href
          });
    });

    $('.create-callback').click(function() {
			$('#callback-dialog').dialog('open');
		}).hover(
			function(){
				$(this).addClass("hover");
			},
			function(){
				$(this).removeClass("hover");
			}
		);

    $(".submit_with_ajax").submitWithAjax();


    // Callback feature
    var title = $("#title"),
        first_name = $("#first_name"),
        surname = $("#surname"),
        email = $("#email"),
        telephone = $("#telephone"),
        message = $("#message"),
        allFields = $([]).add(title).add(first_name).add(surname).add(email).add(telephone).add(message),
        tips = $("#validateTips");

    function updateTips(t) {
        tips.text(t).effect("highlight",{},1500);
    }

    function checkLength(o,n,min,max) {

        if ( o.val().length > max || o.val().length < min ) {
            o.addClass('ui-state-error');
            updateTips("Length of " + n + " must be between "+min+" and "+max+".");
            return false;
        } else {
            return true;
        }

    }

    function checkRegexp(o,regexp,n) {

        if ( !( regexp.test( o.val() ) ) ) {
            o.addClass('ui-state-error');
            updateTips(n);
            return false;
        } else {
            return true;
        }

    }
    


    $("#callback-dialog").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 450,
            width: 450,
			modal: true,
			buttons: {
				'Callback': function() {
					var bValid = true;
					allFields.removeClass('ui-state-error');

					bValid = bValid && checkLength(first_name,"first name",1,80);
                    bValid = bValid && checkLength(surname,"surname",1,80);
					bValid = bValid && checkLength(email,"email",6,80);
					bValid = bValid && checkLength(telephone,"telephone",5,24);

					// From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
					bValid = bValid && checkRegexp(email,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"Invalid email address should be in format: name@example.com");
					bValid = bValid && checkRegexp(telephone,/^([0-9_ ])+$/,"Telephone field only allow : 0-9");

                    if(bValid) {

                        $("#callback-form").submit();
                        $(this).dialog('close');
                    }
				},
				Cancel: function() {
					$(this).dialog('close');
				}
			},
			close: function() {
				allFields.val('').removeClass('ui-state-error');
			}
		});


        $("#callback-form").submitWithAjax();

});


function setSearchDepartureDate(text, control){

  // Text is the value selected by the user in the form d/m/yyyy
  var dt = text.split('/');
  $('#day').val(dt[0]);
  $('#flexible_month').val(dt[1] + ' ' + dt[2]);
}

function showDatepicker(id)
{
  //
  // Set the text input to the selected date in the drop downs
  // in the format we set for the datepicker.

  var flex_month_args = $('#flexible_month').val().split(' ');
  var day = $('#day').val();
  if (day == '') { day = '1' };
  $('#' + id).val(day + '/' +
                  flex_month_args[0] + '/' +
                  flex_month_args[1]);

  $('#' + id).datepicker('show');
}


// Common google map functions
function createNumberMarker( latitude, longitude, number, html ) {
    var icon = createIcon( 'gmap_icon_number_' + number + '.png' );
    return createMarker( latitude, longitude, icon, html );
}

function createVillaMarker( latitude, longitude, html ) {
    var icon = createIcon( 'gmap_house_icon.png' );
    return createMarker( latitude, longitude, icon, html );
}

function createApartmentMarker( latitude, longitude, html ) {
    var icon = createIcon( 'gmap_apartment_icon.png' );
    return createMarker( latitude, longitude, icon, html );
}

function createGuletMarker( latitude, longitude, html ) {
    var icon = createIcon( 'gmap_gulet_icon.png' );
    return createMarker( latitude, longitude, icon, html );
}

function createChaletMarker( latitude, longitude, html ) {
    var icon = createIcon( 'gmap_chalet_icon.png' );
    return createMarker( latitude, longitude, icon, html );
}


function createAirportMarker( latitude, longitude, html ) {
    var icon = createIcon( 'gmap_airport_icon.png' );
    return createMarker( latitude, longitude, icon, html );
}

function createIcon( imageName ) {
    var icon = new GIcon();
    icon.image = '/images/vtg/gmap_markers/' + imageName;
    icon.shadow = '/images/vtg/gmap_markers/shadow.png';
    icon.iconSize = new GSize(30, 37);
    icon.shadowSize = new GSize(30, 37);
    icon.iconAnchor = new GPoint(10, 37);
    icon.infoWindowAnchor = new GPoint(15, 5);
    return icon;
}

function createMarker( latitude, longitude, icon, html ) {
    var point = new GLatLng( latitude, longitude );
    var marker = new GMarker(point, icon);
    var infoDiv = document.createElement('div');
    infoDiv.innerHTML = html;
    enableShortlistLinks(infoDiv);
    marker.bindInfoWindow(infoDiv);
    return marker;
}

function enableShortlistLinks(infoDiv) {
    $(infoDiv).find(".shortlist_link_ajax").click(function(event) {
        event.preventDefault();

        $.ajax({
            type: 'GET',
            dataType: 'script',
            url: this.href
          });
    });
}



