﻿/**
Copyright © 2008 Computer Sciences Corporation Denmark (CSC).
All rights reserved. You may not use, copy, modify or transfer this
program or any copy, modification or portion, in whole or in part,
without the explicit written permission of CSC Denmark
**/

//TopCampaign
$(function() {
$('#topCampaign').hide();
    // toggles the slickbox on clicking the noted link
$('#toolbeltfold').click(function() {
    $('#topCampaign').slideToggle(500);
        return false;
    });
});

/* Removes white 'flig' when the width of the windows is less than 1220 px */
jQuery.event.add(window, "load", resizeFrame);
jQuery.event.add(window, "resize", resizeFrame);
function resizeFrame() {
  var h = $(window).height();
  var w = $(window).width();
  $("#toolbeltfold").css('height', (w > 1220) ? 255 : 0);
}


//jquery.check-radio.js
        $(document).ready(function() {

            $('input:checkbox:not([map])').checkbox({ cls: 'moviaCheckbox' });
            $('input[map]:checkbox').checkbox({ cls: 'moviaCheckbox', onChecked: selectMapFilters });
            $('input:radio').checkbox({ cls: 'moviaRadio' });
            $('a.code').each(function() {
                $(this).click(function() {
                    eval($(this).text());
                    return false;
                })
            });
        });

        displayForm = function(elementId) {
            var content = [];
            $('#' + elementId + ' input').each(function() {
                var el = $(this);
                if ((el.attr('type').toLowerCase() == 'radio')) {
                    if (this.checked)
                        content.push([
								'"', el.attr('name'), '": ',
								'value="', (this.value), '"',
								(this.disabled ? ', disabled' : '')
							].join(''));
                }
                else
                    content.push([
							'"', el.attr('name'), '": ',
							(this.checked ? 'checked' : 'not checked'),
							(this.disabled ? ', disabled' : '')
						].join(''));
            });
            alert(content.join('\n'));
        }

        
//Jquery.Rejseplanen.js

$(function() {
    // Supporting function for datepicker mouseover event
    var cal;
    var $this;
    var checkForMouseout = function(event) {
        var el = event.target;
        while (true) {
            if (el == cal) {
                return true;
            } else if (el == document) {
                $this.dpClose();
                return false;
            } else {
                el = $(el).parent()[0];
            }
        }
    };
    $("#grpHome").hide();
    $("#radioSingle").click(function() {
        if ($("input[@id='radioRoundtrip']:checked").val()) {
            $(".group").toggleClass("requestboth");
            $("#labelDepart1").text('Dato:');
            $("#grpHome").hide();
        }
    });
    $("#radioRoundtrip").click(function() {
        if ($("input[@id='radioSingle']:checked").val()) {
            $(".group").toggleClass("requestboth");
            $("#labelDepart1").text('Ud:');
            $("#grpHome").show();
        }
    });
    $("#radio0Afgang").click(function() {
        if ($("input[@id='radio0Ankomst']:checked").val()) {
            $(".group").toggleClass("REQ0HafasSearchForw");
        }
    });
    $("#radio0Ankomst").click(function() {
        if ($("input[@id='radio0Afgang']:checked").val()) {
            $(".group").toggleClass("REQ0HafasSearchForw");
        }
    });
    $("#radio1Afgang").click(function() {
        if ($("input[@id='radio1Ankomst']:checked").val()) {
            $(".group").toggleClass("REQ1HafasSearchForw");
        }
    });
    $("#radio1Ankomst").click(function() {
        if ($("input[@id='radio1Afgang']:checked").val()) {
            $(".group").toggleClass("REQ1HafasSearchForw");
        }
    });
});


//SearchDropDown.js
$(function() {
    $('.movSearch').hide();
    $('#search input').keydown(function() {
        $('#search .movSearch').slideDown(500);
    });
    $('#mainPage .searchLine input').keydown(function() {
        $('#mainPage .movSearch').slideDown(500);
    });
    $('#mainPage .searchLine2 input').keydown(function() {
        $('#mainPage .movSearch').slideDown(500);
    });
    $('input').click(function() {
        // Check for the change
        if (this.value == this.value) {
            this.select();
        }
    });
});


 
/* Code from 1508. For the simple tree node expansion. Customized a bit for movia */
var simpleTreeCollection;
$(document).ready(function() {
    simpleTreeCollection = $('.simpleTree').simpleTree({
        autoclose: true,
        drag: false,
        afterClick: function(node) {
            //alert("text-"+$('span:first',node).text());
        },
        afterDblClick: function(node) {
            //alert("text-"+$('span:first',node).text());
        },
        afterMove: function(destination, source, pos) {
            //alert("destination-"+destination.attr('id')+" source-"+source.attr('id')+" pos-"+pos);
        },
        afterAjax: function() {
            //alert('Loaded');
        },
        animate: true
        //,docToFolderConvert:true
    });
});

$(document).ready(function() {
    // newuser lightbox
    if ($("input[id $= 'ProfileCreated']").val() == "true") {
        $("input[id $= 'ProfileCreated']").val("false");
        $("div[id $= 'basic-modal-content']").modal({ onClose: NewUserModal_close });
    }

    //.LineScheduleV3 <span> click behavior
    $(".LineScheduleV3 ul>li>span").click(function() {
        var url = $(this).attr("href");
        $(location).attr('href', url); ;
    });
    $(".LineScheduleV3 .active").parents("ul").parents("li.folder-close").addClass("folder-open");
    $(".LineScheduleV3 .active").parents("ul").parents("li.folder-close").removeClass("folder-close");
    $(".LineScheduleV3 .active").parents("ul").css("display", "block");

    //Start line-details
    $(".line-details input[id*='generelRadio']").click(function() {
        if (!$(this).is(":checked") && !$(this).is(":disabled")) {
            clearErrorText();
            deactivateDetails();
            activateGenerel();
        }
    });

    $(".line-details input[id*='detailsRadio']").click(function() {
        if (!$(this).is(":checked") && !$(this).is(":disabled")) {
            deactivateGenerel();
            activateDetails();
        }
    });

    $(".line-details a[id*='save']").click(function() {
        return ($(this).checkAll());
    });

    $(".line-details a[id*='Save']").click(function() {
        activateSms();
        return (true);
    });

    $(".line-details select[id*='fromHourSelect']").change(function() {

        var currentNumber = ($(this).getIdPart("2"));
        $(".line-details span[id*='fromHourError-" + currentNumber + "']").css("display", "none"); //Disable fromHour error text
        $(this).disableHours(currentNumber);
    });

    $(".line-details select[id*='toHourSelect']").change(function() {

        var currentNumber = ($(this).getIdPart("2"));
        $(".line-details span[id*='toHourError-" + currentNumber + "']").css("display", "none"); //Disable toHour error text
    });

    $("input[id*='monCheckbox'],input[id*='tueCheckbox'],input[id*='wedCheckbox'],input[id*='thuCheckbox'],input[id*='friCheckbox'],input[id*='satCheckbox'],input[id*='sunCheckbox']", ".line-details").click(function() {

        var currentNumber = ($(this).getIdPart('2'));
        $("span[id*='daysError-" + currentNumber + "']").css("display", "none"); //Disable days error text
    });

    $("input[id*='mail'],input[id*='sms']", ".line-details").click(function() {

        var currentNumber = ($(this).getIdPart('2'));
        $("span[id*='subscriptionError-" + currentNumber + "']").css("display", "none"); //Disable subscription error text
    });

    //Lineinformation - start

    $(".favoriteLine a.changeButton").click(function() {
        return !($("#subscriptionShortUpdateWarning").html().length > 0);
    });

    $(".favoriteLine a.open").click(function() {

        clickedParentElement = $(this).parents(".favoriteLine tr[id*='favoriteLineRow']");

        //close all lineDetails minus this
        $(".favoriteLine tr[id*='lineDetails']").each(function() {
            if ($(this).parents("tr[id*='favoriteLineRow']").attr('id') != clickedParentElement.attr("id")) {
                $(this).css("display", "none");
            }
        });
        $(".favoriteLine a.close").not($(this)).removeClass("close").addClass("open");

        //close all lineChanges
        $(".favoriteLine tr[id*='lineChanges']").css("display", "none");


        //toggle this and the related lineDetails
        $(this).toggleClass("open");
        $(this).toggleClass("close");
        $("tr[id*='lineDetails']", $(this).parents("tr[id*='favoriteLineRow']")).toggle();
    });

    $(".favoriteLine a.attention").click(function() {

        clickedParentElement = $(this).parents("tr[id*='favoriteLineRow']");

        //close all lineChanges minus this
        $(".favoriteLine tr[id*='lineChanges']").each(function() {
            if ($(this).parents("tr[id*='favoriteLineRow']").attr("id") != clickedParentElement.attr("id")) {
                $(this).css("display", "none");
            }
        });

        //close all lineDetails
        $(".favoriteLine tr[id*='lineDetails']").css("display", "none");
        $(".favoriteLine a.close").removeClass("close").addClass("open");

        //toggle related lineChanges
        $("tr[id*='lineChanges']", $(this).parents("tr[id*='favoriteLineRow']")).toggle();
    });

    //Lineinformation - end


    $(window).load(function() {

        //Lineinformation - start
        $(".favoriteLine tr[id*='lineDetails']").css("display", "none");
        $(".favoriteLine tr[id*='lineChanges']").css("display", "none");

        if ($("#favoriteLineError").length > 0 && $("#favoriteLineError").html().length > 0) {
            $(".favoriteLine a.changeButton").addClass("disabled");
        }

        if ($("#subscriptionShortUpdateWarning").length > 0 && $("#subscriptionShortUpdateWarning").html().length > 0) {
            var ajaxCount = 0;
            $(".favoriteLine a.changeButton").addClass("disabled");
            //require subscriptionstatus up to 6 times with 5 sek. delay while locked
            GetSubscriptionStatus(ajaxCount, "#subscriptionShortUpdateWarning", ".lineinformation");
        }
        //Lineinformation - end

        if ($(".line-details input[name*='detailsLineInformation']:checked").length > 0) {
            var radio = $(".line-details input[name*='detailsLineInformation']:checked").val()
            if (radio.indexOf("detailsRadio") == -1) {
                deactivateDetails();
                activateGenerel();
            }
            else {
                deactivateGenerel();
                activateDetails();
            }
        }

        $(".line-details select[id*='fromHourSelect']").each(function() {
            var currentNumber = ($(this).getIdPart("2"));
            $(this).disableHours(currentNumber);
        })

        if ($("#lineDetailsError").length > 0 && $("#lineDetailsError").html().length > 0) {
            $(".line-details input:radio").attr("disabled", "disabled");  //Disable radio buttons
            deactivateGenerel();
            deactivateDetails();
        }

        if ($("#line-details-modal-content").length > 0 && $("#line-details-modal-content").html().length > 0) {
            $("#subscriptionUpdateWarning").hide();
            $("#line-details-modal-content").modal();
            $("a.modalCloseImg").hide();
        }
        else {
            if ($("#subscriptionUpdateWarning").length > 0 && $("#subscriptionUpdateWarning").html().length > 0) {
                $(".line-details input:radio").attr("disabled", "disabled");  //Disable radio buttons
                deactivateGenerel();
                deactivateDetails();
                var ajaxCount = 0;
                //require subscriptionstatus up to 6 times with 5 sek. delay while locked
                GetSubscriptionStatus(ajaxCount, "#subscriptionUpdateWarning", ".line-details");
            }
        }
    });
    //End line-details
});

$(document).ready(function() {
    // Handling Flash. Firefox needs 2 pixels bigger size
    if ($.browser.mozilla) {
        $('div.EmbedFlash').find('embed').each(function() {
            var current_height = $(this).attr('height');
            var new_height = $(this).attr('height').replace(current_height, (parseInt(current_height)
+ 2) + '');
            var current_width = $(this).attr('width');
            var new_width = $(this).attr('width').replace(current_width, (parseInt(current_width) + 2)
+ '');
            $(this).attr('height', new_height);
            $(this).attr('width', new_width);
        });
    }
});




function pageLoad(sender, args) {

    $(".line-details select[id*='fromSelect']").each(function() {
        var currentNumber = ($(this).getIdPart("2"));
        $(this).disableStops(currentNumber);
    })

    $(".line-details select[id*='fromSelect']").change(function() {

        var currentNumber = ($(this).getIdPart("2"));
        $(".line-details span[id*='fromError-" + currentNumber + "']").css("display", "none"); //Disable from error text
        $(this).disableStops(currentNumber);
    });

    $(".line-details select[id*='toSelect']").change(function() {

        var currentNumber = ($(this).getIdPart("2"));
        $(".line-details span[id*='toError-" + currentNumber + "']").css("display", "none"); //Disable to error text
    });
    
    //if pageload after updatepanel update
    if (args.get_isPartialLoad()) {

        $(".line-details span.moviaValidation_216").css("display", "none");
        $(".line-details span.moviaValidation_187").css("display", "none");
    }
}

// close newuser lightbox
function NewUserModal_close() {
    var url = $("div[id $= 'basic-modal-content']").attr("href");
    $(location).attr("href", url);
    $.modal.close(); // must call this!
}

//Start line-details
jQuery.fn.getIdPart = function(partNumber) {
    var currentId = $(this).attr("id");
    var splitId = currentId.split("-");
    if (splitId.length > 1) {
        if (partNumber == "1") return splitId[0];
        if (partNumber == "2") return splitId[1];
        return "xx";
    }
    else {
        return "xx";
    }
}

jQuery.fn.disableStops = function(currentNumber) {

    var fromIndex = $(this).val();
    var toIndex = $(".line-details select[id*='toSelect-" + currentNumber + "']").val();
    if (toIndex < fromIndex) {
        $(".line-details select[id*='toSelect-" + currentNumber + "']").val("00#default");  //clear selected index
    }
    $("option", ".line-details select[id*='toSelect-" + currentNumber + "']").each(function() {
        if (fromIndex > $(this).val() && $(this).val() > "00#default") {
            $(this).attr("disabled", "disabled"); //Disable option  
        }
        else {
            $(this).removeAttr("disabled");      //Enable option   
        }
    })
    $(".line-details select[id*='toSelect-" + currentNumber + "']").ieLessThan8OptionDisable();
}

jQuery.fn.disableHours = function(currentNumber) {

    var fromIndex = $(this).val();
    var toIndex = $(".line-details select[id*='toHourSelect-" + currentNumber + "']").val();
    if (toIndex <= fromIndex) {
        $(".line-details select[id*='toHourSelect-" + currentNumber + "']").val("00");  //clear selected index
    }
    $("option", ".line-details select[id*='toHourSelect-" + currentNumber + "']").each(function() {
        if (fromIndex >= $(this).val() && $(this).val() > "00") {
            $(this).attr("disabled", "disabled"); //Disable option  
        }
        else {
            $(this).removeAttr("disabled");      //Enable option   
        }
    })
    $(".line-details select[id*='toHourSelect-" + currentNumber + "']").ieLessThan8OptionDisable();
}

jQuery.fn.ieLessThan8OptionDisable = function() {
    if ($.browser.msie && parseFloat($.browser.version) < 8) {
        $(this).find("option").css("color", "#000");
        $(this).find("[disabled]").css("color", "graytext").removeAttr("disabled");
        $(this).change(function() {
            var selected = $(this).val();
            var disabled = $(this).find("[value=" + selected + "]").hasCss("color", "graytext");
            if (disabled) {
                $(this).find("option:first").attr("selected", "selected");
            }
        });
    }
}

function clearErrorText() {

    $(".line-details span.moviaValidation_216").css("display", "none");
    $(".line-details span.moviaValidation_187").css("display", "none");
    $(".line-details span.moviaValidationUpsideDown_216").css("display", "none");
    $(".line-details span.moviaValidationUpsideDown_78").css("display", "none");
    $(".line-details span.moviaValidationUpsideDown_53").css("display", "none");
}

jQuery.fn.checkAll = function() {
    var noErrors = true;

    var currentNumber = $(this).getIdPart("2");
    if ($(".line-details select[id*='directionSelect-" + currentNumber + "']").val() == "00#default") {
        $(".line-details span[id*='directionError-" + currentNumber + "']").css("display", "block");
        noErrors = false;
    }
    else {
        $(".line-details span[id*='directionError-" + currentNumber + "']").css("display", "none");
    }

    if ($(".line-details select[id*='fromSelect-" + currentNumber + "']").val() == "00#default") {
        $(".line-details span[id*='fromError-" + currentNumber + "']").css("display", "block");
        noErrors = false;
    }
    else {
        $(".line-details span[id*='fromError-" + currentNumber + "']").css("display", "none");
    }

    if ($(".line-details select[id*='toSelect-" + currentNumber + "']").val() == "00#default") {
        $(".line-details span[id*='toError-" + currentNumber + "']").css("display", "block");
        noErrors = false;
    }
    else {
        $(".line-details span[id*='toError-" + currentNumber + "']").css("display", "none");
    }

    if ($(".line-details select[id*='fromHourSelect-" + currentNumber + "']").val() == "00") {
        $(".line-details span[id*='fromHourError-" + currentNumber + "']").css("display", "block");
        noErrors = false;
    }
    else {
        $(".line-details span[id*='fromHourError-" + currentNumber + "']").css("display", "none");
    }

    if ($(".line-details select[id*='toHourSelect-" + currentNumber + "']").val() == "00") {
        $(".line-details span[id*='toHourError-" + currentNumber + "']").css("display", "block");
        noErrors = false;
    }
    else {
        $(".line-details span[id*='toHourError-" + currentNumber + "']").css("display", "none");
    }

    if ($(".line-details input[id*='monCheckbox-" + currentNumber + "']:checked").val() == null &&
        $(".line-details input[id*='tueCheckbox-" + currentNumber + "']:checked").val() == null &&
        $(".line-details input[id*='wedCheckbox-" + currentNumber + "']:checked").val() == null &&
        $(".line-details input[id*='thuCheckbox-" + currentNumber + "']:checked").val() == null &&
        $(".line-details input[id*='friCheckbox-" + currentNumber + "']:checked").val() == null &&
        $(".line-details input[id*='satCheckbox-" + currentNumber + "']:checked").val() == null &&
        $(".line-details input[id*='sunCheckbox-" + currentNumber + "']:checked").val() == null) {

        $(".line-details span[id*='daysError-" + currentNumber + "']").css("display", "block");
        noErrors = false;
    }
    else {
        $(".line-details span[id*='daysError-" + currentNumber + "']").css("display", "none");
    }
    
    if ($(".line-details input[id*='mail-" + currentNumber + "']:checked").val() == null &&
        $(".line-details input[id*='sms-" + currentNumber + "']:checked").val() == null) {

        $(".line-details span[id*='subscriptionError-" + currentNumber + "']").css("display", "block");
        noErrors = false;
    }
    else {
        $(".line-details span[id*='subscriptionError-" + currentNumber + "']").css("display", "none");
    }
    
    if (noErrors) activateSms();
    
    return noErrors;
}

function activateGenerel() {

    $("label", "#generelLine").removeClass("disabled");
    $("input:checkbox", "#generelLine").removeAttr("disabled");             //Enable checkbox
    $("a.button", "#generelLine").css("display", "block");                  //Enable link
    $("span.button", "#generelLine").css("display", "none");                //Disable span link
    deactivateSms();
}

function deactivateGenerel() {

    $("label", "#generelLine").addClass("disabled");
    $("input:checkbox", "#generelLine").attr("disabled", "disabled");       //Disable checkbox
    $("a.button", "#generelLine").css("display", "none");                   //Disable link
    $("span.button", "#generelLine").css("display", "block");               //Enable span link
}

function activateDetails() {

    $("label,h2", "#detailsLine").removeClass("disabled");
    $("input:checkbox,select", "#detailsLine").removeAttr("disabled");      //Enable checkbox and select
    $("a.button", "#detailsLine").css("display", "block");                  //Enable link
    $("span.button", "#detailsLine").css("display", "none");                //Disable span link
    deactivateNewDetails();
    deactivateSms();
}

function deactivateDetails() {

    $("label,h2", "#detailsLine").addClass("disabled");
    $("input:checkbox,select", "#detailsLine").attr("disabled", "disabled"); //Disable checkbox and select
    $("a.button", "#detailsLine").css("display", "none");                   //Hide link
    $("span.button", "#detailsLine").css("display", "block");               //Enable span link
}

function deactivateSms() {

    if ($("#customerMobile",".line-details").length > 0 && $("#customerMobile",".line-details").html().length == 0) {
        $("input[id*='Sms'],input[id*='sms-']", ".line-details").attr("disabled", "disabled"); //Disable sms checkbox
    }
}

function activateSms() {

    if ($("#customerMobile",".line-details").length > 0 && $("#customerMobile",".line-details").html().length == 0) {
        $("input[id*='Sms'],input[id*='sms-']", ".line-details").removeAttr("disabled"); //enable sms checkbox
    }
}

function deactivateNewDetails() {

    if ($("#maxDetails", ".line-details").length > 0 && $("#maxDetails", ".line-details").html().length != 0) {
        if ($(".line-details a[id*='save-']").length > ($("#maxDetails", ".line-details").html())) {
            $(".line-details label[id*='-00']").addClass("disabled");
            $(".line-details input[id*='-00'],.line-details select[id*='-00']").attr("disabled", "disabled");   //Disable checkbox og select in newDetails
            $(".line-details a[id*='-00']").css("display", "none");                               //Hide link
            $(".line-details span[id*='saveLabel-00']").css("display", "block");                  //Enable span link
        }
    }
}

jQuery.fn.hasCss = function(prop, val) {
    return $(this).css(prop.toLowerCase()) == val.toLowerCase();
}

function GetSubscriptionStatus(ajaxCount, warningId, locationClass) {
    setTimeout(function() {
        if (ajaxCount++ < 6) {
            $(warningId).append("  .");
            $.get("/_layouts/mymoviaajax.aspx?getSubscriptionStatus=" + $("#customerId", locationClass).html(), function(response) {
                if (response.length && response == "True") {
                    ajaxCount = 6;
                    location.reload();      //reload page
                }
            });
            GetSubscriptionStatus(ajaxCount, warningId, locationClass);
        }
    }, 5000);
}

//End line-details

/* MAP FILTERS */

function selectFavoriteLineFilters() {
    $("input[id*='col4Filter']").attr("checked", "checked");
}

function deselectFavoriteLineFilters() {
    $("input[id*='col4Filter00']").next().removeClass("moviaCheckbox-some_selected");
    $("input[id*='col4Filter']").removeAttr("checked");
}

// selectMapFilters is called from jquery.checkbox.js
function selectMapFilters(obj) {
    if (obj.id.substring(obj.id.length - 2) == "00")  //select all filter
        selectAllMapFilters(obj);
    else
        selectSingleMapFilter(obj);
}

function selectAllMapFilters(obj) {
    var selectId = obj.id;
    if (obj.id.length > 2)
        selectId = obj.id.substring(0, obj.id.length - 2);
    if (obj.checked) {
        $("input[id*='" + selectId + "']").attr("checked", "checked");
    }
    else {
        $("input[id*='" + selectId + "']").removeAttr("checked");
    }

    $(obj).next().removeClass("moviaCheckbox-some_selected");
    selectSingleMapFilter(obj);
}

function selectSingleMapFilter(obj) {
    var lines = "";
    var selectId = obj.id;
    if (obj.id.length > 2)
        selectId = obj.id.substring(0, obj.id.length - 2);
    $("input[id*='" + selectId + "']:checked").each(function () {
        if ($(this).val() != "all") {
            if (lines.length > 0)
                lines += ",";
            lines += $(this).val();
        }
    });
    if ($(".select_one:checked").length == 0) {
        $("input[id*='" + selectId + "00']").removeAttr("checked");
        $("input[id*='" + selectId + "00']").next().removeClass("moviaCheckbox-some_selected");
    }
    else if ($(".select_one:not(:checked)").length == 0) {
        $("input[id*='" + selectId + "00']").attr("checked", "checked");
        $("input[id*='" + selectId + "00']").next().removeClass("moviaCheckbox-some_selected");
    }
    else {
        $("input[id*='" + selectId + "00']").removeAttr("checked");
        $("input[id*='" + selectId + "00']").next().addClass("moviaCheckbox-some_selected");
    }
    var options = { 'favoriteLines': lines };
    $("#" + globalMap.mapElm).mapUtility("drawMap", options);
}

/* GLOBAL MAP VARIABLES */

var globalMap = {
    baseMapUrl: '',
    busMapUrl: '',
    productTypes: [],
    productColors: [],
    defaultProductColor: '',
    lineQueryKey: '',
    queryStringLines: '',
    favoriteLines: '',
    lastSearchedLines: '',
    selectedLine: '',
    showAllLines: false,
    mapElm: 'map',
    map: undefined,
    busLayer: undefined,
    featureLineLayer: undefined,
    busLayerDefinition: [],
    lineQueryTask: undefined,
    lineQuery: undefined,
    identifyTask: undefined,
    identifyParams: undefined,
    scheduleUrl: '',
    favoriteStopUrl: '',
    timeout: 5000,
    depTimer: undefined,
    togUrl: '',
    stogUrl: '',
    metroUrl: '',
    ajaxLineGid: '',
    ajaxDirectionGid: '',
    restApiUrl: ''
};

var startExtent = new esri.geometry.Extent({ 'xmin': 483468.083343027, 'ymin': 6020661.1896496, 'xmax': 904950.176307213, 'ymax': 6263549.17542557, 'spatialReference': { 'wkid': 25832} });

/*MAP FUNCTIONS - START */

(function ($) {

    $.fn.mapUtility = function (action, options) {

        var hasZoomed = false;

        if (!globalMap) return;

        // Extend globalMap variables with options
        globalMap = $.extend(globalMap, options);

        if (options && options.showAllLines) {
            globalMap.queryStringLines = "";
            deselectFavoriteLineFilters();
            globalMap.favoriteLines = "";
            globalMap.lastSearchedLines = "";
            globalMap.selectedLine = "";
            if (globalMap.map && globalMap.map.graphics)
                globalMap.map.graphics.clear();
        }
        if (options && options.queryStringLines && options.queryStringLines.length > 0) {
            globalMap.showAllLines = false;
            deselectFavoriteLineFilters();
            globalMap.favoriteLines = "";
            globalMap.lastSearchedLines = "";
            globalMap.selectedLine = "";
            if (globalMap.map && globalMap.map.graphics)
                globalMap.map.graphics.clear();
        }
        if (options && options.favoriteLines && options.favoriteLines.length > 0) {
            globalMap.showAllLines = false;
            globalMap.lastSearchedLines = "";
            globalMap.selectedLine = "";
            if (globalMap.map && globalMap.map.graphics)
                globalMap.map.graphics.clear();
        }

        return this.each(function () {

            switch (action) {
                case ("initMap"):
                    initMap();
                    break;
                case ("drawMap"):
                    drawMap();
                    break;
                case ("extendMap"):
                    extendMap();
                    break;
                default:
                    /* do nothing */
                    break;
            }

            // Initialize map
            function initMap() {
                globalMap.map = new esri.Map(globalMap.mapElm, { extent: startExtent });

                dojo.connect(globalMap.map, "onUpdateEnd", mapUpdateEnd);
//                dojo.connect(globalMap.map, "onUpdateStart", mapUpdateStart);
                dojo.connect(globalMap.map, "onLoad", mapLoad);

                addBaseLayer();
                addDynamicBusLayer();
                defineQueryLineTask();
                defineIdentifyTask();

                dojo.connect(globalMap.map, "onClick", doIdentify);
                dojo.connect(globalMap.map, "onZoomEnd", mapZoomEnd);
                dojo.connect(globalMap.map.infoWindow, "onHide", hidePopup);
                dojo.connect(globalMap.map.infoWindow, "onShow", showPopup);

                //          globalMap.queryStringLines = getQueryStringVariable(globalMap.lineQueryKey);
                var lines = getInitLinesToShow();
                globalMap.busLayerDefinition = getBusLayerDefinition(lines);
                setBusLayerDefinition(globalMap.busLayerDefinition, true);
                setLinesExtent(globalMap.busLayerDefinition[2]);

                return false;

            };

            function mapUpdateEnd() {
                // close infowindow if user has zoomed and maplevel is less than 5
                if (hasZoomed) {
                    hasZoomed = false;
                    if (globalMap.map.infoWindow && globalMap.map.infoWindow.isShowing) {
                        globalMap.map.infoWindow.hide();
                    }
                }
            }

//            function mapUpdateStart() {
//                // show loading graphic
//                esri.show(loading);
//            }

            function mapLoad(map) {
                dojo.connect($("#" + globalMap.mapElm).get(0), "resize", resizeMap);
                $("#dijit_form_VerticalRule_0").css("width", "0px");
                $("#dijit_form_VerticalRule_0 .dijitRuleMarkV").css("width", "8px");
            }

            function mapZoomEnd(extent, zoomFactor, anchor, level) {
                hasZoomed = true;   // user has zoomed
            }

            function showPopup() {
                var selectedTab;

                // set popup size based on number of tabs
                var tabs = $("#tabs div");
                if (tabs.length > 12) {
                    var popupWidth = (tabs.length / 2) * 45
                    globalMap.map.infoWindow.resize(popupWidth, 293);
                }
                else
                    globalMap.map.infoWindow.resize(280, 293);

                // set popup selected tab based on lines drawn on map
                var linesOnMap = $("#tabs div.lineOnMap");
                if (linesOnMap.length > 0) 
                    selectedTab = linesOnMap[0];
                else
                    selectedTab = $("#tabs div:first")[0];
                if (selectedTab != null)
                    popUpTabSelected(selectedTab);
            }

            function hidePopup () {
                // clear getDeparturesForLine timer
                if (globalMap.depTimer != null) {
                    clearInterval(globalMap.depTimer);
                    globalMap.depTimer = null;
                }
            }

            function showStop(feature) {
                feature.setSymbol(new esri.symbol.PictureMarkerSymbol('/_layouts/images/MoviaImagesV3/movia_map_selected.png', 20, 20));
                globalMap.map.graphics.add(feature);
            }

            function drawMap() {

                // close infowindow
                if (globalMap.map.infoWindow && globalMap.map.infoWindow.isShowing) {
                    globalMap.map.infoWindow.hide();
                }

                if (globalMap.selectedLine.length > 0) {
                    addFeatureLayers();
                }
                else {
                    if (globalMap.featureLineLayer) {
                        globalMap.map.removeLayer(globalMap.featureLineLayer);
                        globalMap.featureLineLayer = null;
                    }
                    globalMap.map.graphics.clear();
                }

                var lines = getLinesToShow();
                globalMap.busLayerDefinition = getBusLayerDefinition(lines);
                if (globalMap.selectedLine.length > 0) {
                    setBusLayerDefinition(globalMap.busLayerDefinition, false);
                }
                else {
                    setBusLayerDefinition(globalMap.busLayerDefinition, true);
                    setLinesExtent(globalMap.busLayerDefinition[2]);
                }
                return false;

            };

            // extend map to dobbelt size
            function extendMap() {
                $("#" + globalMap.mapElm).css("height", $("#" + globalMap.mapElm).height() * 2);
                //          $("#mapLoading").css("top", $("#" + globalMap.mapElm).height() / 2 - 16);
                //          $("#mapLoading").css("left", $("#" + globalMap.mapElm).width() / 2 - 16);
                // recenter if start zoom
                if (globalMap.map.getLevel() == 0) {
                    setExtentAndCenter(startExtent);
                }
                // globalMap.map.reposition();
                globalMap.map.resize();
            }

            // add base map layer
            function addBaseLayer() {
                var basemap = new esri.layers.ArcGISTiledMapServiceLayer(globalMap.baseMapUrl);
                globalMap.map.addLayer(basemap);
            }

            // Define dynamic bus map layer
            function addDynamicBusLayer() {
              var imageParameters = new esri.layers.ImageParameters();

              var layerDefs = [];
              layerDefs[0] = "-1";  // stops
              layerDefs[1] = "";    // stations
              layerDefs[2] = "-1";  // lines
              imageParameters.layerDefinitions = layerDefs;

              imageParameters.layerIds = [0, 1, 2];
              imageParameters.layerOption = esri.layers.ImageParameters.LAYER_OPTION_SHOW;
              imageParameters.transparent = true;

              globalMap.busLayer = new esri.layers.ArcGISDynamicMapServiceLayer(globalMap.busMapUrl, { "imageParameters": imageParameters });
              globalMap.map.addLayer(globalMap.busLayer);

            }

            function addFeatureLayers() {
                if (!globalMap.featureLineLayer) {
                    globalMap.featureLineLayer = new esri.layers.FeatureLayer(globalMap.busMapUrl + "/2", {
                        mode: esri.layers.FeatureLayer.MODE_ONDEMAND,
                        outFields: ["LineGid"],
                        visible: true
                    });
                    var busSelectionSymbol = new esri.symbol.SimpleLineSymbol("solid", new dojo.Color("#329cfd"), 3); 
                    var renderer = new esri.renderer.SimpleRenderer(busSelectionSymbol);
                    globalMap.featureLineLayer.setRenderer(renderer);

                    globalMap.map.addLayer(globalMap.featureLineLayer);
                }
                setLineFeatureLayer("DirectionGid='" + globalMap.selectedLine + "'");
            }

            function setLineFeatureLayer(definitionExpression) {
                globalMap.featureLineLayer.setDefinitionExpression(definitionExpression);

            }

            // Define line querytask
            function defineQueryLineTask() {

                //build query task 
                globalMap.lineQueryTask = new esri.tasks.QueryTask(globalMap.busMapUrl + "/2");

                //build query filter 
                globalMap.lineQuery = new esri.tasks.Query();
                globalMap.lineQuery.outSpatialReference = globalMap.map.spatialReference;
                globalMap.lineQuery.returnGeometry = true;
                globalMap.lineQuery.outFields = ["LineGid"];
            }

            // Define line and stop identify task
            function defineIdentifyTask() {

                //build identify task
                globalMap.identifyTask = new esri.tasks.IdentifyTask(globalMap.busMapUrl);

                //build identify parameters
                globalMap.identifyParams = new esri.tasks.IdentifyParameters();
                globalMap.identifyParams.tolerance = 9;
                globalMap.identifyParams.returnGeometry = true;
                globalMap.identifyParams.layerIds = [0, 1];
                globalMap.identifyParams.layerOption = esri.tasks.IdentifyParameters.LAYER_OPTION_VISIBLE;
            }

            // Return initial map lines querystring
            function getInitLinesToShow() {

                var lines = [];
                if (globalMap.queryStringLines.length > 0) {
                    lines = globalMap.queryStringLines.split(",");
                }
                else if (globalMap.favoriteLines.length > 0) {
                    selectFavoriteLineFilters();
                    lines = globalMap.favoriteLines.split(",");
                }
                else if (globalMap.lastSearchedLines.length > 0) {
                    lines = globalMap.lastSearchedLines.split(",");
                }

                return lines;
            }

            // Return map lines querystring
            function getLinesToShow() {

                var lines = [];
                if (globalMap.queryStringLines.length > 0) {
                    lines = globalMap.queryStringLines.split(",");
                }
                if (globalMap.favoriteLines.length > 0) {
                    var fLines = globalMap.favoriteLines.split(",");
                    for (i = 0; i < fLines.length; i++) {
                        if ($.inArray(fLines[i], lines) == -1)  // not in queryStringLines
                            lines.push(fLines[i]);
                    }
                }
                if (globalMap.lastSearchedLines.length > 0) {
                    lines = globalMap.lastSearchedLines.split(",");
                }

                return lines;
            }

            // Return buslayerdefinition
            function getBusLayerDefinition(lines) {

                var lineQueryString = "";
                var stopQueryString = "";
                var layerDefs = [];

                layerDefs[1] = "";  // show all stations

                if (lines && lines.length > 0) {
                    for (var i = 0; i < lines.length; i++) {
                        if (i > 0) {
                            stopQueryString += " or ";
                            lineQueryString += ",";
                        }
                        stopQueryString += "LineGidList LIKE '%" + lines[i] + "%'";
                        lineQueryString += "'" + lines[i] + "'";
                    }
                    lineQueryString = "LineGid IN (" + lineQueryString + ")";
                    if (globalMap.selectedLine.length > 0) {
                        stopQueryString += " or DirectionGidList LIKE '%" + globalMap.selectedLine + "%'";
                        lineQueryString += " or DirectionGid='" + globalMap.selectedLine + "'";
                    }
                }
                else {
                    //  show all stops and lines
                    stopQueryString = "";
                    lineQueryString = "";
                }

                layerDefs[0] = stopQueryString;
                layerDefs[2] = lineQueryString;

                return layerDefs;
            }

            // Set Buslayer definition
            function setBusLayerDefinition(layerDefs, setZoom) {
                var doNotRefresh = setZoom;
                globalMap.busLayer.setLayerDefinitions(layerDefs, doNotRefresh);
            }

            // Set map extent
            function setExtentAndCenter(extent) {
                if (extent) {
                    globalMap.map.setExtent(extent, true);
                }
                else {
                    globalMap.map.setExtent(globalMap.map.extent);  //refresh features on map
                }
            }

            // Set map extent based on lines
            function setLinesExtent(lineQueryString) {

                // show no lines
                if (lineQueryString == "-1") {
                    setExtentAndCenter(null);
                    return;
                }
                // show all lines
                if (lineQueryString == "") {
                    setExtentAndCenter(startExtent);
                    return;
                }

                // show selected lines
                globalMap.lineQuery.where = lineQueryString;

                //Execute task and call showResults on completion
                globalMap.lineQueryTask.execute(globalMap.lineQuery, function (fset) {

                    var unionExtent;
                    if (fset.features.length > 0) {

                        var featureExtent;
                        var lineFeature;
                        for (var i = 0; i < fset.features.length; i++) {
                            lineFeature = fset.features[i];
                            featureExtent = lineFeature.geometry.getExtent();
                            if (unionExtent)
                                unionExtent = unionExtent.union(featureExtent);
                            else
                                unionExtent = featureExtent;
                        }

                    }
                    //set extent based on lines in resultset
                    setExtentAndCenter(unionExtent);
                });
            }

            function doIdentify(evt) {
                if (globalMap.map.getLevel() < 5)
                    return;   // do not identify on maplevel less than 5
                globalMap.identifyParams.geometry = evt.mapPoint;
                globalMap.identifyParams.layerDefinitions = globalMap.busLayerDefinition;
                globalMap.identifyParams.mapExtent = globalMap.map.extent;
                globalMap.identifyParams.width = globalMap.map.width;
                globalMap.identifyParams.height = globalMap.map.height;
                globalMap.identifyTask.execute(globalMap.identifyParams, function (idResults) { handleIdentified(idResults, evt); }, function () { alert('Der er sket en fejl og ønskede oplysninger kan ikke vises - prøv igen'); });
            }

            function handleIdentified(idResults, evt) {
                var selectedResult;
                var popUpContent = "";

                if (idResults.length == 0)  //nothing found
                    return;

                // get selected feature from identify results
                selectedResult = getSelectedFeature(idResults);

                if (!selectedResult) //nothing relevant identified
                    return;

                // clear graphics and hide popup
                globalMap.map.graphics.clear();
                globalMap.map.infoWindow.hide();

                switch (selectedResult.featureType) {
                    case ("Stop"):  // show popup with stop
                        showStop(selectedResult.feature);  // show graphic on selected stop
                        var stopPopupData = getStopPopupData(selectedResult.feature);
                        stopPopupData.lines.sort(SortByName);

                        globalMap.map.infoWindow.setTitle("<div class='map-popup-header'>" + stopPopupData.stopName + "</div>");
                        popUpContent = getPopUpContent(stopPopupData);

                        globalMap.map.infoWindow.setContent(popUpContent);

                        globalMap.map.infoWindow.show(evt.screenPoint, globalMap.map.getInfoWindowAnchor(evt.screenPoint)); 
                        break;
                    case ("Tog"):   // navigate to re-tog site
                        window.open(globalMap.togUrl);
                        break;
                    case ("Stog"):  // navigate to s-tog site
                        window.open(globalMap.stogUrl);
                        break;
                    case ("Metro"): // navigate to metro site
                        window.open(globalMap.metroUrl);
                        break;
                    default:
                        /* do nothing */
                        break;
                }
            }

            function getPopUpContent(stopPopupData) {

                var popUpContent = "<div id='tabs' class='map-popup-tabs'>";
                for (var i = 0; i < stopPopupData.lines.length; i++) {
                    popUpContent += getPopUpTab(stopPopupData.lines[i].lineName, stopPopupData.lines[i].productColor, stopPopupData.lines[i].lineOnMap, stopPopupData.lines[i].popupvalues);
                }
                popUpContent += "</div>";

                popUpContent += "      <div class='map-popup-dev-dep-zone'>";
                popUpContent += "        <div class='map-popup-dev-header'><h2>";
                popUpContent += "          <span id='map-popup-dev-header' style='display: none;'>Ændringer<img alt='OBS' src='/_layouts/images/MoviaImagesV3/movia_map_popup_attention.png' width='22' height='19'>";
                popUpContent += "          <a class='moviaChange' href='javascript:void(0)' onclick='javascript:toggleDevDep(this);' title='Åbn'>Åbn</a></span>";
                popUpContent += "        </h2></div>";
                popUpContent += "        <div id='pop-up_changes' class='map-popup-changes' style='display: none;'>";
                popUpContent += "        </div>";

                popUpContent += "        <div id='pop-up_lineinfo' class='map-popup-lineinfo'>";
                popUpContent += "        </div>";
                popUpContent += "    </div>";

                popUpContent += "    <div class='map-popup-bottom'>";
                popUpContent += "      <a class='map-popup-draw' href='#'><img src='/_layouts/images/MoviaImagesV3/movia_map_popup_optegn_rute.png'></a>";
                popUpContent += "      <a class='map-popup-favorite' href='#'><img src='/_layouts/images/MoviaImagesV3/movia_map_popup_gem_som_favorit.png'></a>";
                popUpContent += "      <a class='map-popup-schedule' 'href='#'><img src='/_layouts/images/MoviaImagesV3/movia_map_popup_vis_koreplan.png'></a>";
                popUpContent += "    </div>";

                return popUpContent;
            }

            function getPopUpTab(lineName, productColor, lineOnMap, value) {

                var popUpTab = "";
                var selectedClass = "selected_" + productColor;
                var selectedRightclass = "selected_" + productColor + "_right";

                popUpTab += "<div class='" + selectedClass + (lineOnMap ? " lineOnMap" : "") + "' value='" + value + "'><span>" + lineName + "</span></div><div class='" + selectedRightclass + "'></div>";
                return popUpTab;
            }

            function getSelectedFeature(idResults) {
                var selectResult = { featureType: '', feature: null };
                var stopFeatures = [];
                var stationFeatures = [];

                if (idResults.length == 0)
                    return null;

                var idResult;
                for (var i = 0; i < idResults.length; i++) {
                    idResult = idResults[i];
                    if (idResult.layerId === 0) {  // stops
                        stopFeatures.push(idResult.feature);
                    }
                    else if (idResult.layerId === 1) {  // stations
                        stationFeatures.push(idResult.feature);
                    }
                }

                if (stopFeatures.length > 0) {
                    selectResult = new Object();
                    selectResult.featureType = "Stop";
                    selectResult.feature = stopFeatures[0];
                    return selectResult;
                }
                else if (stationFeatures.length > 0) {
                    selectResult = new Object();
                    selectResult.feature = stationFeatures[0];
                    if (selectResult.feature.attributes["Tog"] == 1)
                        selectResult.featureType = "Tog";
                    else if (selectResult.feature.attributes["Stog"] == 1)
                        selectResult.featureType = "Stog";
                    else if (selectResult.feature.attributes["Metro"] == 1)
                        selectResult.featureType = "Metro";
                    if (selectResult.featureType.length > 0)
                        return selectResult;
                    else
                        return null;
                }
                else
                    return null;
            }

            function getStopPopupData(stopFeature) {
                var stopPopup = { stopName: null, stopgid: null, JPPGid: null, lines: [] };
                var line = { lineName: null, productColor: null, linegid: null, directiongid: null, lineOnMap: false, popupvalues: null }
                var productType;

                stopPopup.stopName = stopFeature.attributes["Name"];
                stopPopup.stopgid = stopFeature.attributes["StopAreaGid"];
                stopPopup.JPPGid = stopFeature.attributes["JPPGid"];

                var linegidList = stopFeature.attributes["LineGidList"];
                var linegidArray = linegidList.split(";");
                var directiongidList = stopFeature.attributes['DirectionGidList'];
                var directiongidArray = directiongidList.split(";");
                var busList = stopFeature.attributes["BusList"];
                var busArray = busList.split(";");
                var productList = stopFeature.attributes["ProductList"];
                var productArray = productList.split(";");
                for (var i = 0; i < busArray.length; i++) {
                    line = new Object();
                    line.lineName = busArray[i];
                    if (productArray.length >= i)
                        productType = productArray[i];
                    else
                        productType = "";
                    line.productColor = globalMap.defaultProductColor;  // default product color
                    for (var j = 0; j < globalMap.productTypes.length; j++) {
                        if (productType == globalMap.productTypes[j]) {
                            line.productColor = globalMap.productColors[j];
                            break;
                        }
                    }
                    //line.productColor = "red" //temporay development color

                    if (linegidArray.length >= i)
                        line.linegid = linegidArray[i];
                    else
                        line.linegid = "";

                    line.lineOnMap = false;
                    if (line.linegid.length > 0) {
                        if (globalMap.queryStringLines.indexOf(line.linegid) !== -1 ||
                            globalMap.favoriteLines.indexOf(line.linegid) !== -1 ||
                            globalMap.lastSearchedLines.indexOf(line.linegid) !== -1 )
                            line.lineOnMap = true;
                    }

                    if (directiongidArray.length >= i)
                        line.directiongid = directiongidArray[i];
                    else
                        line.directiongid = "";

                    if (globalMap.selectedLine.length > 0 && line.directiongid.length > 0) {
                        if (globalMap.selectedLine.indexOf(line.directiongid) !== -1)
                            line.lineOnMap = true;
                    }

                    line.popupvalues = line.lineName + ";" + line.linegid + ";" + line.directiongid + ";" + line.productColor + ";" + stopPopup.stopgid + ";" + stopPopup.JPPGid;

                    stopPopup.lines.push(line);
                }

                return stopPopup;
            }

            function SortByName(a, b) {
                var aName = a.lineName;
                var bName = b.lineName;
                return alphanum(aName, bName);
            }

            function alphanum(a, b) {
                function chunkify(t) {
                    var tz = [], x = 0, y = -1, n = 0, i, j;

                    while (i = (j = t.charAt(x++)).charCodeAt(0)) {
                        var m = (i == 46 || (i >= 48 && i <= 57));
                        if (m !== n) {
                            tz[++y] = "";
                            n = m;
                        }
                        tz[y] += j;
                    }
                    return tz;
                }

                var aa = chunkify(a);
                var bb = chunkify(b);

                for (x = 0; aa[x] && bb[x]; x++) {
                    if (aa[x] !== bb[x]) {
                        var c = Number(aa[x]), d = Number(bb[x]);
                        if (c == aa[x] && d == bb[x]) {
                            return c - d;
                        } else return (aa[x] > bb[x]) ? 1 : -1;
                    }
                }
                return aa.length - bb.length;
            }


        });

        var resizeTimer;
        function resizeMap() {
            clearTimeout(resizeTimer);
            resizeTimer = setTimeout(function () {
                globalMap.map.resize();
                globalMap.map.reposition();
            }, 500);
        }
    };

})(jQuery);

$(document).ready(function () {

    $("#showLargeMap").click(function () {
        $(this).css("display", "none");
        if (!globalMap) return;
        $(this).parent().mapUtility("extendMap");
    });
    $('#printMapIcon').click(function () {
      printMap('printArea')
    });

});

function popUpTabSelected(obj) {
    var popUpValue =  $(obj).attr("value");
    var popUpValueArray = popUpValue.split(";");
    var selProductColor = globalMap.defaultProductColor;    // default product color
    if (popUpValueArray != null && popUpValueArray.length > 5)
        selProductColor = popUpValueArray[3];

    // mark prior selected line unselected
    var popUpTabSelected = "popUpTabSelected(this);";
    var newclick = new Function(popUpTabSelected);
    for (var i = 0; i < globalMap.productColors.length; i++) {
        $(".selected_" + globalMap.productColors[i]).click(newclick);
        $(".selected_" + globalMap.productColors[i]).removeClass("selected_" + globalMap.productColors[i]).addClass(globalMap.productColors[i]);
        $(".selected_" + globalMap.productColors[i] + "_right").removeClass("selected_" + globalMap.productColors[i] + "_right").addClass(globalMap.productColors[i] + "_right");
    }

    // mark clicked line selected and fetch data
    $(obj).removeClass(selProductColor).addClass("selected_" + selProductColor);
    $(obj).next().removeClass(selProductColor + "_right").addClass("selected_" + selProductColor + "_right");
    //    $(obj).attr('onclick', '');
    $(obj).unbind("click"); 
    $("#pop-up_changes").hide();
    $(".map-popup-dev-header a").attr("title", "Åbn");
    $(".map-popup-dev-header a").text("Åbn");
    $("#map-popup-dev-header").hide();
    getDeviationsForLine(popUpValueArray[1]);

    $("#pop-up_lineinfo").show();

    // clear getDeparturesForLine timer
    if (globalMap.depTimer != null) {
        clearInterval(globalMap.depTimer);
        globalMap.depTimer = null;
    }
    // getDeparturesForLine and set timer
    getDeparturesForLine(popUpValueArray[2], popUpValueArray[4]);
    globalMap.depTimer = setInterval(function () {
        getDeparturesForLine(popUpValueArray[2], popUpValueArray[4]);
    },60000);

    // draw selected line button
    $(".map-popup-draw").unbind("click", drawSelectedLine);
    $(".map-popup-draw").bind("click", { directionGid: popUpValueArray[2] }, drawSelectedLine);

    // link to line schedule
    $(".map-popup-schedule").attr("href", globalMap.scheduleUrl + "?direction_gid=" + popUpValueArray[2] + "&line_name=" + popUpValueArray[0] + "&linegid=" + popUpValueArray[1] + "&journey_gid=" + popUpValueArray[5] + "#navigate");

    // link to add favorite stop
    $(".map-popup-favorite").attr("href", globalMap.favoriteStopUrl + "?direction_gid=" + popUpValueArray[2] + "&line_gid=" + +popUpValueArray[1] + "&next_stop=" + popUpValueArray[4]);

}

function toggleDevDep(obj) {
    if ($("#pop-up_changes").is(":visible")) {
        $("#pop-up_changes").hide();
        $(obj).attr("title", "Åbn");
        $(obj).text("Åbn");
        $("#pop-up_lineinfo").show();
    }
    else {
        $("#pop-up_lineinfo").hide();
        $("#pop-up_changes").show();
        $(obj).attr("title", "Luk");
        $(obj).text("Luk");
    }
}
  
function drawSelectedLine(event) {
    globalMap.map.infoWindow.hide();
    var options = { "selectedLine": event.data.directionGid };
    $("#" + globalMap.mapElm).mapUtility("drawMap", options);
    return false;
}

function drawAllLines() {
    $("#" + globalMap.mapElm).mapUtility('drawMap', { 'showAllLines': true });
    return false;
}

function getDeviationsForLine(lineGid) {
    var deviationText = "";
    globalMap.ajaxLineGid = lineGid;
    $("#pop-up_changes").html("");
    /*alert("You selected '" + lineGid + "'"); */
    $.ajax({
        url: globalMap.restApiUrl + "/GetDeviationsForLineGid/" + lineGid,
        type: "GET",
        contentType: "application/json",
        processData: false,
        timeout: globalMap.timeout,
        dataType: "jsonp",
        success: function (result) {
        if (result != null && globalMap.ajaxLineGid != result.lineGid)  // response to last request ?
            return;
        if (result != null && result.status > 0) {
            $("#map-popup-dev-header").show();

            deviationText = "<p>";
            for (i = 0; i < result.Deviations.length; i++) {
            if (i > 0) deviationText += "<br><br>";
            deviationText += "<b>" + result.Deviations[i].ValidFromDateTime + " - " + result.Deviations[i].ValidFromDateTime + "</b><br>";
            deviationText += result.Deviations[i].headerText;
            if (result.Deviations[i].summaryText != null && result.Deviations[i].summaryText.length > 0)
                deviationText += "<br>" + result.Deviations[i].summaryText;
            if (result.Deviations[i].bodyText != null && result.Deviations[i].bodyText.length > 0)
                deviationText += "<br><br>" + result.Deviations[i].bodyText;
            }
            deviationText += "</p>";
            $("#pop-up_changes").html(deviationText);
        }
        else
            if (result != null && result.status == 0)
                $("#pop-up_changes").html("<p>Der er ingen planlagte ændringer på denne linje</p>");
            else
                $("#pop-up_changes").html("<p>Ændringer er ikke tilgængelige i øjeblikket - prøv igen senere</p>");
        },
        error: function (xhr, message, ex) {
        if (message == "timeout")
            $("#pop-up_changes").html("<p>Timeout - prøv igen senere</p>");
        else
            $("#pop-up_changes").html("<p>Ændringer er ikke tilgængelige i øjeblikket - prøv igen senere</p>");
        }
    });
}

function getDeparturesForLine(directionGid, stopGid) {
    var departureText = "";
    globalMap.ajaxDirectionGid = directionGid;
    $("#pop-up_lineinfo").html("<div><img src='/_layouts/images/MoviaImagesV3/movia_map_popup_loader.gif' width='32' height='32'/></div>");
    $.ajax({
        url: globalMap.restApiUrl + "/GetNextDepartureForLineGid/" + stopGid + "," + directionGid,
        type: "GET",
        contentType: "application/json",
        processData: false,
        timeout: globalMap.timeout,
        dataType: "jsonp",
        success: function (result) {
        if (result != null && globalMap.ajaxDirectionGid != result.LineDirectionGid)  // response to last request ?
            return;
        if (result != null && result.status > 0) {
            for (i = 0; i < result.NextDepartures.length; i++) {
            departureText += "<div class='map-popup-departure'>";
            departureText += "<span class='destination'>Mod:<br><span class='destinationName'>" + result.NextDepartures[i].DestinationName + "</span></span>";
            departureText += "<span class='departure'><span class='departureMin'>" + result.NextDepartures[i].MinutesToDeparture + "</span> min</span>";
            departureText += "</div>";
            }
            $("#pop-up_lineinfo").html(departureText);
        }
        else 
            if (result != null && result.status == 0)
                $("#pop-up_lineinfo").html("<p>" + globalMap.departureNotFoundTxt + "</p>");
            else
                $("#pop-up_lineinfo").html("<p>Afgange er ikke tilgængelige i øjeblikket - prøv igen senere</p>");
    },
        error: function (xhr, message, ex) {
        if (message == "timeout")
            $("#pop-up_lineinfo").html("<p>Timeout - prøv igen senere</p>");
        else
            $("#pop-up_lineinfo").html("<p>Afgange er ikke tilgængelige i øjeblikket - prøv igen senere</p>");
        }
    });
}

function printMap(printId) {

    var display_setting = "status=no,toolbar=no,location=no,directories=no,menubar=no,";
    display_setting += "scrollbars=yes,width=800, height=800, left=100, top=25";

    var content_innerhtml = document.getElementById(printId).innerHTML;
    var document_print = window.open("", "", display_setting);
    document_print.document.open();
    document_print.document.write('<html><head><title>Kort</title>');
    document_print.document.write('  <scr' + 'ipt type="text/javascript">dojoConfig = { parseOnLoad: true }</scr' + 'ipt>');
    document_print.document.write('  <scr' + 'ipt type="text/javascript" src="http://serverapi.arcgisonline.com/jsapi/arcgis/?v=2.5"></scr' + 'ipt>');
    document_print.document.write('  <style type="text/css">');
    document_print.document.write('    .infowindow {display: none !important;}  /* kort - popup */');
    document_print.document.write('    .dijitSlider {display: none;}  /* kort - zoomnavigator */');
    document_print.document.write('    #map_gc {display: none;}  /* kort - grafiske lag */');
    document_print.document.write('    .showLargeMap {display: none;}  /* kort - Vis stort kort knap */');
    document_print.document.write('    .printMap {display: none;}  /* kort - Print knap */');
    document_print.document.write('  </style>');
    document_print.document.write('</head>');
    document_print.document.write('<body>');
    document_print.document.write(content_innerhtml);
    document_print.document.write('</body></html>');
    document_print.document.close();
    if (window.focus) { document_print.focus(); }  
    document_print.print();
    document_print.close();
    return false;
}

/*MAP FUNCTIONS - END */
