﻿// The next line adds a reference to an intellisense file for JQuery
/// <reference path="jquery-1.3.2-vsdoc.js" />

// Globals
var slideSpeed = 700;
var slideRight = true;
var currentSlideLink;
var printContentQuery;
var slideIsMap = false;
var enquiryModeIsBooking = false;

function PrintSpecials() {
    printContentQuery = "#listingTitle,#contactInfo,#Specials,#printFooter";
    var win = window.open("/_html/print.html", "specialsPrint", "width=640,height=640,location=no,menubar=no,scrollbars=yes,status=no,toolbar=no");
}
function PrintMap() {
    printContentQuery = "#listingTitle,#contactInfo,#Map2,#printFooter";
    var win = window.open("/_html/map.html", "mapPrint", "width=640,height=640,location=no,menubar=no,scrollbars=no,status=no,toolbar=no");
}
function PrintCallback() {
    // return jQuery(printContentQuery).html(); // hey jQuery, this does not work!
    var html = "";
    var ids = printContentQuery.split(",");
    for (var i = 0; i < ids.length; i++) {
        html += jQuery(ids[i]).html();
    }
    return html;
}
function Hide(jquery, speed) {
    jQuery(jquery).slideUp(speed);
}

function Show(jquery, speed) {
    jQuery(jquery).slideDown(speed);
}

function ShowBooking() {
    jQuery("input[name=Mode]").val("Booking");
    jQuery("tr.booking").show();
    jQuery("#enquiryCaption").html("Reservation form <small><a href='#Enquiry' onclick='ShowEnquiry();return false;'>Switch to enquiry form</a> </small>");
    jQuery("#remarksLabel").html("Any comments?:");
    jQuery("#sendButton").val("Send Reservation");
    Show("#enquiry", "slow");
}

function ShowEnquiry() {
    jQuery("input[name=Mode]").val("Enquiry");
    jQuery("tr.booking").hide();
    jQuery("#enquiryCaption").html("Enquiry form <small><a href='#Reservation' onclick='ShowBooking();return false;'>Switch to reservation form</a> </small>");
    jQuery("#remarksLabel").html("Your enquiry*:");
    jQuery("#sendButton").val("Send Enquiry");
    Show("#enquiry", "slow");
}

function loadRecentlyViewed() {
    jQuery.get("/Documents/Recent", { "WebsiteId": jQuery("input[name=WebsiteId]").val(), "mode": "viewed" }, 
    function(data) {
        jQuery("#recentlyViewed").html(data);
        jQuery("#recentlyViewed").show();
    }, "html");   
}
function loadRecentlyStarred() {
    jQuery.get("/Documents/Recent", { "WebsiteId": jQuery("input[name=WebsiteId]").val(), "mode": "starred" }, 
    function(data) {
        if (data.length > 0) {
            jQuery("#recentlyStarred").html(data);
            jQuery("#recentlyStarred").show();
        }
        jQuery("#share").show();
    }, "html");
}
function starDocument(id) {
    jQuery.get("/Documents/Star", { "WebsiteId": jQuery("input[name=WebsiteId]").val(), "DocumentId": id },
    function(data) {
        // TODO: Make star glow, Add to recently starred
    }, "json");
}

function ShowMoreComments(e) {
    $.get(GetWsUrl("/Listings/Comments/"), { listingId: $("#ListingId").val(), websiteId: $("#WebsiteId").val() }, function(j) {
        try {
            $("div#moreComments").html(j);
            $("div#moreComments").slideDown("slow");
            $(e).hide();
        }
        catch (e) { }; // silence callback errors
    });
}


//    $("#enquiryDialog").dialog(
//	{
//	    bgiframe: true,
//	    autoOpen: false,
//	    height: 730,
//	    width: 550,
//	    modal: true,
//	    buttons:
//	    {
//	        'Send': EnquiryNeedCaptcha,
//	        Cancel: function() {
//	            $(this).dialog('close');
//	        }
//	    },
//	    open: function() {

//	    if (captcha) {
//	        $("#enquiry_captcha_tr").show();
//	        createCaptcha("enquiry_recaptcha_div");
//	    }
//	    else
//	        $("#enquiry_captcha_tr").hide();
//	    
//	    var isBooking = enquiryModeIsBooking;

//	        $("#enquiryModeField").hide();
//	        $("#enquiryFormCaption").hide();
//	        $("#enquiryFormOK").hide();
//	        $("#enquiryForm")[0].onsubmit = function() { EnquiryFormSend(); return false; };

//	        if (isBooking) {
//	            $("tr.booking").show();
//	            $("#ui-dialog-title-enquiryDialog").html("Reservation form");
//	            mode.val("Booking");
//	        }
//	        else {
//	            $("tr.booking").hide();
//	            $("#ui-dialog-title-enquiryDialog").html("Enquiry form");
//	            mode.val("Enquiry");
//	        }
//	    },
//	    close: function() {
//	        allFields.removeClass('ui-state-error');
//	        $("#enquiryValidateTips").show();
//	        $("#enquiryForm").show();
//	        $("#enquiryDialog").siblings(".ui-dialog-buttonpane").show();
//	        $("#enquiryFormInfo").hide();
//	    }
//	});

function MoreLinks() {
    // tests certain content divs to see if they are too big for the slideshow, and if so resizes and displays a button to scroll them
    var scroller = jQuery(".slide2 > div.about_content, .slide2 > div.about_content2");
    scroller.each(function() {
        if (jQuery(this).height() > 370) {
            jQuery(this).css({ "overflow": "hidden" });
            jQuery(this).height("370px");
            jQuery(this).children("div.about_more").show();
        }
    });
}

function MoreContent(e) {
    // Hides the "read more" button, turns on the scrollbars, scrolls the content down a bit
    jQuery(e).parent().hide();
    jQuery(e).parent().parent().css({ "overflow": "auto" });
    jQuery(e).parent().parent().animate({ "scrollTop": "180px" }, slideSpeed, "swing");    
}

// Event handlers
jQuery(document).ready(body_onready);

function body_onready() {
    // Set event handlers
    $("#commentForm").submit(CommentForm_OnSubmit);
    $("#enquiryForm").submit(EnquiryForm_OnSubmit);    
    
    // If Image query in the URL, show the appropriate slide
    if (location.search.length > 1) {
        if (location.search.indexOf("?Image") == 0) 
        {
            var seq = parseInt(location.search.replace("?Image", ""));
            if (isNaN(seq)) {
                SelectThumb(jQuery("#navTray > a:first"));
            }
            else
            {
                seq--;
                if (seq > 0) jQuery("#navTray > a:eq(" + seq + ")").click();
                else SelectThumb(jQuery("#navTray > a:first"));
            }
        }
        // Show map, comments, enquiry form etc
        else jQuery("a[href=#" + location.search.replace("?", "") + "]").click();
    }
    else SelectThumb(jQuery("#navTray > a:first"));
    StarListings();
    jQuery(".datepicker").each(parseDatePicker);
    jQuery(".timepicker").each(parseTimePicker);
    
    // init popup comments form
    $("#commentDialog").dialog({
        bgiframe: true,
        autoOpen: false,
        height: 550,
        width: 500,
        modal: true
    });
    $("#CommentForm").hide();
    
    // init popup enquiry form
    $("#enquiryDialog").dialog({
        bgiframe: true,
        autoOpen: false,
        height: 650,
        width: 500,
        modal: true,
        open: function() {
            var isBooking = enquiryModeIsBooking;
            $("#enquiryModeField").hide();
            if (isBooking) {
                $("tr.booking").show();
                $("#ui-dialog-title-enquiryDialog").html("Reservation form");
                $("#enquiryMode").val("Booking");
            }
            else {
                $("tr.booking").hide();
                $("#ui-dialog-title-enquiryDialog").html("Enquiry form");
                $("#enquiryMode").val("Enquiry");
            }
        }
    });
    $("#EnquiryForm").hide();
    
    // If postback, show confirmation
    if (location.search.length > 1) {
        // Only show postbacks from localhost or *.eatoutadmin.com
        if (location.search.indexOf("?msg=") == 0) {
            switch (location.search.substr(5)) {
                case "CommentOK":
                    $("#CommentOK").dialog(
                    {
                        bgiframe: true,
                        autoOpen: true,
                        height: 250,
                        width: 450,
                        modal: false
                    }); 
                    break;
                case "EnquiryOK":
                    $("#EnquiryOK").dialog(
                    {
                        bgiframe: true,
                        autoOpen: true,
                        height: 250,
                        width: 450,
                        modal: false
                    });
                    break;
            }
        }
    }

    // Load the map
    showAddress($("#Map2 > div > div.gmap > div")[0], $("#gmapinfo1")[0]);
}

function CommentForm_OnSubmit() {
    var v = new Validator($("#commentFormInfo"));

    v.CheckLength("#commentName", "Name", 1, 100) && v.CheckLength("#commentEmail", "Email", 1, 200) && v.CheckEmail("#commentEmail", "Email")
        && v.CheckLength("#commentLocation", "Location", 1, 50) && v.CheckLength("#commentVisitedDate", "When last visited", 1, 50)
        && v.CheckLength("#commentRemarks", "Comments", 1, 1000);

    return v.IsValid;
}

function EnquiryForm_OnSubmit() {
    var v = new Validator($("#commentFormInfo"));
    
    v.CheckLength("#enquiryName", "Name", 1, 100) && v.CheckLength("#enquiryEmail", "Email", 1, 200)
        && v.CheckEmail("#enquiryEmail", "Email") && ($("#enquiryMode").val() == "Booking" ? v.CheckLength("#enquiryPhone", "Phone number", 1, 50) 
            && v.CheckLength("#enquiryDate", "Date", 1, 50) && v.CheckLength("#enquiryTime", "Time", 1, 50) 
            && v.CheckLength("#enquiryNumberPeople", "Number of people", 1, 100) : v.CheckLength("#enquiryRemarks", "Comments", 1, 1000));

    return v.IsValid;
}
var slideLeft = false;

function menu_onclick(e) {
    var href = jQuery(e).attr("href");
    if (href == "#Photos") jQuery("#navTray > a:first").click();
    else jQuery("#navTray > a[href=" + href + "]").click();
}

function thumb_onclick(e) {
    // don't slide if the same thumb was clicked twice
    if (e.href == currentSlideLink) return;
    slideLeft = SelectThumb(e);
    LoadTray(e);
}

function LoadTray(e) {
    // Switch any scrollbars off because Mozilla doesn't like animating them
    jQuery(".slide2 > div.about_content").css({ "overflow": "hidden" });
    slideIsMap = false;
    if (e.href.search("#") >= 0) {
        // Menu, Special, Map, etc
        var id = e.href.substr(e.href.search("#"));
        
        switch (id) {
            case "#Map":
                slideIsMap = true;
                if (slideLeft) {
                    jQuery("#slideR").html(jQuery("#Map").html());
                }
                else {
                    jQuery("#slideL").html(jQuery("#Map").html());
                }

                MoreLinks();
                SlideTray();

                break;
            default:
                if (slideLeft) {
                    jQuery("#slideR").html(jQuery(id).html());
                    MoreLinks(); 
                    SlideTray();
                }
                else {
                    jQuery("#slideL").html(jQuery(id).html());
                    MoreLinks(); 
                    SlideTray();
                }
                break;
        }
        Hilite(jQuery("a[href=" + id + "]")[0]);
    }
    else {
        // Image
        // load tray and wait for image to load
        Hilite(jQuery("#photos2 > a")[0]);

        if (slideLeft) {
            jQuery("#slideR").html("<img class='slide2' src='" + e.href + "?size=500&amp;ratio=1' alt='' title='' />");
            jQuery("#slideR > img")[0].onload = SlideTray;
        }
        else {
            jQuery("#slideL").html("<img class='slide2' src='" + e.href + "?size=500&amp;ratio=1' alt='' title='' />");
            jQuery("#slideL > img")[0].onload = SlideTray;
        }
        jQuery("#wait16")[0].style.display = "block";
    }

}

function SlideTray() {
    try {
        jQuery("#wait16")[0].style.display = "none";
        if (slideLeft) jQuery("#slideTray").animate({ left: "-1492px" }, slideSpeed, "swing", SlideTrayCallback);
        else jQuery("#slideTray").animate({ left: "0px" }, slideSpeed, "swing", SlideTrayCallback);
        if (!slideIsMap)  $("#gmap2").hide();
        

    }
    catch (ex) {
        HandleException(ex);
    }        
}

function SlideTrayCallback() {
    // copy the slide to the center slide and reset
    try {
        var img = jQuery("#slideL > img")[0];
        if (img != null) img.onload = null;
        img = jQuery("#slideR > img")[0];
        if (img != null) img.onload = null;

        if (slideLeft) jQuery("#slide").html(jQuery("#slideR").html());
        else jQuery("#slide").html(jQuery("#slideL").html());
        jQuery("#slideTray")[0].style.left = "-746px";

        if (slideIsMap) {
            $("#gmap2").show();
            showAddress($("#gmap2")[0], $("#gmapinfo2")[0]);
        }
    }
    catch (ex) {
        HandleException(ex);
    }
}

function Hilite(e) {
    jQuery("#nav_restaurant > li > a").each(function() { this.style.backgroundPosition = "0 0"; });
    e.style.backgroundPosition = "0 -32px";
}

function HandleException(ex) {
    if (document.location.toString().search("http://localhost") >= 0) alert(ex);
}

function SlideNext() {
    var e = jQuery("#navTray > a[href=" + currentSlideLink + "]");
    if (e.next()[0] == null) jQuery("#navTray > a:first").click();
    else e.next().click();
}
function SlidePrev() {
    var e = jQuery("#navTray > a[href=" + currentSlideLink + "]");
    if (e.prev()[0] == null) jQuery("#navTray > a:last").click();
    else e.prev().click();
}

function SelectThumb(e) {
    var num = jQuery("#navTray > a").index(e);
    
    slideLeft = (jQuery("#navTray > a").index(e) > jQuery("#navTray > a").index(jQuery("#navTray > a[href=" + currentSlideLink + "]")));
    currentSlideLink = jQuery(e).attr("href");
    
    // Move the thumbs
    jQuery(e).children().animate({ opacity: 1 }, 100);
    jQuery(e).siblings().children().animate({ opacity: 0.5 }, 100);
    jQuery("#navTray").animate({ left: "" + (337 - (num * 75)) + "px" }, slideSpeed, "swing", SelectThumbCallback);
    return slideLeft;
}

function SelectThumbCallback() {
    // not finished, but intention is to allow slides to continue in a loop
    return;
    try {
        var imageCount = jQuery("#ImageCount").val();
        var imageWidth = 75;
        var trayWidth = imageCount * 2 * imageWidth;
        var offset = 750;
        var left = jQuery("#navTray")[0].offsetLeft;
        var i = 0;
        if (left > 0 && left < offset) i = left - offset;
        else if (left < 0 && left < -offset) i = jQuery("#navTray")[0].offsetLeft + offset;
        else return;
    }
    catch(ex)
    {
        HandleException(ex);
    }
}

// Google mapping functions
function showAddress(mapDiv, infoDiv) {
    // infoId is the id of the Info balloon and is compulsory
    if (GBrowserIsCompatible()) {
        var address = jQuery("#Address").val();
        var gLatLng = jQuery("#GLatLng").val();

        // If a GLatLng value exists use it to create a point
        if (gLatLng.length > 0) {
            eval("var point = new GLatLng(" + gLatLng + ");");
            DrawMarker(point, mapDiv, infoDiv);
        }
        else {
            // Geocode the address and draw a point in the callback
            var geocoder = new GClientGeocoder();
            geocoder.getLatLng(address, function(a) { DrawMarker(a, mapDiv, infoDiv); });
        }
    }
}
function DrawMarker(point, mapDiv, infoDiv) {
    var gZoomLevel = 15; //starting zoom level. Lower number = a higher altitude

    if (!point) {
        var ex = address + " not found";
        HandleException(ex);
    }
    else {
        // Initialise the map object
        var map = new GMap2(mapDiv);
        map.addControl(new GSmallMapControl());

        // Create the Eatout custom icon
        var icon = new GIcon();
        icon.image = "/_images/pin.png";
        icon.shadow = "/_images/pin_shadow.png";
        icon.iconSize = new GSize(36, 36);
        icon.shadowSize = new GSize(36, 36);
        icon.iconAnchor = new GPoint(3, 34);
        icon.infoWindowAnchor = new GPoint(25, 1);

        // center the map
        map.setCenter(point, gZoomLevel);
        // draw the marker
        var marker = new GMarker(point, icon);
        map.addOverlay(marker);
        // Show the info
        infoDiv.style.display = "block";
        marker.openInfoWindow(infoDiv);
    }
}
