﻿/*
    Uses google maps
        http://code.google.com/apis/maps/documentation/javascript/reference.html
*/

var map

function initialize() {
    var myLatLng = new google.maps.LatLng(0, 0);
    //var opt = new google.maps.OverviewMapControlOptions({opened:true});
    var myOptions = {
    zoom: 1,
    backgroundColor: '#9CB2CE',
    center: myLatLng,
    mapTypeId: google.maps.MapTypeId.TERRAIN, // terrain looks better than map/sattellite
    streetViewControl: false, // dont want to go to street level
    panControl: false, // circle with NS< EW> arrows to move you around
        overviewMapControl: true,
        overviewMapControlOptions: {
            opened: false
        },
        maxZoom:4,
        minZoom:1,
        mapTypeControl: false // map satellite
        
    };

    if (document.getElementById("map_canvas")) {
        map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
        //map.fitBounds(new google.maps.LatLngBounds(new google.maps.LatLng(-50, 50))
        //    , new google.maps.LatLngBounds(new google.maps.LatLng(50, -50)));
        map.AllPolyHPolygons = [];

        var lastPoint;
        google.maps.event.addListener(map, "mousemove", function(event) { window.status = event.latLng.lat().toFixed(8) + ', ' + event.latLng.lng().toFixed(8); });

        google.maps.event.addListener(map, "click",
            function(event) { Debug_WriteLine('[' + event.latLng.lng().toFixed(8) + ', ' + event.latLng.lat().toFixed(8) + '],'); });
        google.maps.event.addListener(map, "zoom_changed", map_zoomChanged);
        google.maps.event.addListener(map, "bounds_changed",
            function() {
                Debug_WriteLine('getBounds().getNorthEast()=[' + map.getBounds().getNorthEast().lng().toFixed(4) + ',' + map.getBounds().getNorthEast().lat().toFixed(4) + ']' + '  .getSouthWest()=[' + map.getBounds().getSouthWest().lng().toFixed(4) + ',' + map.getBounds().getSouthWest().lat().toFixed(4) + ']');
            });

        $('.MapLinkContainer .MapLinkOpener').toggle(MapLinkOpener_close, MapLinkOpener_open);
    }

    // setup Where/When/Type
/*
    $('#wheredetail').show();
    $('#wheresummary').hide();
    $('#whensummary').show();
    $('#whendetail').hide();
    $('#where').click(
        function() {
            $('#wheresummary').hide();
            $('#wheredetail').show();
            $('#whensummary').show();
            $('#whendetail').hide();
        }
    );*/
    SearchAccordianShow('where');
    $('#where').click(function() { SearchAccordianShow('where'); });
    //alert($('#when').html());
    $('#when').click(function() { SearchAccordianShow('when'); });
    $('#type').click(function() { SearchAccordianShow('type'); });

    //onclick = "$('#wheredetail').toggle()"
}

function SearchAccordianShow(tab) {
    if (tab != 'where') {
        $('#whereSummary').slideDown('fast');
        $('#whereDetail').slideUp('fast');
    }
    if (tab != 'when') {
        $('#whenSummary').slideDown('fast'); // show();
        $('#whenDetail').slideUp('fast');   //hide();
    }
    if (tab != 'type') {
        $('#typeSummary').slideDown('fast'); // show();
        $('#typeDetail').slideUp('fast');   //hide();
    }

    $('#' + tab + 'Summary').slideUp('fast');   //hide();
    $('#' + tab + 'Detail').slideDown('fast'); //show();

}

function map_zoomChanged() {
    Debug_WriteLine('getZoom()=' + map.getZoom());
    var z = map.getZoom();
    $.each(map.AllPolyHPolygons, function(i, polyHpoly) {
        var _map = null;
        if (contains(polyHpoly.ZoomLevels, z)) {
            _map = map;
        }
        // dont set / unset the map needlessly 
        if (polyHpoly.getMap() != _map) {
            polyHpoly.setMap(_map);
            if (_map == null) {
                Debug_WriteLine('hide');
                Debug_WriteLine($(polyHpoly.linkedHtml).html());
                //$(polyHpoly.linkedHtml).hide();
            } else {
                //$(polyHpoly.linkedHtml).show();
            }
        }
    });

}
function MapLinkOpener_open() {
    //Debug_WriteLine('open');
    //Debug_WriteLine($(this).html());
    var childrenContainer = $('.MapLinkChildren', $(this).parent())
    childrenContainer.show(100, null);
    var polyHpoly = $('.MapLinkSelector', $(this).parent()).get(0).PolyHPoly
    Debug_WriteLine(polyHpoly.Bounds);
    if (polyHpoly.Bounds != null) {
        map.panTo(new google.maps.LatLng(polyHpoly.Bounds[0],polyHpoly.Bounds[1]));
        map.setZoom(polyHpoly.Bounds[2]);
    }
}
function MapLinkOpener_close(){
    var childrenContainer = $('.MapLinkChildren', $(this).parent())
    childrenContainer.hide(100, null);
}

function MapLinkOpener_onclick(MapLinkOpener) {
    var childrenContainer = $('.MapLinkChildren', $(MapLinkOpener).parent())
    childrenContainer.toggle(100, null);
    if (childrenContainer.is(':visible')) {
        Debug_WriteLine('visible')
    }
}


function Debug_WriteLine(text) { 
    $('#info').val($('#info').val() + text + '\n');
}
    function setupContinentEvents(nn) {
        if (nn.length) {
            $.each(nn, function(i, n) {
                google.maps.event.addListener(n, "mouseover", poly_mouseover); //this.setOptions({ fillOpacity: .1 });
                google.maps.event.addListener(n, "mouseout", poly_mouseout);
            });
        } else {
            google.maps.event.addListener(nn, "mouseover", poly_mouseover);
            google.maps.event.addListener(nn, "mouseout", poly_mouseout);
        }
    }


    function poly_mouseover(event) {
        if (this.parent) {
            $.each(this.parent, function(i, n) { poly_mouseover_core(n) });
        } else {
            poly_mouseover_core(this);
        }
    }
    function poly_mouseover_core(control) {
        if (control.Highlight) {
            poly_mouseover_core(control.Highlight);
        } else {
            control.setOptions({ strokeOpacity: .8, fillOpacity: .3 });
            $(control.linkedHtml).addClass('areaHover');
        }
    }
    function poly_mouseout(event) {
        if (this.parent) {
            $.each(this.parent, function(i, n) { poly_mouseout_core(n) });
        } else {
            poly_mouseout_core(this);
        }
    }
    function poly_mouseout_core(control) {
        if (control.Highlight) {
            poly_mouseout_core(control.Highlight);
        } else {
            control.setOptions({ strokeOpacity: 0, fillOpacity: 0 });
            if (control.linkedHtml) {
                $(control.linkedHtml).removeClass('areaHover');
                
            }
        }
    }

function contains(ZoomLevels, zoom){
    for (var i = 0; i < ZoomLevels.length; i++) {
        if (ZoomLevels[i] == zoom){
            return true;
        }    
    }
    return false;
}

///<summary>
/// Link is being hovered over eg Africa so highlight the map Poly for Africa
///<summary>
function MapLinkSelector_mouseEnter() {
    //Debug_WriteLine($(this).get(0).PolyHPoly);
    poly_mouseover_core($(this).get(0).PolyHPoly);
}
///<summary>
/// Link is being no longer being hovered over eg Africa so remove highlight from map for Africa
///<summary>  
function MapLinkSelector_mouseLeave() {
    poly_mouseout_core($(this).get(0).PolyHPoly);
}
    
///<summary>
/// Factory object for generating 
///<summary>  
function PolygonFactory() {
    this.map = map;
}
///<summary>
/// Create a PolygonHighlightingPolygon
///<summary>
PolygonFactory.prototype.PolyHPoly = function(coordinates, SelectingCoordinates, linkedHtmlSelector, ZoomLevels,Bounds) {

    var _map = null;
    if (contains(ZoomLevels, map.getZoom())) {
        _map = this.map;
    }

    var result = this.Poly(coordinates, _map);
    var SelectionArea;
    result.ZoomLevels = ZoomLevels;
    result.Bounds = Bounds;
    if (SelectingCoordinates == null) {
        SelectionArea = this.Poly(coordinates, _map);
    } else {
        SelectionArea = this.Poly(SelectingCoordinates, _map);
    }

    SelectionArea.setOptions({ fillOpacity: 0 });
    SelectionArea.Highlight = result;
    setupContinentEvents(SelectionArea);
    setupContinentEvents(SelectionArea.Highlight);
    result.linkedHtml = $(linkedHtmlSelector).get(0);
    result.linkedHtml.PolyHPoly = result;
    $(result.linkedHtml).hover(MapLinkSelector_mouseEnter, MapLinkSelector_mouseLeave); //(MapLinkSelector_mouseEnter, MapLinkSelector_mouseLeave);
    //$(result.linkedHtml).hover(function() { Debug_WriteLine(($(this).html())); $(this).fadeOut(100); $(this).fadeIn(500); }); //(MapLinkSelector_mouseEnter, MapLinkSelector_mouseLeave);
    //Debug_WriteLine($(result.linkedHtml).html());
    result.setOptions({ fillOpacity: 0, zIndex: 2 });
    map.AllPolyHPolygons.push(result);
    return result;
}


///<summary>
/// Create a Polygon
///<summary>
PolygonFactory.prototype.Poly = function(coordinates,setMap) {
    
    var paths = [];
    $.each(coordinates, function(i, n) {
        var path = [];
        $.each(n, function(j, p) { path.push(new google.maps.LatLng(p[0], p[1]));});
        paths.push(path);
    });

    return new google.maps.Polygon({
        paths: paths,
        strokeColor: "#FF9933",
        strokeOpacity: 0,
        strokeWeight: 2,
        fillColor: "#FF9933",
        fillOpacity: 0.0,
        map: setMap,
        geodesic: false
    });
}

//BEGIN PRODUCT DETAILS JAVASCRIPT
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]

$(document).ready(function(){
    if ($("#featured").length >0)
    {
        $("#featured > ul").tabs({ fx: { opacity: "toggle" } }).tabs("rotate", 10000, true);
    }
});

function GetProductPrice(ProductId, ProductCode, GuestNum, DepartureDate, DepartureCtlId) 
{
    //TODO : Remove absolute URL and get domain from url itself
    // GetItineraryPriceForDuration(string productId, int numberOfGuests, string departureDate)
    //dd3e2f51-623c-4c8a-825b-cb3343ea54b9,JAM,3,Jan|12,ddlMonth
    var productId = ProductId;
    var departureDate = DepartureDate;
    var guestNum = GuestNum;
    var productCode = ProductCode
    //string productId, string departureDate, string guestNum
    $.ajax({
        type: "POST",
        url: "http://" + window.location.hostname + "/SignIn.aspx/GetItnPrice",
        data: "{'productId':'" + productId + "','productCode':'" + productCode + "','numberOfGuests':'" + guestNum + "','departureDate':'" + departureDate + "'}",
        success: function(data) {
            var dat = data.d;
            var html = '';
            var bselected = false;
            if (data.d.length > 0) {
                //yyyy,mm,price
                for (var i = 0; i < data.d.length; i++) {
                    var flds = data.d[i].split(",");
                    var mnth = months[flds[1] - 1].substring(0, 3);
                    var yr = flds[0].substring(2, 4);
                    var arDts = departureDate.split("|");

                    if (arDts[1] == yr && arDts[0] == mnth) {
                        $("#productPrice").html("£" + flds[2]);
                        html += '<option value="' + mnth + '|' + yr + '" selected="selected">' + mnth + ' ' + yr + '</option>';
                        bselected = true;
                    }
                    else {
                        html += '<option value="' + mnth + '|' + yr + '">' + mnth + ' ' + yr + '</option>';
                    }

                }
                if (!bselected) {
                    var price = data.d[0].split(",")[2];
                    $("#productPrice").html("£" + price);
                }

                UpdateLowestPrice(data);
                $('#' + DepartureCtlId).empty().append(html);
            }
            $("#btnSubmit").show();
            $("#ajaxWait").hide();


        },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function(e, textStatus, errorThrown) {
            //bReturn = false;
        }
    });
}



function RefreshPrice(DepartureId, ProductCode) {
    if (DepartureId == 'ddlMonth') {
        $("#btnSubmit").hide();
        $("#ajaxWait").show();
        var departureDt = "";
        
        if ($('#' + DepartureId + ' option').size() > 0) {
            departureDt = $("#" + DepartureId + " option:selected").val();
        }
        else {
            departureDt = "Jan|" + ((new Date()).getFullYear()+1).toString().substring(2,4);
        }
        GetProductPrice(getQueryString()["id"], ProductCode, $("#ddlGuests option:selected").val(), departureDt, DepartureId);
    }
}

function UpdateLowestPrice(data) {
    var dat = data.d;
    var html = '';
    for (var i = 0; i < data.d.length ; i++) {
        var flds = data.d[i].split(",");
        var mnth = months[flds[1] - 1].substring(0, 3);
        var yr = flds[0];
        html += '<tr><td class="dataCell"><a onclick="UpdatePriceBrief(\'' + mnth + '\',\'' + yr + '\',\'' + flds[2] + '\')" href="#">' + months[flds[1] - 1] + '   ' + yr + '</a></td>';
        html += '<td class="dataCell"><a onclick="UpdatePriceBrief(\'' + mnth + '\',\'' + yr + '\',\'' + flds[2] + '\')" href="#">£' + flds[2] + '</a></td></tr>';
    }
    $('#tblLowestPrice').empty().append(html);
}

function UpdatePriceBrief(mnth, year, price) {
    $("#productPrice").html("£" + price);
    var drpVal = mnth + "|" + year.substring(2, 4);
    $("#ddlMonth").val(drpVal);
}

function getQueryString() {
    var result = {}, queryString = location.search.substring(1),
			  re = /([^&=]+)=([^&]*)/g, m;
    while (m = re.exec(queryString)) {
        result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
    }
    return result;
}

function toggleTab(linkid) {
    var pnlid = "panel" + linkid.substring(linkid.length - 1);
    var panels = $("[id^='panel']");
    panels.each(
			function(idx, div) {
			    var tidx = div.id.substring(div.id.length - 1);
			    if (div.id == pnlid) {
			        $("#" + div.id).show();
			        $("#link" + tidx).addClass("selected");
			    }
			    else {
			        $("#" + div.id).hide();
			        $("#link" + tidx).removeClass("selected");
			    }
			});
}
//END PRODUCT DETAILS JAVASCRIPT

//SALES PRINT OUTS
function showHide(objID) {
    var theImage = $("#objID" + 'DDL');
    if ($("#" + objID).is(":visible")) {
        $("#" + objID).hide();
        if(theImage.length>0)//not sure if this and below lines are used in any other page(s).
        {theImage.attr("src", "/images/TitanAgents/apps/app-extend-close.png");}
    }
    else {
        $("#" + objID).show();
        if(theImage.length>0)
        { theImage.src = "/images/TitanAgents/apps/app-extend-open.png"; }    
    }
}
//USE JQUERY
function showHideNew(el) {
//    var theEle = _div.style;
    var theImage = el;
//    $(_div).toggle();
    if (theImage.src.indexOf("app-extend-close.png") == -1) {
        theImage.src = "/images/TitanAgents/apps/app-extend-close.png";
    }
    else {
        theImage.src = "/images/TitanAgents/apps/app-extend-open.png";

    }
}

function SPtoggle(div) {
    var option = ['selectPosterBackgrounds', 'selectPosterSizes', 'selectPosterOrientations'];
    for (var i = 0; i < option.length; i++) {
        obj = document.getElementById(option[i]);
        obj.style.display = (option[i] == div) && !(obj.style.display == "block") ? "block" : "none";
    }
}
function SPpreviewPoster() {
    document.getElementById('DisplayType').value = "preview";
    //$("#txtBackgroundImage").val($("#selBackgroundImage option:selected").text());
    var frm = document.getElementById('frmHTMLToPDF');
    frm.action = 'printposter.aspx';
    frm.method = 'get';
    frm.submit();
}

function SPsubmitPoster() {
    document.getElementById('DisplayType').value = "print";
    var frm = document.getElementById('frmHTMLToPDF');
    frm.action = 'offer-poster1.aspx';
    frm.method = 'get';
    frm.submit();
}

function SPsetBackground(posterId) {
    $("#selBackgroundImage").val(posterId);
}

function SPsetLayoutSize(layout) {
    $("#pagesize").val(layout);

}

function SPsetLayoutOrientation(orientation) {
    $("#pageorientation").val(orientation);
}
function swapImage(imgID) {
    var theImg = document.getElementById(imgID)
    if (theImg.src.indexOf("close.png") < 0)
        theImg.src = "/images/TitanAgents/apps/app-extend-close.png";
    else
        theImg.src = "/images/TitanAgents/apps/app-extend-open.png";
}

function fontSizer(size) {

    if (document.getElementById('link100')) {
        document.getElementById('link100').className = 'fontsizer100';
        if (size == '100') {
            document.getElementById('link100').className = 'fontsizer100';
        }
    }

    if (document.getElementById('link110')) {
        document.getElementById('link110').className = 'fontsizer110';
        if (size == '110') {
            document.getElementById('link110').className = 'fontsizer110';
        }
    }

    if (document.getElementById('link120')) {
        document.getElementById('link120').className = 'fontsizer120';
        if (size == '120') {
            document.getElementById('link120').className = 'fontsizer120';
        }
    }
    
    if (document.getElementById('page'))
    {
        document.getElementById('page').style.fontSize = size + '%';
    }

}
//SALES PRINT OUTS
