/*******************************************************************************
 * all the things that have to be done on document load
 * requires JQuery 1.3 !!!!!!
 *
 * @return void
 ******************************************************************************/
$(function(){
    //try {getColorbox();		}catch (e) {}
    /*
    try {
        $("a[href*='output_adb_file']").live("click", function(){
            window.open(this.href + "&popup=true&nav=" + _nav, "Download-Popup", "width=300,height=350,scrollbars=no");
            return false;
        });
    } 
    catch (e) {
    }*/
    init(); 
});
// ready
$(document).ready(function(){
    try {
        $(document).pngFix({
            blankgif:"../../assets/common/spacer.gif",
            repeatMethod:"Crop"
        });
    } catch (e) { }
    try {
        doAjaxSlider();
    } catch (e) {
        throwError(e);
    }
    /*
    try {
        setEventMonth();
    } 
    catch (e) {
        throwError(e);
    }
    try {
        getColorbox();
    } 
    catch (e) {
        throwError(e);
    }
    try {
        doAjaxAnmelden();
    } 
    catch (e) {
        throwError(e);
    }
    */
    
    try {
        
        if (window.location.host.indexOf('schwabenlandhalle') >= 0) {
            var theKey = '#@2095caa968780aa08bf';
        }
        else {
            var theKey = '#@78564909422f9a31c27';
        }
        
        
        $('a.flowplayer img').remove();
        flowplayer("a.flowplayer", "../../assets/swf/flowplayer.commercial-3.2.7.swf", {
            "key": theKey,
            "debug":false,
            "clip":  {
                "autoPlay": false,
                "autoBuffering": true,
                "onFinish": function() {
                    this.seek(0);
                    this.pause();
                }
            }
        });
   
    }
    catch (e) {
        console.log(e);
    }
    
}); // ende $(document).ready();

// init
function init(){
    try {
        getGaleries();
    } catch (e) {
        throwError(e);
    }
    try {
        doAjaxLink();
    } catch (e) {
        throwError(e);
    }
    try {
        getSliders();
    } catch (e) {
        throwError(e);
    }
    //try { getLocationfinderSlider();                                                               } catch (e) { throwError(e); }
    try {
        $("a.lightbox").lightBox({
            imageLoading: '../../assets/jquery/plugins/lightbox/0.5/images/locale/de_DE/lightbox-ico-loading.gif',
            imageBtnClose: '../../assets/jquery/plugins/lightbox/0.5/images/locale/de_DE/lightbox-btn-close.gif',
            imageBtnPrev: '../../assets/jquery/plugins/lightbox/0.5/images/locale/de_DE/lightbox-btn-prev.gif',
            imageBtnNext: '../../assets/jquery/plugins/lightbox/0.5/images/locale/de_DE/lightbox-btn-next.gif',
            imageBlank: '../../assets/jquery/plugins/lightbox/0.5/images/locale/de_DE/lightbox-blank.gif',
            txtOf: 'von',
            txtImage: 'Bild'
        });
    }
    catch (e) {
        throwError(e);
    }
    try {
        $("ul#ticker").liScroll({
            travelocity: 0.05
        });
    } catch (e) {
        throwError(e);
    }
    
/*
    try {
        getEventCoverflow();
    } 
    catch (e) {
        throwError(e);
    }
    try {
        getEventSlideshow();
    } 
    catch (e) {
        throwError(e);
    }
    try {
        getEventMonths();
    } 
    catch (e) {
        throwError(e);
    }
    // scroll fuer terminvorschau
    try {
        getDatesScroll();
    } 
    catch (e) {
        throwError(e);
    }
    try {
        getTooltip();
    } 
    catch (e) {
        throwError(e);
    }
    
    try {
        getGalleryview(false);
    } 
    catch (e) {
        throwError(e);
    }
    try {
        getDatePicker();
    } 
    catch (e) {
        throwError(e);
    }
    try {
        getGroundviewLocations();
    } 
    catch (e) {
        throwError(e);
    }
    try {
        getGroundviewBuilding();
    } 
    catch (e) {
        throwError(e);
    }
    try {
        $("#accordion").accordion({
            autoHeight: false,
            collapsible: true,
            icons: false
        }).accordion("activate", false);
    } 
    catch (e) {
        throwError(e);
    }*/
}

function getGaleries() {
    var galleries = $(".standard-gallery").adGallery( {
        width:  509,                    // Width of the image, set to false and it will read the CSS width
        height: 400,                    // Height of the image, set to false and it will read the CSS height
        thumb_opacity: 1,               // Opacity that the thumbs fades to/from, (1 removes fade effect)
        // Note that this effect combined with other effects might be resource intensive
        // and make animations lag
        description_wrapper: false,     // Either false or a jQuery object, if you want the image descriptions
        // to be placed somewhere else than on top of the image
        start_at_index: 0,              // Which image should be displayed at first? 0 is the first image
        animate_first_image: false,     // Should first image just be displayed, or animated in?
        animation_speed: 400,           // Which ever effect is used to switch images, how long should it take?
        display_next_and_prev: true,    // Can you navigate by clicking on the left/right on the image?
        display_back_and_forward: true, // Are you allowed to scroll the thumb list?
        scroll_jump: 0,                 // If 0, it jumps the width of the container
        effect: "none",                 // or "slide-vert", "resize", "fade", "none" or false
        enable_keyboard_move: false,     // Move to next/previous image with keyboard arrows?
        loader_image: '../../assets/common/load_white.gif',
        cycle: true,
        slideshow: {
            enable: false
        },
        callbacks: {
            init: function () {
                this.preloadAll();
            },
            afterImageVisible: function () {
                var image = this.images[this.current_index];
                var _tmp_cls = $(this.wrapper.context).attr("class");
                _tmp_cls = _tmp_cls.split(' ');
                this.cls = _tmp_cls[2];

                $("."+this.cls+" .ad-gallery-desc-custom").delay(100).fadeOut(100, function (obj) {
                    var cls = $(this).parent().attr("class");
                    cls = cls.split(' ');
      	     
                    var title = image.title != false ? image.title : "&nbsp;";
                    var desc = image.desc != false ? image.desc : "&nbsp;";
                    var html = '<div class="title">'+title+'</div><div class="desc">'+desc+'</div>'
                    $("."+ cls[2] +" .ad-gallery-desc-custom").fadeIn(100).html(html);
                });
            },
            beforeImageVisible: function () {
                var _tmp_cls = $(this.wrapper.context).attr("class");
                _tmp_cls = _tmp_cls.split(' ');
                this.cls = _tmp_cls[2];
      
                $("."+this.cls+" .ad-gallery-desc-custom").html('<img class="load" src="../../assets/common/load_white.gif" alt="Loading..." title="Loading..." />');
            }
        }
    } );

    var galleries = $(".location-gallery").adGallery( {
        width:  509,                    // Width of the image, set to false and it will read the CSS width
        height: 400,                    // Height of the image, set to false and it will read the CSS height
        thumb_opacity: 1,               // Opacity that the thumbs fades to/from, (1 removes fade effect)
        // Note that this effect combined with other effects might be resource intensive
        // and make animations lag
        description_wrapper: false,     // Either false or a jQuery object, if you want the image descriptions
        // to be placed somewhere else than on top of the image
        start_at_index: 0,              // Which image should be displayed at first? 0 is the first image
        animate_first_image: false,     // Should first image just be displayed, or animated in?
        animation_speed: 400,           // Which ever effect is used to switch images, how long should it take?
        display_next_and_prev: true,    // Can you navigate by clicking on the left/right on the image?
        display_back_and_forward: true, // Are you allowed to scroll the thumb list?
        scroll_jump: 0,                 // If 0, it jumps the width of the container
        effect: "none",                 // or "slide-vert", "resize", "fade", "none" or false
        enable_keyboard_move: false,     // Move to next/previous image with keyboard arrows?
        loader_image: '../../assets/common/load_white.gif',
        cycle: true,
        slideshow: {
            enable: false
        }
    } );
}
/*
function getColorbox(){
    // colorbox
    $("a.colorbox").colorbox({
        //        height: "90%",
        //        width: "550px",
        onComplete: function(){
            var height = $('#cboxLoadedContent').height();
        }
    }, function(){
        //getGroundviewBuilding();
        getGalleryview(true);
        
        //var height = $('#cboxLoadedContent').height();
    });
    
    $("a.colorbox_groundview").colorbox({
        height: "90%",
        width: "500px",
        innerWidth: "460px",
        onComplete: function(){
            var height = $('#cboxLoadedContent').height();
        }
    }, function(){
        getGroundviewBuilding();
        
        //var height = $('#cboxLoadedContent').height();
    });
    
    
}

function setToolTips(){
    jQuery(".calHighlight").tooltip({
        extraClass: "activite"
    });
}

function getDatePicker(){
    $(".datepicker").datepicker({
        //yearRange: "1910:2010",
        //changeYear:true,
        dateFormat: "dd.mm.yy",
        dayNamesMin: ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"],
        monthNames: ['Januar', 'Februar', 'M&auml;rz', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember']
    });
    if ($('.calender').length != 0) {
        $('.tooltip').each(function(){
        
            if ($(this).find('.tooltip_content').length != 0) {
                $(this).qtip({
                    text: false,
                    content: $(this).find('.tooltip_content').html(),
                    hide: {
                        when: 'mouseout',
                        fixed: true
                    }
                });
            }
        });
    }
}

function getTooltip(){
    // Notice the use of the each() method to acquire access to each elements attributes
    $('.tooltip').each(function(){
        $(this).qtip({
            text: false,
            hide: {
                when: 'mouseout',
                fixed: true
            }
        });
    });
    
}

function getAutocompleteWords(){
    var type = $(this).attr('name'); // name from input
    $('.suchtext').autocomplete({
        minLength: 2,
        search: function(){
            var params = $(this).parent('form').serialize();
            $(this).autocomplete("option", "source", getAjaxUrl('autocomplete&type=' + $(this).attr("name")) + '&' + params);
        },
        select: function(event, ui){
            log(ui.item ? ("Selected: " + ui.item.value + " aka " + ui.item.id) : "Nothing selected, input was " + this.value);
        }
    });
}


function toggleSlider(){
    if ($('#form_categories select').val() == 11) {
        $("#locationslider2").show();
        $("#locationslider1").hide();
    }
    else {
        $("#locationslider1").show();
        $("#locationslider2").hide();
    }
}

function getLocationfinderSlider(){
    if ($('#locationfinder .result').length != 0) {
        $("#locationfinder .result").jCarouselLite({
            btnNext: "#locationfinder .next",
            btnPrev: "#locationfinder .prev",
            visible: 1,
            speed: 1400,
            vertical: true,
            auto: 1300
        });
    }
}

function getAjaxLoader(div){
    $(div).ajaxStart(function(){
        $(this).html('<div class="loading"></div>');
    });
}

function doAjaxAnmelden(){
    var params = {
        TOID: "freiburg_messe",
        VAC_PROFILE: "0", //Vakanzprofil
        LID: "0", // TP_Freiburg_Messe  Tracking Benutzer
        NAV: "1",
        LANG: "de"
    };
    var str_param = jQuery.param(params);
    
    // http://fit.tomas.travel/irs/TPortalRegion/start.jsp?TOID=freiburg_messe&MODULE=MOD_EXEC_VAC&VAC_PROFILE=0&LID=0&NAV=1&LANG=de&ARR_DAY=11&ARR_MONTH=5&ARR_YEAR=2010&NIGHTS=5&ADULTS=4&CITY=FIT00020070000008727
    $('.form_anmeldung_search .submit').click(function(){
        var form_params = $(this).parent('form').serializeArray();
        var datum = $(this).parent('form').find("input[name='datum']").val();
        var arr_datum = datum.split(".");
        var str_ort = $(this).parent('form').find("select[name='selPlace']").val();
        var str_pax = $(this).parent('form').find("select[name='selPax']").val();
        var str_nights = $(this).parent('form').find("select[name='selNights']").val();
        
        var form_params = {
            MODULE: "MOD_EXEC_VAC",
            ARR_DAY: ltrim(arr_datum[0], "0"),
            ARR_MONTH: ltrim(arr_datum[1], "0"),
            ARR_YEAR: arr_datum[2],
            NIGHTS: str_nights,
            ADULTS: str_pax,
            CITY: str_ort
        };
        var str = jQuery.param(form_params);
        var url = $(this).parent('form').attr('action') + str_param + "&" + str;
        $(this).colorbox({
            href: url,
            width: "700",
            height: "80%",
            iframe: true
        });
        
        return false;
    });
    
    $('.form_anmeldung_search .detailsuche').click(function(){
        var form_params = {
            MODULE: "MOD_VAC"
        };
        var str = jQuery.param(form_params);
        
        var url = $(this).parent('form').attr('action') + str_param + "&" + str;
        $(this).colorbox({
            href: url,
            width: "700",
            height: "80%",
            iframe: true
        });
        
        return false;
    });
    
}
*/
function ltrim(str, charlist){
    // Strips whitespace from the beginning of a string
    //
    // version: 1004.2314
    // discuss at: http://phpjs.org/functions/ltrim    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Erkekjetter
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // *     example 1: ltrim('    Kevin van Zonneveld    ');    // *     returns 1: 'Kevin van Zonneveld    '
    charlist = !charlist ? ' \\s\u00A0' : (charlist + '').replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
    var re = new RegExp('^[' + charlist + ']+', 'g');
    return (str + '').replace(re, '');
}

function getSliders() {
    galStart = false;
    arrForms = ["st", "nd", "rd", "th", "fth"];
    $.each(arrForms, function(key,id) {
        getSlider(id);
    });
}

function getSlider(id){
    if($("#form_"+id+" select").length != 0) {
        $("#form_"+id+" select").selectToUISlider({
            labels: 10,
            tooltip: false,
            labelSrc: 'text',
            sliderOptions: {
                change: function(e,ui) {
                    doAjaxSlider();
                }
            }
        });
}
}

function slider_carousel_init(carousel) {
    if(galStart==false) {
        jQuery('#next').bind('click', function() {
            carousel.next();
            return false;
        });
        jQuery('#previous').bind('click', function() {
            carousel.prev();
            return false;
        });
    }
}
  
function startCarousel() {
    $("#viewport").jcarousel({
        scroll: 1,
        visible: 1,
        wrap: "circular",
        initCallback: slider_carousel_init,
        buttonNextHTML: null,
        buttonPrevHTML: null
    });
    
    carousel = $("#viewport").data("jcarousel");
}
  
function doAjaxSlider () {
    // Wird übernommen:
    // => arrForms
  	
    //Neue Variablen
    var url    = $("#form_"+arrForms[0]).attr("action")!="" ? $("#form_"+arrForms[0]).attr("action") : "../../content_scripts/ajax/handle.php?action=slider";
    var inpVal = new Object;
  	 
    //Ajax Loader
    $("#viewport").addClass("loading");
    $("#viewport ul").css("display","none");
  	 
    //Aktuelle Ergebnisse auflisten
    $.each(arrForms,function(key,id) {
        inpVal[id] = $("#form_"+id+" select").val();
    });

    //Abfrage absenden
    $.post(url, {
        values: inpVal
    },
    function (data) {
        //Ajax Loader
        $("#viewport").removeClass("loading");
        $("#viewport ul").css("display","block");
   	    
        if(galStart==false) {
            $("#viewport ul").html(data); 
            startCarousel();
            galStart = true;
        }  
        else {
            carousel.reset();
            $("#viewport ul").html(data);
            startCarousel();
        }
    });
}

function doAjaxLink(){
    $("a.ajax").click(function(){
        var url = $(this).attr("href");
        $.post(url, {}, function(data){
            eval(nl2empty(data));
        });
        return false;
    });
}

function submitLocationFinder (id, lang, nav) {
    // Wird übernommen:
    // => arrForms
  
    var inpVal = '';
  
    //Aktuelle Ergebnisse auflisten
    $.each(arrForms, function (key, id) {
        inpVal += '&' + id + '=' + $("#form_" + id + " select").val();
    });
  
    $.ajax({
        type: 'POST',
        url: '../../content_scripts/ajax/handle.php?action=seoUrl&lang=' + lang + '&nav=' + nav,
        data: 'id=' + id + inpVal,
        success: function (data) {
            location.href = data;
        }
    });
  
    return false; 
}

function getTagcloud(){
    /*
     $('#myCanvas').tagcanvas(
     {
     textColour : '#000000',
     outlineThickness : 1,
     maxSpeed : 0.03,
     depth : 0.75
     });
     return false;
     */
    if ($('#tagcloud').length != 0) {
        var html = $('#tagcloud').html();
        /*$('#tagcloud ul li').each(function()
         {
         html += $(this).html();
         });*/
        $('#tagcloud').html('');
        
        $('#tagcloud').flash({
            src: '../../assets/files/tagcloud.swf',
            width: 240,
            height: 300,
            wmode: 'opaque',
            flashvars: {
                tcolor: '0x666666',
                distr: 'true',
                tspeed: '110',
                xmlpath: 'html'
            // mode: 'tags',
            // tagcloud: "<tags>" + html + "</tags>"
            }
        });
    }
}

function getEventCoverflow(){
    if ($('#event_coverflow').length != 0) {
        var slideshow = new ImageFlow();
        slideshow.init({
            startID: 3,
            ImageFlowID: 'event_coverflow',
            reflections: false,
            //aspectRatio: 1.9,
            imagesHeight: 0.9,
            imageFocusM: 1.9,
            //            imagesHeight: 2,
            //            imageFocusMax: 5.7,
            //            imageScaling: false,
            //            circular: true,
            //            buttons: true,
            //            opacity: false,
            //            imageCursor: 'pointer',
            //            sliderCursor: 'pointer',
            //            startAnimation: true,
            slider: false,
            captions: false,
            captionDivStyle: false
        //           xStep: 130
        });
        
        // default bild
        //debug($('#event_coverflow_logo img').attr('src').length);
        
        if ($('#event_coverflow_logo img').attr('src').length == 0) {
            var event_id = $('#event_coverflow_images img:eq(2)').attr('rel');
            if (event_id > 0) {
                $.ajax({
                    type: "GET",
                    url: getAjaxUrl('coverflow_img') + '&event_id=' + event_id,
                    dataType: "json",
                    success: function(msg){
                        $('#event_coverflow_logo img').attr('src', msg.img).attr('height', msg.height).attr('title', msg.title);
                        $('#event_coverflow_logo').fadeIn();
                    }
                });
            }
        }
        // logo laden
        $('#event_coverflow_images img').mouseover(function(){
            var event_id = $(this).attr('rel');
            if ($(this).attr('rel') > 0) {
                $.ajax({
                    type: "GET",
                    url: getAjaxUrl('coverflow_img') + '&event_id=' + event_id,
                    dataType: "json",
                    success: function(msg){
                        $('#event_coverflow_logo img').attr('src', msg.img).attr('height', msg.height).attr('title', msg.title);
                    }
                });
            }
        });
    }
}

function getEventSlideshow(){
    if ($('#event_slideshow .slider').length != 0) {
        $("#event_slideshow .slider").jCarouselLite({
            btnNext: "#event_slideshow .next",
            btnPrev: "#event_slideshow .prev",
            visible: 3,
            scroll: 2,
            speed: 1000
        });
    }
}

function getDatesScroll(){
    $('.date_pager .down').bind('mousedown mouseup', function(event){
        if (event.type == 'mousedown') {
            $('.dates_preview').animate({
                "scrollTop": "+=2000px"
            }, 3000, 'linear');
            return false;
        }
        else {
            $('.dates_preview').stop();
            return false;
        }
        
    });
    
    $('.date_pager .up').bind('mousedown mouseup', function(event){
        if (event.type == 'mousedown') {
            $('.dates_preview').animate({
                "scrollTop": "-=2000px"
            }, 3000, 'linear');
            return false;
        }
        else {
            $('.dates_preview').stop();
            return false;
        }
        
        return false;
    });
}


function setEventMonth(){
    var today = new Date();
    var month = today.getMonth() + 1;
    $("#event_months .months").ready(function(){
        $("#event_months .months").hide();
        if ($("#event_months #month-" + month + " ul").html()) {
            $("#event_months #month-" + month).fadeIn();
        }
        else { //also wenn keine Termine in dem aktuellen Monat vorhaden sind, rutsch zum nächsten mit Termine
            var bool = false;
            for (var i = month; i <= 12 && !bool; i++) {
                if ($("#event_months #month-" + i + " ul").html()) {
                    $("#event_months #month-" + i).fadeIn();
                    bool = true;
                }
            }
            if (i == 12 && !bool) {
                i = 1;
            }
        }
    });
}

function getEventMonths(){
    if ($('#event_months').length != 0) {
        try {
            $("#event_months .months").show();
            
            $("#event_months ul#choose li a").click(function(){
                var month = $(this).attr("href").split("#"); //split the URL once
                month = month[1].split("-"); //then split the id that is send with the URL
                month = month[1]; //now assign the letter
                $("#event_months .months").hide();
                $("#event_months #month-" + month).fadeIn();
                return false;
            });
            $("#display-all-months").click(function(){
                $(".months").fadeIn();
                return false;
            });
        } 
        catch (e) {
        }
    }
}

function getGalleryview(colorbox){
    if ($('#galleryview').length != 0) {
        $('#galleryview').galleryView({
            filmstrip_size: 5,
            panel_width: 420,
            panel_height: 270,
            frame_width: 60,
            frame_height: 40,
            overlay_height: 50,
            img_path: '../../assets/jquery/plugins/galleryview/1.1/',
            img_path: '../../assets/common/',
            border: 'none',
            background_color: '#5b544c'
        //overlay_color: '#5b544c'
        //overlay_color: '#222',
        //overlay_text_color: 'white',
        //caption_text_color: '#222',
        //background_color: 'transparent',
        //nav_theme: 'dark',
        //pause_on_hover: true
        });
        $('#galleryview .nav-prev').attr('src', '../../assets/common/arrow_double_white_left.gif');
        $('#galleryview .nav-next').attr('src', '../../assets/common/arrow_double_white_right.gif');
        
        if (colorbox == true) {
            $.fn.colorbox.resize();
        }
        else {
            // Der Pointer darf nicht hier verwendet werden nur auf der Colorbox
            $('#galleryview #pointer').remove();
        }
        
    }
}

function getGroundviewLocations(){
    //$('.overview .button').click(function(){
    //$('.overview').toggle();
    //return false;
    //});
    $("#accordion_receiver img").hide();
    $("#accordion_receiver img").first().show();
    if ($('#accordion').length != 0) {
        $('.accordion-links a.intern').click(function(){
            var href = $(this).attr('id').split("_");
            var asset_id = href[2]; //split the URL once
            var img_id = 'overview_img_' + asset_id;
            
            if ($('#' + img_id).length != 0) {
                $("#accordion_receiver img").hide();
                $('#' + img_id).show();
            }
            return false;
        });
    }
}

function getGroundviewBuilding(){
    if ($('.map').length != 0) {
        $('img.map').maphilight({
            fill: true,
            fillColor: '9db9c9',
            fillOpacity: 0.8,
            stroke: false,
            strokeColor: 'ff0000',
            strokeOpacity: 1,
            strokeWidth: 1,
            fade: false,
            alwaysOn: false
        });
        
        var html = $('#description_box').html();
        
        $('area').mouseover(function(){
            var href = $(this).attr('href').split("#");
            var id_div = '#' + href[1];
            $('#description_box').html('');
            $(id_div).clone().appendTo('#description_box');
        //		 $('#description_box').html($(id_div).clone().html());
        
        //$.fn.colorbox.resize();
        
        }).mouseout(function(){
            //$('#description_box').html(html);
            });
        
    }
}

function str_replace(search, replace, subject){
    return subject.split(search).join(replace);
}

function nl2empty(str){
    if (typeof(str) == "string") 
        return str.replace(/(\r\n)|(\n\r)|\r|\n/g, "");
    else 
        return str;
}

function debug(error){
    if (window.console) {
        console.debug(error);
    }
}

function throwError(e){
    debug(e);
}

function loadMap(mapId, address){
    var myOptions = {
        zoom: map_zoom,
        center: new google.maps.LatLng(48.14364, 7.6688),
        mapTypeId: google.maps.MapTypeId.HYBRID
    };
    var map = new google.maps.Map(document.getElementById("gMap-" + mapId), myOptions);
    var c = null;
    var gCoder = new google.maps.Geocoder();
    gCoder.geocode({
        "address": address
    }, function(Result, Status){
   
        console.log(Result);
        console.log(Status);
   
        if (Status == google.maps.GeocoderStatus.OK)
        {
            var latitude = Result[0].geometry.location.lat();
            var longitude = Result[0].geometry.location.lng();
         
            console.log(latitude);
            console.log(longitude);
         
            c = new google.maps.LatLng(latitude, longitude);
            map.setCenter(c);
            var marker = new google.maps.Marker({
                position: c,
                map: map,
                title: address
            });
        }
    });
    try {
        var directionsDisplay = new google.maps.DirectionsRenderer();
        directionsDisplay.setPanel(document.getElementById("GDirectionsPanel-" + mapId));
        directionsDisplay.setMap(map);
        $DirectionsForm = $("#GDirectionsForm-" + mapId);
        $DirectionAddress = $("#GDirectionsAddress-" + mapId);
        $DirectionsForm.live("submit", function(){
            var direction = new google.maps.DirectionsService();
            direction.route({
                origin: $DirectionAddress.val(),
                destination: address,
                travelMode: google.maps.DirectionsTravelMode.DRIVING
            }, function(Result, Status){
                if (Status == google.maps.GeocoderStatus.OK) {
                    directionsDisplay.setDirections(Result);
                }
            });
            return false;
        });
    } 
    catch (E) {
        log(E);
    }
}


