/* ******
MAP/PLACEPAGE DISPLAY STUFF
****** */

var fade;

$(document).ready(function() {
	
    /* ******
            SET ENVIRONMENT
            ****** */
            
	$("#gmap-layout, #my-selection").show();
	
	$("div.note").livequery(function() {
		$(this).show();
	});
	
	$("#place-info").livequery(function() {
		$(this).hide();
	});
	
	$("div.hidden").livequery(function() {
		$(this).css('opacity', fade);
	});

	/* date popups */
	$("#staydate-form, #date-form").hide();

    /* ******
            LODGING NOTES
            ****** */
          
	/* display notes */  
	$(".note a").livequery("click", function(event) {
        
		var lodId = lodgingId($(this));
		
		if(lodId != 0) {
		
			$.getJSON("/shortlist/note/id/" + lodId, function(data) {

                $('.dialog').dialog('destroy').remove(); // remove previous dialog
                $('<div class="dialog"></div>').html(data.html).dialog({  title: 'Write a Note',
                                                                            modal: true,
                                                                            resizable: false,
                                                                            width: 450,
                                                                            bgiframe: true,
                                                                            open: function() {
                                                                                $("#login-form :text:first, #note-form textarea").focus();
                                                                            }
                                                                        });
					
			});
		
		}
		
		event.preventDefault();
		
	});
	
	/* submit note */
	$("#note-form").livequery("submit", function(event) {

		$.post(this.action, $("#note-form").serialize(), function(data) {
		
			if(!data.completed) {
				$("#note-form .form-error").html(data.errors);
			} else {
				$(".id" + $("#note-form #id").val() + " .note-container").html(data.notes);
				$('.dialog').dialog('destroy').remove(); // remove previous dialog
			}
			
		}, "json");
		
		event.preventDefault();
		
	});
	
    /* ******
            LOGIN & REGISTER
            ****** */
            
	/* display login */
	$("a.button-login, a#show-login").livequery("click", function(event) {

       
		$.getJSON(this.href + "/format/json", function(data) {
			
            $('.dialog').dialog('destroy').remove(); // remove previous dialog
            $('<div class="dialog"></div>').html(data.html).dialog({  title: 'Sign In',
                                                                        modal: true,
                                                                        resizable: false,
                                                                        width: 350,
                                                                        bgiframe: true,
                                                                        open: function() {
                                                                            $("#login-form :text:first").focus();
                                                                        }
                                                                    });
				
		});

		event.preventDefault();
		
	});
    
	
	/* login submit */
	$("#login-form").livequery("submit", function(event) {
	
		event.preventDefault();

		$.post("/auth/login/format/json", $("#login-form").serialize(), function(data) {
		
			if(!data.loggedIn) {
            
				$("#login-form .form-error").html(data.error);
				$("#login-form:password").empty();
                
			} else {
            
                $('.dialog').dialog('destroy').remove(); // remove previous dialog
                
				$("#login-register").html(data.html);
				$("div#shortlist").replaceWith(data.shortlist);
                
				mapMove();
				applySortable();
                
			}
			
		}, "json");
		
		
	});
	
	/* switch login to register */
	$("#show-register").livequery("click", function(event) {
	        
		$.getJSON(this.href + "/format/json", function(data) {

            $('.dialog').dialog('destroy').remove(); // remove previous dialog
            $('<div class="dialog"></div>').html(data.html).dialog({  title: 'Sign In',
                                                                        modal: true,
                                                                        resizable: false,
                                                                        width: 350,
                                                                        bgiframe: true,
                                                                        open: function() {
                                                                            $("#register-form :text:first").focus();
                                                                        }
                                                                    });
				
		});

		event.preventDefault();
		
	});
	
	/* register submit */
	$("#register-form").livequery("submit", function(event) {
	
		event.preventDefault();

		$.post("/auth/register/format/json", $("#register-form").serialize(), function(data) {
		
			if(!data.loggedIn) {
            
				$("#register-form .form-error").html(data.error);
				$("#register-form:password").empty();
                
			} else {
            
                $('.dialog').dialog('destroy').remove(); // remove previous dialog
                
				$("#login-register").html(data.html);
				$("div#shortlist").replaceWith(data.shortlist);
			}
			
		}, "json");
		
		
	});

	/* logout */
	$("a.button-logout").livequery("click", function(event) {
	
		event.preventDefault();
		
        $('.dialog').dialog('destroy').remove(); // remove previous dialog
        $('<div class="dialog">Are you sure you want to sign out?</div>').dialog({  title: 'Sign Out',
                                                                    modal: true,
                                                                    resizable: false,
                                                                    width: 350,
                                                                    bgiframe: true,
                                                                    open: function() {
                                                                        $("#register-form :text:first").focus();
                                                                    },
                                                                    buttons: {
                                                                        'No': function() {
                                                                            $(this).dialog('close');
                                                                        },
                                                                        'Yes': function() {
                                                                        
                                                                            $.getJSON("/auth/logout/format/json", function(data) {
                                                                            
                                                                                    $("#login-register").html(data.html);
                                                                                    $("div#shortlist").replaceWith(data.shortlist);
                                                                                    
                                                                                    mapMove();
                                                                                    
                                                                            });
                                                                            
                                                                            $(this).dialog('close');
                                                                            
                                                                        }
                                                                    }

                                                                });

	});
	
    /* ******
            DATE SUBMISSION
            ****** */
            
	/* date form */
    var dateFormDialog =    $("#date-form").dialog({
                                title: 'Change Date',
                                modal: true,
                                resizable: false,
                                autoOpen: false,
                                width: 350,
                                bgiframe: true
                            });
    
	$("span.button-date, a.button-date").livequery("click", function(event) {

		dateFormDialog.dialog('open');
		event.preventDefault();
		
	});
    
	
	/* date submit */
	$("#date-form").submit(function(event) {
	
		event.preventDefault();

        /* clear rates */
        $("table.rfTable").empty();

        /* show please wait */
        $("p.loadingBookingOptions").show();
            
		$.post("/page/date/format/json", $("#date-form").serialize() + "&idList=" + getIdList(), function(data) {
		
			$("#stayDate").text(data.dateCurrency);
			$("p.date span").text(data.dateCurrency);

			setReload();
			
			dateFormDialog.dialog('close');
			
		}, "json");
		
	});
    
    /* ******
            NEW WINDOW
            ****** */
	
	/* new window */
	$("a.new-window").livequery("click", function(event) {
        
        if(window.open(this.href)) {
            return false;
        }
        
        return true;

	});
	
    /* ******
            SHOW MORE PLACE INFO
            ****** */
            
	/* place info slide */
	$("#show-more").livequery("click", function(event) {
	
			$("#place-info").slideToggle();

			if($("a#show-more").text() == '+') {
				$("a#show-more").text('-');
			} else {
				$("a#show-more").text('+');
			}

			event.preventDefault();
			
	});
    
    /* ******
           FILTERS
            ****** */
            
	/* filter change update */
	$("#selectGroup select").change(mapMove);
	$("#selectGroup input:checkbox").click(mapMove);
	
	/* check checkboxes if brand selected */
	$("#groups").change(function() {

		if($(this).val() != 0) {
			$("#selectGroup input:checkbox").attr('checked', true);
		}
		
	});
	
	/* default group if checkbox unticked */
	$("#selectGroup input:checkbox").click(function() {
		$('#groups').val("0");
	});
	
    
    /* ******
            SHORTLIST
            ****** */
            
	/* sortable  */
	function applySortable() {
		$("div#shortlist ul").sortable({containment: 'div#shortlist', helper: 'clone', axis: 'y', update : function () {
			$.post("/shortlist/order", $(this).sortable('serialize'));
		}});	
	}
	applySortable();
    
    $("span.add-shortlist").livequery("click", function(event) {
    
		var id = lodgingId(this);

		$("div.id" + id + " li.add-remove-shortlist span").toggle(); // toggle shortlist lodging icon
		
		// update shortlist widget
		$.getJSON('/shortlist/add/id/' + id + '/format/json', function(data) {
			$("div#shortlist").replaceWith(data.shortlist);
			applySortable();
		});
		
		event.preventDefault();
        
        
    });
    
    $("span.remove-shortlist").livequery("click", function(event) {
    
		var id = lodgingId(this);

		$("div.id" + id + " li.add-remove-shortlist span").toggle(); // toggle shortlist lodging icon
        
		$("div.results-popup div.id" + id).remove(); // from shortlist popup if open
		if(($("div.results-popup").length) && ($("div.results-popup").children().length < 1)) {
            $('.dialog').dialog('destroy').remove(); // remove previous dialog
		}
		
		// update shortlist widget
		$.getJSON('/shortlist/remove/id/' + id + '/format/json', function(data) {
			$("div#shortlist").replaceWith(data.shortlist);
			applySortable();
		});
		
		event.preventDefault();
    
    });

    /* ******
            HIDE/SHOW LODGINGS
            ****** */
            
	$("span.show-hide-show").livequery("click", function(event) {

		var id = lodgingId(this);
		
		$("div.id" + id + " li.show-hide a, div.id" + id + " li.show-hide span").toggle(); // toggle radio

        $("div.id" + id).css('opacity', fade); // fade out
        $("div.id" + id + " div.entry-results").hide() // hide results

		$.get('/shortlist/hide/id/' + id + '/format/json');

		event.preventDefault();
			
	});
    
	$("span.show-hide-hide").livequery("click", function(event) {

		var id = lodgingId(this);
		
		$("div.id" + id + " li.show-hide a, div.id" + id + " li.show-hide span").toggle(); // toggle radio

        $("div.id" + id).css('opacity', 1); // fade in
        $("div.id" + id + " div.entry-results").show() // hide results

		$.get('/shortlist/show/id/' + id + '/format/json');

		event.preventDefault();
			
	});
	
	$("a.show-lodging").livequery("click", function(event) {
    
		showLodging(this.href, 'url');
        
		event.preventDefault();
        
	});
	
	$("a.button-shortlist").livequery("click", function(event) {

		var $dialog = $('<div></div>')
			.load(this.href + "/format/ajax")
			.dialog({
				title: 'myShortlist',
                modal: true,
                resizable: false,
				width: maxWindowWidth(),
				height: maxWindowHeight(),
                bgiframe: true,
                open: function() {
                    setReload();
                }
			});

		event.preventDefault();
		
	});
    
    
    /* ******
            LODGING CONTACT POPUP
            ****** */
            
	$(".contact-us").livequery("click", function(event) {
    
        var id = lodgingId(this);
        
		var $dialog = $('<div></div>')
			.load("/info/index/lodgingId/" + id + "/format/ajax")
			.dialog({
				title: 'Contact Us',
                modal: true,
                resizable: false,
				width: maxWindowWidth(),
				height: maxWindowHeight(),
                bgiframe: true
			});

		event.preventDefault();
        
	});
    
	$("#wrong-details-form").livequery("submit", function(event) {
    
		$.post('/info/wrongdetails/', $(this).serialize());
        $(this).html('<p class="green">Thank you for your contact.</p>');
		
		event.preventDefault();
        
	});
    
	$("#send-to-email-form").livequery("submit", function(event) {
    
		$.post('/info/senddetails/', $(this).serialize());
        $(this).html('<p class="green">Details have been sent.</p>');
		
		event.preventDefault();
        
	});
    
	$(".print-page").livequery("click", function(event) {

        $(this).parents('.contact-popup').jqprint();

		event.preventDefault();
        
	});

});

/* lodging popup */
function showLodging(idOrUrl, type) {

	var type = (type == null) ? "id" : type;

    if(type == "id") {
        url = "/page/show/id/" + idOrUrl + "/format/ajax";
    } else {
        url = idOrUrl + "/format/ajax";
    }
    
    var width = $('#map-list').width();
        
    var $dialog = $('<div class="dialog"></div>').load(url)
        .dialog({
            title: 'Lodging Details',
            modal: true,
            resizable: false,
            width: width,
            position: 'top',
            bgiframe: true,
            open: function() {
                setReload();
            }
        });

}

/* extract current lodging id from obj  */
function lodgingId(obj) {

	var className = $(obj).parents("div.entry, li.shortlistitem");
	
	if(className.length > 0) {
		return className.attr("class").match(/id([0-9]*)/)[1];
	}
	
	return 0;
		
}

/* get id list */
function getIdList() {

	var idList = "0";
	$("div.entry").each(function (i) {
		idList = idList + "," + $(this).attr("class").match(/id([0-9]*)/)[1];
	});
	
	return idList;
	
}

/* reload RF tables*/
var reload = 4000;
function setReload() {
	$.timer(reload, reloadData);
}


/* set reload onload */
setReload();

function reloadData(timer) {

	$.post("/page/reload", "idList=" + getIdList(), function(data) {
		
        /* hide loading */
        $(".loadingBookingOptions").hide();

		$.each(data.results, function(i, result) {
		
			$.timer(Math.random()*500, function (timer2) {

				$("div.rates" + result.id).html(result.html);
                
				timer2.stop();
                
			});
			
		});
		
		if(data.stillChecking) {
			
			reload = reload + 500;
			timer.reset(reload);
			
		} else {
			timer.stop();
		}
		
	}, "json");

}