﻿var map = null;
var DEFAULT_ZOOM = 2;
var PROPERTY_PIN_IMAGE = "http://chart.apis.google.com/chart?cht=d&chdp=mapsapi&chl=pin_star'i\'['-2'f\hv'a\]h\]o\FF0000'fC\000000'tC\000000'eC\FFFF00'1C\000000'0C\Lauto'f\&ext=.png";

// fade out the first shortList item
$(function() {
    var shortList = new Sunhat.Web.Shortlist();
    if (shortList.get_items().length > 0)
        $('#actions').css({ 'display': 'block' });

    $('#liSendToSunhat').click(function(event) { ShowContactWindow(true); });
    $('#liSendToFriend').click(function(event) { ShowFriendWindow(true); });
    $('#liBrochureRequest').click(function(event) { ShowBrochureWindow(true); });
    $('#btnCancel').click(function(event) { ShowContactWindow(false); });
    $('#btnCancelFriend').click(function(event) { ShowFriendWindow(false); });
    $('#btnCancelBrochure').click(function(event) { ShowBrochureWindow(false); });
    $('#btnSend').click(SendEnquiry_Click);
    $('#btnSendFriend').click(SendFriend_Click);
    $('#btnBrochureSend').click(SendBrochure_Click);

    $('#btnCheck').click(checkAvailability);
    $('#btnBookingCancel').click(function(event) { $('#booknow').hide(); $('#overlay').hide() });

    $('#liDeleteAll').click(function(event) {
        if (confirm('Are you sure you wish to delete all of your shortlist items?')) {
            var shortList = new Sunhat.Web.Shortlist();
            shortList.deleteAll();
            $('.searchresultitem').css({ 'backgroundColor': '#fff' })
                                                          .animate({ 'opacity': 0 }, 1000, function() { $(this).remove(); });

            $('#numItems').html('You have no items in your shortlist.');
            $('#actions').css({ 'display': 'none' });
        }
    });

    // assign handler to each shortlist item link
    $('.link').each(function() {
        var item = new Sunhat.Web.ShortlistItem();
        var pID = $(this).attr('name');
        item.propertyID = parseInt(pID);

        var shortlist = new Sunhat.Web.Shortlist();
        $(this).click(function(event) { deleteShortlistItem(event, pID); }).html('Remove from Shortlist');
    });

    // assign a book handler to each book link
    $('.footer').each(function() {
        $(this).append(' | <span class="link book" name="' + $($(this).children()[2]).attr('name') + '">Book Now</span>');
    });

    $('.book').click(function(event) {
        $('#hidPID')[0].value = $(this).attr('name'); $('#overlay').show(); $('#booknow').show(); $('#pw').hide(); if ($('#main_modals_bookdate')[0].value != '')
            checkAvailability();
    })

});

function checkAvailability(event) {
    $('#btnCheck')[0].disabled = true;
    $('#bookingDates').hide();
    $('#booknow').animate({ 'height': '100px' }, 200, function() { $('#pw').show(); });
    var date = $('#main_modals_bookdate')[0].value;
    var duration = parseInt($('#main_modals_ddlDuration')[0].value);
    var id = $('#hidPID')[0].value;
    Sunhat.Web.ClientService.Service.GetBookingPrices(id, date, duration, GetBookingPricesSuccess, GetBookingPricesFailed);

}
function GetBookingPricesSuccess(results) {
    $('#pw').hide();
    var s = '';
    var pid = parseInt(location.search.substring(1).split('=')[1]);
    var date = $('#main_modals_bookdate')[0].value
    var duration = $('#main_modals_ddlDuration')[0].value;
    if (results.length > 0) {
        $('#booknow').animate({ 'height': parseInt(100 + (20 * results.length)) + 'px' }, 200);
        
        for (var i = 0; i < results.length; i++) {

            s += '<div>';
            if (results[i].Date == date) s += '<strong>';
            s += results[i].Date + ' for ' + results[i].Duration + ' nights : ' + results[i].Price + ' - ';
            var lnk = 'https://www.sun-hat-villas.com/booking.aspx?b=' + encodeURIComponent(results[i].Hash);
            s += '<a href="' + lnk + '">Book Now<a/>';
            if (results[i].Date == date) s += '</strong>';
            s += '</div>';

        }
    }
    else
        s = 'Sorry, there are no available dates around ' + date + ' for ' + duration + ' nights.';
    $('#bookingDates').show().html(s);
    $('#btnCheck')[0].disabled = false;

    pageTracker._trackPageview('/ajax/booknow/' + pid);
}

function GetBookingPricesFailed(err) {
    alert(err.get_message());
}

function deleteShortlistItem(event, pID) {
    if (confirm('Do you really want to delete this item from your shortlist?')) {
        var sli = new Sunhat.Web.ShortlistItem();
        sli.propertyID = pID;
        var shortlist = new Sunhat.Web.Shortlist();
        shortlist.remove_item(sli);
        // remove the item from view
        $(event.target).parent()
                       .parent()
                       .css({ 'backgroundColor': '#fff' })
                       .animate({ 'opacity': 0 }, 1000)
                       .animate({ 'height': 0 },1000, function() { $(this).remove(); });

        var text = new Sys.StringBuilder();
        text.append('You have ');
        switch (shortlist.get_items().length) {
            case 0:
                {
                    text.append('no items ');
                    break;
                }
            case 1:
                {
                    text.append('1 item ');
                    break;
                }
            default:
                {
                    text.append(shortlist.get_items().length + ' items ');
                }
        }
        text.append('in your shortlist.');
        $('#numItems').html(text.toString());
        if (shortlist.get_items().length == 0)
            $('#actions').css({ 'display': 'none' });

        pageTracker._trackPageview('/ajax/removefromshortlist/' + pID);
    }
}

function ShowContactWindow(show) {
    $('#overlay').css({ 'display': show ? 'block' : '' });
    $('#contactDetails').css( {'display': show ? 'block' : '' });
}

function ShowFriendWindow(show) {
    $('#overlay').css({ 'display': show ? 'block' : '' });
    $('#sendToFriend').css( {'display': show ? 'block' : '' });
}

function ShowBrochureWindow(show) {
    $('#overlay').css({ 'display': show ? 'block' : '' });
    $('#sendBrochure').css( {'display': show ? 'block' : '' });
}

function SendEnquiry_Click(evt)
{
    var email = $get('contactEmail').value;
    var title = $get('contactTitle').value;
    var firstname = $get('contactFirstname').value;
    var surname = $get('contactSurname').value;
    var telephone = $get('contactTelephone').value;
    var notes = $get('contactNotes').value;
    
    var err = '';
    
    // check for e-mail
    if(email == '')
        err+='Please enter an e-mail address.\n';
    
    // check e-mail address
    else
    {
        var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if(!email.match(emailRegEx))
            err+='Please enter a valid e-mail address.\n';
    }
            
    if(surname == '')
        err+='Please enter your surname.\n';
        
    if(firstname == '')
        err+='Please enter your firstname.\n';
        
    if(title == '')
        err+='Please enter your title (Mr., Mrs., Miss etc.)\n';
        
    if(err!='')
    {
        alert(err);
        return false;
    }
    var enq = new Sunhat.Web.ClientService.Enquiry();
    enq.Email = email;
    enq.Title = title;
    enq.Firstname = firstname;
    enq.Surname = surname;
    enq.Telephone = telephone;
    enq.Notes = notes;
    
    // send the enquiry
    Sunhat.Web.ClientService.Service.SendShortlist(enq, SendSuccess, SendFailed);

    ShowContactWindow(false);
        
    ShowPleaseWait(true, 'Sending Shortlist...');
}

function ShowPleaseWait(show,message) {
    if (show) {
        $('#pleaseWait').show();
        $('#pMessage').html = message;
    }
    else
        $('#pleaseWait').hide();
}

function SendSuccess(result)
{
    var div = $get('pleaseWait');
    div.innerHTML = '<h4>Shortlist Sent</h4>';
    setTimeout('ShowPleaseWait(false)', 2000);
    pageTracker._trackPageview('/ajax/shortlistsent.html');
}

function SendFailed(err)
{
    alert(err.get_message());
}

function SendFriend_Click(sender) {
    var shortList = new Sunhat.Web.Shortlist();
    var props = shortList.get_propertyIDs();

    var friendName = $get('friendName').value;
    var friendEmail = $get('friendEmail').value;
    var name = $get('yourName').value;
    var email = $get('yourEmail').value;
    var message = $get('emailDetails').value;

    var err = '';
    var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    
    // check for e-mail
    if (friendEmail == '')
        err += 'Please enter your friend\'s e-mail address.\n';

    // check e-mail address
    else {
        
        if (!friendEmail.match(emailRegEx))
            err += 'Please enter a valid e-mail address for your friend.\n';
    }

    // check for e-mail
    if (email == '')
        err += 'Please enter your e-mail address.\n';

    // check e-mail address
    else {

        if (!email.match(emailRegEx))
            err += 'Please enter a valid e-mail address for you.\n';
    }

    if (friendName == '')
        err += 'Please enter your friend\'s name.\n';

    if (name == '')
        err += 'Please enter your name.\n';

    if (err != '') {
        alert(err);
        return false;
    }

    ShowPleaseWait(true, 'Sending Shortlist to ' + friendName + '...');

    Sunhat.Web.ClientService.Service.SendShortlistToFriend(props, friendEmail, friendName, email, name, message, SendShortListToFriendSuccess, SendFailed);

    ShowFriendWindow(false);
}

function SendShortListToFriendSuccess(results) {
    $get('friendName').value = ''
    $get('friendEmail').value = ''
    var div = $get('pleaseWait');
    div.innerHTML = '<h4>Shortlist Sent</h4>';
    setTimeout('ShowPleaseWait(false)', 2000);
    pageTracker._trackPageview('/ajax/sendshortlisttofriend.html');
}


// TODO finish location map for shortlisted properties
function liLocationMap_Click(sender) {
    var shortList = new Sunhat.Web.Shortlist();
    
    var mapElement = $get('map');
    if (GBrowserIsCompatible()) {
        // remove the static image
        mapElement.removeChild(mapElement.childNodes[0]);

        // set up the dynamic map
        map = new GMap2(mapElement);
        map.setMapType(G_HYBRID_MAP);
        map.setCenter(new GLatLng(latitude, longitude), zoom);
        var mapControl = new GMapTypeControl();
        map.addControl(mapControl);
        map.addControl(new GLargeMapControl());

        var scalePosition = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10, 30));
        map.addControl(new GScaleControl(), scalePosition);

        var props = shortList.get_propertyIDs();

        Sunhat.Web.ClientService.Service.GetPropertyLocations(props, PropertyLocationGetSuccess, SendFailed);
    }
}

function PropertyLocationGetSuccess(results) {
    // load properties onto map
    for(var i=0; i < results.length; i++)
    {
        var lat = results[i].Latitude;
        var lng = results[i].Longitude;
        if(lat != '' && lng != '')
            addProperty(lat,lng );
    }
}            

function addProperty(latitude, longitude) {
    //set up the coordinates for our marker
    var point = new GLatLng(latitude, longitude);

    var icon = MapIconMaker.createLabeledMarkerIcon({ primaryColor: "#FF0000", strokeColor: "#000000" });
    // create the marker
    var marker = new GMarker(point, icon);

    // add the marker to the map
    map.addOverlay(marker);
}

function SendBrochure_Click(sender) {
    var shortList = new Sunhat.Web.Shortlist();
    var props = shortList.get_propertyIDs();

    var email = $get('brochureEmail').value;
    var name = $get('brochureName').value;

    var err = '';
    var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

    // check for e-mail
    if (email == '')
        err += 'Please enter your e-mail address.\n';

    // check e-mail address
    else {

        if (!email.match(emailRegEx))
            err += 'Please enter a valid e-mail address.\n';
    }

    if (name == '')
        err += 'Please enter your name.\n';

    if (err != '') {
        alert(err);
        return false;
    }

    ShowPleaseWait(true, 'Sending Brochure Request...');

    Sunhat.Web.ClientService.Service.SendBrochure(props, email, name, SendBrochureSuccess, SendFailed);

    ShowBrochureWindow(false);
}

function SendBrochureSuccess(result) {
    var div = $get('pleaseWait');
    div.innerHTML = '<h4>Brochure Sent</h4><p>Please check your e-mail inbox in a few minutes.</p>';
    setTimeout('ShowPleaseWait(false)', 5000);
    pageTracker._trackPageview('/ajax/sendbrochure.html');
    
}
