﻿var hosturl = GetCurrentHostUrl(document.location);
var map = null;
var cityLayer = new VEShapeLayer();
var pathLayer = new VEShapeLayer();
var routeDayLayer = new VEShapeLayer();
var redIcon = "<div class='spriteImage redIcon' style='margin:5px 0px 0px 5px;'>&nbsp;</div>";
var yellowIcon = "<div class='spriteImage orangeIcon' style='margin:5px 0px 0px 5px;'>&nbsp;</div>";
var currentShape = null;

var ctvEnContlink = "http://www.ctvolympics.ca/torch/tell-your-story/index.html";
var ctvFrContLink = "http://www.rdsolympiques.ca//torch/tell-your-story/index.html";
var msnEnContLink = "http://torch.sports.msn.ca/upload";
var msnFrContLink = "http://flamme.sports.msn.ca/upload";

var routePathDataHandler;
var infoboxHandler;

var partnerParam = "ctv";
var languageParam = "en";

function GetCurrentHostUrl(url) {
    var cutoff;
    var cutIndex;
    if (url.toString().indexOf('https') < 0) { // http
        cutIndex = 7;
        cutoff = url.toString().substring(cutIndex).indexOf('/');
        return "http://" + url.toString().substring(cutIndex).substr(0, cutoff + 1);
    } else { // https
        cutIndex = 8;
        cutoff = url.toString().substring(cutIndex).indexOf('/');
        return "https://" + url.toString().substring(cutIndex).substr(0, cutoff + 1);
    }
}

function GetMap() {
    map = new VEMap('myMap');
    map.SetClientToken(token);
    map.LoadMap(new VELatLong(58,-95), null, VEMapStyle.Road, null, null, false);

    //disable shape display threashold so that polyline shows up correctly.
    map.EnableShapeDisplayThreshold(false);

    //Enable printing capability
    var printOpt = new VEPrintOptions(true);
    map.SetPrintOptions(printOpt);

    //Ensure that the map uses Kilometers instead of miles.
    map.SetScaleBarDistanceUnit(VEDistanceUnit.Kilometers);

    //Add shape layers to map
    map.AddShapeLayer(cityLayer);
    map.AddShapeLayer(pathLayer);
    map.AddShapeLayer(routeDayLayer);

    //Create data handler for route data
    routePathDataHandler = new DataPointHandler(map, cityLayer, CreateCity);

    //Create the infobox control
    InfoboxControl = new CustomInfoboxControl("mainMap_Infobox", map);
    
    //hide the city layer so that any shapes added to layer do not render
    cityLayer.Hide();
    
    //Add the route path to the city layer for processing
    var routeDataLayerSpec = new VEShapeSourceSpecification(VEDataType.GeoRSS, "geoRSS/routeData.xml", cityLayer);
    map.ImportShapeLayerData(routeDataLayerSpec, processRouteData, false);  

    //Detect if browser is Firefox 3.5, this is to fix a bug in the browser
    if (navigator.userAgent.indexOf("Firefox/3.5") != -1) {
        document.getElementById("myMap").addEventListener('DOMMouseScroll', WindowMouseWheelHandler, false);
    }
    
    //Disable the birdseye popup
    document.getElementById('MSVE_obliqueNotification').style.display = 'none';
    document.getElementById('MSVE_obliqueNotification').style.visibility = 'hidden';

    // Attach events
    map.AttachEvent('onchangeview', routePathDataHandler.Redraw);
    map.AttachEvent('onclick', MouseClickHandler);
    map.AttachEvent('onmouseover', MouseOverHandler);

    map.AttachEvent('onchangeview', InfoboxControl.CloseInfobox);
    map.AttachEvent('onmousedown', InfoboxControl.CloseInfobox);
}

function DisposeMap() {
    if (map != null) {
        map.Dispose();
    }
}

function processRouteData(feed) {
    var routeData = [];
    var points = [];
 
    //loop trough feed and extract route data
    for (var i = 0; i < feed.GetShapeCount(); i++) {
        var shape = feed.GetShapeByIndex(i);
        
        var desc = shape.GetDescription();
        var data = desc.split("|");
        routeData.push({ "ID": i+1,
            "VisitDay": parseInt(data[0]),
            "Type": parseInt(data[1]),
            "isMajorCity": parseInt(data[2]),
            "City": data[3],
            "Province": data[4],
            "Date": data[5],
            "LatLong": shape.GetPoints()[0]
        });

        points.push(shape.GetPoints()[0]);
    }
    
    AddRoutePolyline(points);
    cityLayer.DeleteAllShapes();
    cityLayer.Show();
    routePathDataHandler.SetData(routeData);
    initializedropDowns();

    routeData = null;
    points = null;
}

//Create a pushpin shape for a city 
function CreateCity(city) {
    var coord = new VELatLong(city.LatLong.Latitude, city.LatLong.Longitude);
    var shape = new VEShape(VEShapeType.Pushpin, coord);
    
    //assign the shape with a route point ID for querying infobox data
    shape.RoutePointID = city.ID;

    if ((city.Type == 1 || city.Type == 3) && map.GetZoomLevel() > 7) {
        shape.SetCustomIcon(yellowIcon);
        shape._zIndex = 1000;
    }
    else {
        shape.SetCustomIcon(redIcon);
        shape._zIndex = 1001;
    }

    return shape;
}

/***********************************
Infobox content retrival methods
************************************/
function RequestInfoboxContent(shape) {
    var currLat = (shape.GetPoints()[0]).Latitude;
    var currLong = (shape.GetPoints()[0]).Longitude;
    currentShape = shape;
    //CTV.OlympicTorch.WebUI.WebServices.OlympicTorchServices.GetRoutePointSummaryByID(languageParam, partnerParam, shape.RoutePointID, GenerateInfobox);
    CTV.OlympicTorch.WebUI.WebServices.OlympicTorchServices.GetRoutePointSummaryByLatLong(languageParam, partnerParam, parseFloat(currLat), parseFloat(currLong), GenerateInfobox);
}

function GenerateInfobox(result) {
    if (result != null && result != "") {

        TrackOmniture("Torch Relay", "", "Torch Relay:Map", "", "map");
        
        var summary = eval("(" + result + ")");
        //if (summary.ID == currentShape.RoutePointID) {
        if (true) {
            var infoboxHeight = 31;
            var infoboxWidth = 200;

            try {
                //get all shapes at this location
            var shapeData = routePathDataHandler.GetDataByLatLong(currentShape.GetPoints()[0]);
            
            var numberOfLinks = 0;
            var description = ["<div style='width:", infoboxWidth, "px;'>"];

            if (shapeData.length > 0) {
                description.push("<div class='infoboxTitle'>", shapeData[0].City, "</div>");

                var currentType = 0;
                description.push("<div style='width:100%;'>");
                for (var i = 0; i < shapeData.length; i++) {

                    if (shapeData[i].Type == 2 && currentType != 2) {
                        description.push("<span class='infoboxCommunityTitle'>", resourceTxt.CELEBCOMMUNITY, "</span><br/>");
                        currentType = 2;
                        infoboxHeight += 13;
                    } else if (shapeData[i].Type == 1 && currentType != 1) {
                        description.push("<span class='infoboxCommunityTitle'>", resourceTxt.ROUTE_COMMUNITY, "</span><br/>");
                        currentType = 1;
                        infoboxHeight += 13;
                    } else {
                        currentType = 3;
                    }

                    var vDay = shapeData[i].VisitDay;
                    if (vDay == 0) {
                        vDay = 106;
                    }
                    description.push("<div class='infoboxCommunityDate'>", resourceTxt.DAY, " ", vDay, ", ", DateMonthLocalization(shapeData[i].Date), "</div>");

                    infoboxHeight += 12;
                }
                description.push("</div>");

                // Photo - 1
                // Video - 2
                // Story - 4
                if (summary.NumberOfNonUGCStories) {
                    description.push(GenerateInfoboxItem(shapeData[0].ID, 4, false, partnerParam, summary.NumberOfNonUGCStories, resourceTxt.NEWS_STORIES, shapeData[0].LatLong));
                    numberOfLinks++;
                }

                if (summary.NumberOfNonUGCPhotos) {
                    description.push(GenerateInfoboxItem(shapeData[0].ID, 1, false, partnerParam, summary.NumberOfNonUGCPhotos, resourceTxt.NEWS_PHOTOS, shapeData[0].LatLong));
                    numberOfLinks++;
                }

                if (summary.NumberOfNonUGCVideos) {
                    description.push(GenerateInfoboxItem(shapeData[0].ID, 2, false, partnerParam, summary.NumberOfNonUGCVideos, resourceTxt.NEWS_VIDEOS, shapeData[0].LatLong));
                    numberOfLinks++;
                }

                if (summary.NumberOfUGCStories) {
                    description.push(GenerateInfoboxItem(shapeData[0].ID, 4, true, partnerParam, summary.NumberOfUGCStories, resourceTxt.USER_STORIES, shapeData[0].LatLong));
                    numberOfLinks++;
                }

                if (summary.NumberOfUGCPhotos) {
                    description.push(GenerateInfoboxItem(shapeData[0].ID, 1, true, partnerParam, summary.NumberOfUGCPhotos, resourceTxt.USER_PHOTOS, shapeData[0].LatLong));
                    numberOfLinks++;

                }

                if (summary.NumberOfUGCVideos) {
                    description.push(GenerateInfoboxItem(shapeData[0].ID, 2, true, partnerParam, summary.NumberOfUGCVideos, resourceTxt.USER_VIDEO, shapeData[0].LatLong));
                    numberOfLinks++;

                }
            }

            infoboxHeight += 50 * numberOfLinks;

            description.push("<div style='width:100%;height:15px;'><p></p></div><div style='width:100%;height:15px;font-weight:bold;'><a href='javascript:void(0);' class='infoboxLink' onclick='contributeLink()'>", resourceTxt.CONTRIBUTE_VIDEO_PHOTO, " <span style='font-size:13px;font-weight:bold; position:relative; bottom:-2px;'>&#62;&#62;</span></a></div></div>");

            InfoboxControl.DisplayInfobox(description.join(''), shapeData[0].LatLong, infoboxWidth, infoboxHeight, true);

            } catch (ex) { }
        }
    }
}

function contributeLink() {
    if (partnerParam.toLowerCase() === "ctv" && languageParam.toLowerCase() === "en") {
        parent.location.href = ctvEnContlink;
    } else if (partnerParam.toLowerCase() === "ctv" && languageParam.toLowerCase() === "fr") {
        parent.location.href = ctvFrContLink;
    } else if (partnerParam.toLowerCase() === "msn" && languageParam.toLowerCase() === "en") {
        parent.location.href = msnEnContLink;
    } else if (partnerParam.toLowerCase() === "msn" && languageParam.toLowerCase() === "fr") {
        parent.location.href = msnFrContLink;
    } else  {
        parent.location.href = ctvEnContlink;
    }
}

function GenerateInfoboxItem(routeID, dataType, isUGC, partner, count, title, latlong) {
    var imageClass = "";
    var phrase = "";
    
    switch(dataType)
    {
        //photos
        case 1:
            imageClass = "photoImage";
            phrase = resourceTxt.COME_JOIN_THE_FUN;
            break;
        //videos 
        case 2:
            imageClass = "videoImage";
            phrase = resourceTxt.SHARE_OLYMPIC_SPIRIT;
            break;
        //story
        case 4:
        default:
            imageClass = "newImage";
            phrase = resourceTxt.READ_MORE_ABOUT_IT;
            break;
    }

    var itemHTML = [];
    itemHTML.push('<div class="hpuEntrySummary infoItem"><table class="hpuTable" onclick="showModalContent(\'', partner.toString(), '\',\'', languageParam.toString(), '\',', isUGC, ',', parseInt(dataType), ',', parseFloat(latlong.Latitude), ',', parseFloat(latlong.Longitude), ',', parseInt(routeID), ');">');
    itemHTML.push('<tbody><tr><td><img alt=""  class="spriteImage ' , imageClass, '" src="Images/transparentIcon.gif" /></td>');
    itemHTML.push('<td><span class="infoboxSubTitle">(', count, ') ', title, '</span><br />');
    itemHTML.push('</td></tr></tbody></table></div>');
    return itemHTML.join('');
}

/******************************
Route path building method
******************************/
function AddRoutePolyline(coordinates) {
    var routePath = new VEShape(VEShapeType.Polyline, coordinates);
    
    //Hide the icon that belongs to the polyline
    routePath.HideIcon();
    
    //make the route line red and semi transparent
    routePath.SetLineColor(new VEColor(255, 199, 65, 1));
    routePath.SetLineWidth(3);
    
    //Add the polyline to the pathLayer
    pathLayer.AddShape(routePath);
}

// Function that spawns the modal popup for media player
function showModalContent(partner, language, isUGC, datatypeID, latitude, longitude, routeID) {

    TrackOmniture("Torch Relay", "", "Torch Relay:Map", "", "map");
    
    var routepoint = routePathDataHandler.GetDataByID(routeID);
    var currCity = routepoint.City;
    var currProv = routepoint.Province;
    if (datatypeID == 4) { // story
        jQuery('.jqmWindow').width('450px');
        jQuery('.jqmWindow').height('416px');
        // Ajax call to retrive the stories
        var params = '{"partner":"' + partner + '", "language":"' + language + '", "datatypeID":' + datatypeID + ', "isUGC":' + isUGC + ', "latitude":' + latitude + ', "longitude":'+ longitude +'}';
        jQuery.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "WebServices/OlympicTorchServices.asmx/GetRoutePointStories", // WebMethod
            data: params,
            dataFilter: function(data) {
                var msg = eval('(' + data + ')');
                // If the response has a ".d" top-level property, return what's below that instead.
                if (msg.hasOwnProperty('d'))
                    return msg.d;
                else
                    return msg;
            },
            error: function(xhr, status, error) {
                var err = eval("(" + xhr.responseText + ")");
                jQuery('.statusmessage').html(err.Message).css('color', 'red').show();
            },
            success: function(msg, status) {
                if (msg != null) {
                    // Construct the modal's content with stories
                    var storyArray = [];
                    if (!isUGC) { // NON-UGC content
                        storyArray.push('<h2>', resourceTxt.NEWS_STORIES, ' - ', currCity, '</h2>');
                        storyArray.push('<div class="jqmStoryDiv">');
                        jQuery.each(msg, function(i, val) {
                            if (val.ThumbnailUrl != "" && val.ThumbnailUrl != null) {
                                storyArray.push('<div style="padding-bottom:0px; margin-bottom:10px; min-height: 110px;">');
                            } else {
                                storyArray.push('<div style="padding-bottom:0px; margin-bottom: 10px;">');
                            }
                            storyArray.push('<div>');
                            if (val.ThumbnailUrl != "" && val.ThumbnailUrl != null) {
                                storyArray.push('<img class="story_image" alt="" src="', val.ThumbnailUrl, '"/>');
                            }
                            if (val.Title != "" && val.Title != null) {
                                if (val.MediaUrl != null && val.MediaUrl != null) {
                                    storyArray.push('<a class="story_title_link" target="_blank" alt="" href="', val.MediaUrl, '"><span>', val.Title, '</span></a>');
                                } else {
                                    storyArray.push('<span class="story_title_nolink">', val.Title, '</span>');
                                }
                            }
                            if (val.Author != "" && val.Author != null) {
                                storyArray.push('<h6>', val.Author, '</h6>');
                            }
                            if (val.Description != "" && val.Description != null) {
                                storyArray.push('<p> ', val.Description, '</p>');
                            }
                            if (val.MediaUrl != "" && val.MediaUrl != null) {
                                storyArray.push('<a class="story_link" target="_blank" alt="" href="', val.MediaUrl, '" >Read more</a>');
                            }
                            storyArray.push('</div></div>');
                        });
                        storyArray.push('</div>');
                    } else { // UGC content
                        storyArray.push('<h2>', resourceTxt.USER_STORIES, ' - ', currCity, '</h2>');
                        storyArray.push('<div class="jqmStoryDiv">');
                        jQuery.each(msg, function(i, val) {
                            storyArray.push('<div style="padding-bottom:0px; margin-bottom: 10px;">');
                            if (val.Author != "" && val.Author != null) {
                                storyArray.push('<span style="font-weight:bold;font-size:11px;">', val.Author, '</span> - ');
                            }
                            if (val.PublishDate != "" && val.PublishDate != null) {
                                storyArray.push('<span class="story_ugc_datetime">', ConvertUgcDateFormat(val.PublishDate.toString()), '</span>');
                            }
                            if (val.Description != "" && val.Description != null) {
                                storyArray.push('<p> ', val.Description, '</p>');
                            }
                            storyArray.push('</div>');
                        });
                        storyArray.push('</div>');
                    }
                    var storyHTML = storyArray.join('');
                    jQuery('div.jqmMediaPlayer').html(storyHTML).show();
                }
            } // end of success
        });      // end of jQuery.ajax
    } else { // video or photo
        var objectWidth;
        var objectHeight;
        if (datatypeID == 1) { // photo
            jQuery('.jqmWindow').width('604px');
            jQuery('.jqmWindow').height('536px');
            objectWidth = "604";
        } else if (datatypeID == 2) { // video
            jQuery('.jqmWindow').width('595px');
            jQuery('.jqmWindow').height('536px');
            objectWidth = "595";
        }
        
        var mediaPlayer = [];
        if (!isUGC) {
            if (datatypeID == 1) {// Photo
                mediaPlayer.push('<h2>', resourceTxt.NEWS_PHOTOS, ' - ', currCity, '</h2>');
            } else if (datatypeID == 2) { // Video
                mediaPlayer.push('<h2>', resourceTxt.NEWS_VIDEOS, ' - ', currCity, '</h2>');
            }
            else {
                mediaPlayer.push('');
            }
        } else {
            if (datatypeID == 1) { // Photo
                mediaPlayer.push('<h2>', resourceTxt.USER_PHOTOS, ' - ', currCity, '</h2>');
            } else if (datatypeID == 2) { // Video
                mediaPlayer.push('<h2>', resourceTxt.USER_VIDEO, ' - ', currCity, '</h2>');
            } else {
                mediaPlayer.push('');    
            }
        }
        mediaPlayer.push('<div class="silverlightControlHost">');
        mediaPlayer.push('<object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="',objectWidth,'" height="510px" style="text-align:center;">');
        mediaPlayer.push('<param name="source" value="', hosturl, 'ClientBin/CTV.OlympicTorch.MediaPlayer.xap"/>');
        mediaPlayer.push('<param name="onError" value="onSilverlightError" />');
        mediaPlayer.push('<param name="background" value="white" />');
        mediaPlayer.push('<param name="minRuntimeVersion" value="3.0.40624.0" />');
        mediaPlayer.push('<param name="autoUpgrade" value="true" />');
        mediaPlayer.push('<param name="initParams" value="partner=', partner.toString().toLowerCase(), ',language=', language.toString().toLowerCase(), ',latitude=', latitude, ',longitude=', longitude, ',datatypeID=', datatypeID, ',isUGC= ', isUGC, '" />');
        mediaPlayer.push('<a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40624.0" style="text-decoration:none">');
        mediaPlayer.push('<img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style:none"/>');
        mediaPlayer.push('</a></object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe></div>');
        var mediaPlayerHTML = mediaPlayer.join('');
        jQuery('div.jqmMediaPlayer').html(mediaPlayerHTML).show();
    }

    jQuery('a.jqModal').trigger('click');
}

function ConvertUgcDateFormat(dFormat) {
    var dateFormat = dFormat.substring(6, dFormat.length - 2);
    var d = new Date();
    d.setTime(parseInt(dateFormat));
    return d.toLocaleDateString() + ' | ' + d.toLocaleTimeString();
}

/*********************
 Mouse Event Handlers
**********************/
function MouseOverHandler(e) {
    // NOTE: returning true to prevent the default mouseover event to happen
    return true;
}

function MouseClickHandler(e) {
    if (e.elementID != null) {
       // map.HideInfoBox();
        try {
            var shape = map.GetShapeByID(e.elementID);

            if (shape != null && shape.GetType() == VEShapeType.Pushpin) {
                RequestInfoboxContent(shape);
                //map.ShowInfoBox(shape);
                return true;
            }
        } catch (ex) { }       
    }
}

//Bug fix for Firefox 3.5 and the mouse scroll wheel
function WindowMouseWheelHandler(e) {
    e.stopPropagation();
    e.preventDefault();
    e.cancelBubble = false;
    return false;
}

/***********
UI handlers
***********/

function initializedropDowns() {
    //Fill the route day drop down box
    var dates = routePathDataHandler.GetDates();

    var dateDD = document.getElementById('routeDayDD');
    dateDD.options[0] = new Option('- ' + resourceTxt.DAY + ' -', 0);

    for (var i = 1; i <= dates.length; i++) {
        var date = DateMonthLocalization(dates[i - 1]);
        dateDD.options[i] = new Option(resourceTxt.DAY + ' ' + i + ', ' + date, i);
    }

    //Sort Provinces by Name
    provinces.sort(SortByName);
   
    var provinceDD = document.getElementById('provinceDD');
    provinceDD.options[0] = new Option('- ' + resourceTxt.PROVINCE_TERRITORY + ' -', '');

    for (var i = 0; i < provinces.length; i++) {
        provinceDD.options[i+1] = new Option(provinces[i].Name, provinces[i].ID);
    }
    
    var cityDD = document.getElementById('cityDD');
    cityDD.options[0] = new Option('- ' + resourceTxt.COMMUNITY + ' -', '');
}

function DayDropDownChange() {
    jQuery('#provinceDD').val("");
    jQuery('#cityDD').val("");

    var dateDD = document.getElementById('routeDayDD');
    var day = parseInt(dateDD.options[dateDD.selectedIndex].value);
    
    routeDayLayer.DeleteAllShapes();

    if (day != 0) {
        var points = routePathDataHandler.GetPointsByVisitDay(day);

        if (points.length > 1) {
            var line = new VEShape(VEShapeType.Polyline, points);
            line.HideIcon();
            line.SetLineColor(new VEColor(0, 32, 224, 1));
            line.SetLineWidth(3);
            routeDayLayer.AddShape(line);
        }
        map.SetMapView(points);
    } else {
        map.SetCenterAndZoom(new VELatLong(58,-95), 4);
    }

    TrackOmniture("Torch Relay","","Torch Relay:Map", "", "map");
}

function ProvinceDropDownChange() {
    jQuery('#routeDayDD').val("0");
    routeDayLayer.DeleteAllShapes();

    var provinceDD = document.getElementById('provinceDD');
    var province = provinceDD.options[provinceDD.selectedIndex].value;

    var cityDD = document.getElementById('cityDD');
    cityDD.selectedIndex = 0;

    var j = cityDD.options.length - 1;
    if (j >= 0) {
        do {
            cityDD.options[j] = null;
        } while (j--);
    }

    cityDD.options[0] = new Option('- ' + resourceTxt.COMMUNITY + ' -', '');

    ZoomToProvince(province);

    TrackOmniture("Torch Relay", "", "Torch Relay:Map", "", "map");
}

function ZoomToProvince(province) {
    if (province != "") {
        var cityDD = document.getElementById('cityDD');
        var cities = routePathDataHandler.GetCommunitiesByProvince(province);
        for (var i = 0; i < cities.length; i++) {
            cityDD.options[i + 1] = new Option(cities[i], cities[i]);
        }

        for (var i = 0; i < provinces.length; i++) {
            if (provinces[i].ID == province) {
                map.SetCenterAndZoom(provinces[i].LatLong, provinces[i].Zoom);
                break;
            }
        }
    } else {
        map.SetCenterAndZoom(new VELatLong(58, -95), 4);
    }   
}

function CommunityDropDownChange() {

    TrackOmniture("Torch Relay", "", "Torch Relay:Map", "", "map");
    
    jQuery('#routeDayDD').val("0");
    
    var cityDD = document.getElementById('cityDD');
    var provinceDD = document.getElementById('provinceDD');
    var city = cityDD.options[cityDD.selectedIndex].value;

    if (city != '') {
        var province = provinceDD.options[provinceDD.selectedIndex].value;

        if (province != '') {
            var location = routePathDataHandler.GetDataByCityAndProvince(city, province);

            if (location != null) {
                map.SetCenterAndZoom(location.LatLong, 12);
            }
        }
    } else {
        ZoomToProvince(jQuery('#provinceDD').val());
    }
}

/**********
Utilities
**********/
//Sorts an array of objects by the NAme property
function SortByName(a, b) {
    if (a.Name == b.Name) {
        if (a.Name == b.Name) {
            return 0;
        }
        return (a.Name < b.Name) ? -1 : 1;
    }
    return (a.Name < b.Name) ? -1 : 1;
}

// Function to get URL query parameter by name
function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}

function DeseriazlieDate(dateString) {
    dateString = dateString.substring(1);
    dateString = dateString.substring(0, dateString.indexOf("\/"));
    dateString = "\"\\\/" + dateString + "\\\/\"";
    var date = Sys.Serialization.JavaScriptSerializer.deserialize(dateString);
    return date;
}

function FormatDateTime(datetime) {
    var dateVal = [];
    if (datetime.getDay() == 0) {
        dateVal.push('Sunday ');
    } 
    
    return dateVal.join('');
}

function DateMonthLocalization(date) {
    if (/fr/i.test(languageParam)) {
        for (var i = 0; i < months.length; i++) {
            var re = new RegExp(months[i].EN);
            if (re.test(date)) {
                date = 'le ' + date.split(',')[0].split(' ')[1] + ' ' + date.split(',')[0].split(' ')[0] + ', ' + date.split(',')[1];
                return date.replace(months[i].EN, months[i].FR);
            }
        }
    }

    return date;
}

function TrackOmniture(channel, campaign, subsection, subsection2, contenttype) {
    if (s != null && s != 'undefined') {
        s.eVar1 = subsection;
        s.eVar2 = subsection2;
        s.eVar4 = contenttype;
        s.channel = channel;
        s.campaign = campaign;
        s.t();
    }
    return;
}

function rotateAd(adType) {
    advManager.refresh(null, adType);
}


// BEGIN document.ready
jQuery(document).ready(function() {
    var closeModal = function(hash) {

        hash.w.fadeOut('2000', function() { hash.o.remove(); jQuery('div.jqmMediaPlayer').html(''); });
    }

    var partner = getParameterByName("partner")

    if (partner != '') {
        partnerParam = partner;
    }

    var language = getParameterByName("language");

    if (language != '') {
        languageParam = language;
    }

    var mapWidth = getParameterByName("width");
    var mapHeight = getParameterByName("height");

    if (mapWidth != '' && mapHeight != '') {
        var mapDiv = document.getElementById('myMap');
        var controlPanelDiv = document.getElementById('ControlPanel');

        mapDiv.style.width = parseInt(mapWidth) + "px";
        mapDiv.style.height = parseInt(mapHeight) + "px";

        controlPanelDiv.style.left = (parseInt(mapWidth) - 247) + 'px';
    }

    GetMap();
    jQuery('#dialog').jqm({
        modal: true,
        overlay: 30,
        onHide: closeModal
    });
});
// END document.ready
