window.mapMarkers = new Object();
window.mapInfo = new Object();
window.hashLocators = new Array();
var hashVal = parseInt(window.location.hash.replace("#", ""));
window.firstLoad = false;

var overrideFylker = { 
    'Vestfold' : { lat : 59.21777154189173, lon : 10.292816162109375, zoom : 11 },
    'Sør-Trøndelag' : { lat : 63.23239045275928, lon : 10.2227783203125, zoom : 10 },
    'Nord-Trøndelag' : { lat : 63.91564308935915, lon : 11.4202880859375, zoom : 9 },
    'Troms' : { lat : 69.34158817053789, lon : 18.5064697265625, zoom : 9 },
    'Nordland' : { lat : 67.22955876681458, lon : 15.589599609375, zoom : 8 },
    'Finnmark' : { lat : 70.01307827710367, lon : 24.6533203125, zoom : 7 },
    'Telemark' : { lat : 59.208282180667524, lon : 9.47296142578125, zoom : 11 },
    'Hedmark' : { lat : 60.654339553149704, lon : 11.93939208984375, zoom : 10 },
    'Buskerud' : { lat : 59.80892258639126, lon : 10.12115478515625, zoom : 11 },
    'Oppland' : { lat : 61.03036144848879, lon : 10.06072998046875, zoom : 10 }
};

$(document).ready(function() {
    
    if($('#kampanjeslideshow') != null)
    if($('#kampanjeslideshow').size() > 0) {
        jQuery('#kampanjeslideshow').cycle({ fx: 'fade', delay: 2000, speed: 500, timeoutFn: calculateTimeout });
        $('#kampanjeslideshow').mouseover(function() {
            $(this).cycle('pause');
        });
        $('#kampanjeslideshow').mouseout(function() {
            $(this).cycle('resume');
        });
    }

    if($("#searchbox") != null)
    if($("#searchbox").size() > 0) {
        var seachBoxVal = $("#searchbox").val();
        $("#searchbox").focus(function() {
            var val = $(this).val();
            if(val == seachBoxVal)
                $(this).val("");
        });
        $("#searchbox").blur(function() {
            var val = $(this).val();
            if(val == "")
                $(this).val(seachBoxVal);
        });
    }
    
    if($(".blank") != null)    
    $(".blank").attr("target", "_blank");
    
    var t = setTimeout(function() {
        var rightCorrection = 0;
        if($("#contactCredentcials").size() > 0) {
            var $rightColumn = $("#rightcolumn-mid");
            var RightColumnHeight = $rightColumn.height();
            var rightCorrection = 25;
            var leftCorrection = 0;
        } else {
            var $rightColumn = $("#rightcolumn");
            var RightColumnHeight = $rightColumn.height();
            var leftCorrection = 25;
        }
        if($("#leftcolumn-mid") != null) {
                        var LeftColumnHeight = $("#leftcolumn-mid").height()+25;
            //var RightColumnHeight = $("#rightcolumn").height();
       
            if(LeftColumnHeight > RightColumnHeight)
                $rightColumn.animate({height: (LeftColumnHeight-rightCorrection)}, "fast");
                
            if(LeftColumnHeight < RightColumnHeight)
                $("#leftcolumn-mid").animate({height: RightColumnHeight-leftCorrection}, "fast");
        }        
        clearTimeout(t);
    },1000);
    
    var $forhandlerForm = $("form#forhandlerForm");
    $forhandlerForm.find("select").change(function()
    {
        $forhandlerForm.attr("action", "forhandlere/"+$(this).val()+"/");
        $forhandlerForm.submit();
    });
    
    $directionForm = $("form#drivingRoute");
    $("a#showRouteBtn").click(function(){
        $directionForm.show();
    });
    
    $("a#mapDirectionsBtn").click(function(){
        $directionForm.hide();
    });
});

$(function() {
    if($("#map_canvas").size() > 0)
        initialize();    
    $("input#makeRouteSubmit").click(function(){
        calcRoute();
        return false;
    });
    if($("a.fylkesBtn").size() > 0) {
        $("a.fylkesBtn").click(function() {
            jQuery("#forhandlerList a.active").removeClass("active");
            jQuery(this).addClass("active");
            map.streetView.setVisible();
            if(window.currentInfo != undefined) {
                window.currentInfo.remove();
                window.currentInfo.setMap(null);
                window.currentInfo = null;
            }
            window.map.setZoom(7);
            centerFylke($(this).html(), window.map);
            return false;
        });
    }
    if($("a.forhandlerBtn").size() > 0) {
        $("a.forhandlerBtn").click(function() {
            jQuery("#forhandlerList a.active").removeClass("active");
            jQuery(this).addClass("active");
            map.streetView.setVisible();
            var companyId = $(this).attr("rel");
            markerObj = eval("window.mapMarkers["+companyId+"]");
            infoObj = eval("window.mapInfo["+companyId+"]");
            if(window.currentInfo != undefined) {
                window.currentInfo.remove();
                window.currentInfo.setMap(null);
                window.currentInfo = null;
            }
            
            window.map.setZoom(14);
            window.map.setCenter(new google.maps.LatLng(infoObj.latlng.lat(),infoObj.latlng.lng()));
            
            if(!infoObj.logo) {
                infoObj.logo = "";
            }
            google.maps.event.addListenerOnce(map, 'idle', function(){ 
                window.currentInfo = new InfoBox(infoObj);
            });
            return false;
        });
    }
});

var directionDisplay;
    var directionsService = new google.maps.DirectionsService();
    var map;

function initialize() {
    
    directionsDisplay = new google.maps.DirectionsRenderer();
    var norway = new google.maps.LatLng(65.36683689226321, 15.9521484375);
    var zoom = 4;
    if(window.startCoordinates != undefined) {
        norway = window.startCoordinates;
        zoom = window.mapZoom;
    }
    var stylez = [{ featureType: "administrative", elementType: "all", stylers: [{ visibility: "on" },{ hue: "#0022ff" },{ saturation: 50 },{ lightness: -10 },{ gamma: 0.9 }]},{ featureType: "landscape.natural", elementType: "all", stylers: [{ visibility: "on"},]},{ featureType: "poi", elementType: "all", stylers: [{ visibility: "on" }, { hue: "#0022ff" },{ saturation: 50 },{ lightness: -10 },{ gamma: 0.9 }] },{featureType: "road",elementType: "all", stylers: [{ visibility: "off" }]},{featureType: "transit",elementType: "all",stylers: [{ visibility: "off" }]},{featureType: "water",elementType: "labels",stylers: [{ visibility: "on" }]}];
    var myOptions = {
        zoom:zoom,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: norway
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById("directions"));
    directionsDisplay.setOptions({suppressMarkers:true});
    var styledMapOptions = {name: "Hip-Hop"};
    var jayzMapType = new google.maps.StyledMapType(stylez, styledMapOptions);
    map.mapTypes.set("Hip-Hop", jayzMapType);
    
    var i = 0;
    var forhandlereTotal = window.forhandlere.length;
    for(i = 0; i < forhandlereTotal; i++) {        
        //addMarker(window.forhandlere[i].latitude, window.forhandlere[i].longitude, window.forhandlere[i].infoContent, window.forhandlere[i].tiderContent, window.forhandlere[i].name, map, window.forhandlere[i].index, window.forhandlere[i].segment, window.forhandlere[i].logo)
        addMarker(window.forhandlere[i].latitude, window.forhandlere[i].longitude, window.forhandlere[i].infoContent, window.forhandlere[i].tiderContent, window.forhandlere[i].merContent, window.forhandlere[i].name, map, window.forhandlere[i].index, window.forhandlere[i].segment, window.forhandlere[i].logo, window.forhandlere[i].thumb, window.forhandlere[i].img)
    }
    if(hashVal != "")
        if(window.hashLocators[hashVal] != undefined)
            if(window.mapInfo[window.hashLocators[hashVal]] != undefined) {
                map.setCenter(window.mapInfo[window.hashLocators[hashVal]].latlng);
            }
    google.maps.event.addListener(map, "tilesloaded", function() {
        if(window.firstLoad == false) {
            if(hashVal != "")
                if(window.hashLocators[hashVal] != undefined)
                    if(window.mapInfo[window.hashLocators[hashVal]] != undefined) {
                        window.currentInfo = new InfoBox(window.mapInfo[window.hashLocators[hashVal]]);
                        window.firstLoad = true;
                    }
        }
    });
    window.map = map;
    //if(window.forhandlere[window.location.hash] != undefined)
}

//function addMarker(latitude, longitude, info, tider, name, mapReferance, index, segment, logo) {
function addMarker(latitude, longitude, info, tider, mer, name, mapReferance, index, segment, logo, thumb, img) {
    var coord = new google.maps.LatLng(latitude, longitude);
    var image = new google.maps.MarkerImage(
        'assets/Uploads/markerImage2green.png',
        new google.maps.Size(37,37),
        new google.maps.Point(0,0),
        new google.maps.Point(19,37)
      );
      
      var shadow = new google.maps.MarkerImage(
        'assets/Uploads/markerShadow2.png',
        new google.maps.Size(59,37),
        new google.maps.Point(0,0),
        new google.maps.Point(19,37)
      );
      
      var shape = {
        coord: [22,0,22,1,22,2,22,3,22,4,22,5,22,6,22,7,22,8,22,9,22,10,22,11,22,12,22,13,36,14,36,15,36,16,36,17,36,18,35,19,34,20,34,21,33,22,32,23,32,24,31,25,31,26,30,27,29,28,29,29,28,30,28,31,26,32,24,33,22,34,20,35,18,36,10,36,9,35,8,34,7,33,6,32,4,31,3,30,2,29,1,28,1,27,0,26,0,25,0,24,0,23,0,22,0,21,0,20,0,19,0,18,0,17,0,16,0,15,0,14,0,13,0,12,0,11,0,10,0,9,0,8,0,7,0,6,0,5,0,4,0,3,0,2,0,1,0,0,22,0],
        type: 'poly'
      };

    
    var marker = new google.maps.Marker({
        position: coord,
        map: mapReferance,
        title:name,
        draggable: false,
        raiseOnDrag: false,
        icon: image,
        shadow: shadow,
        shape: shape
    });
    
    var infowindow = new google.maps.InfoWindow({
        content: info
    });
    
    //var infoBoxObject = {latlng: marker.getPosition(), map: map, infoContent:info, tiderContent: tider, indexVal: index, title: name, logo: logo };
    var infoBoxObject = {latlng: marker.getPosition(), map: map, infoContent:info, tiderContent: tider, merContent: mer, indexVal: index, title: name, logo: logo, thumb: thumb, img: img};
    
    google.maps.event.addListener(marker, 'click', function() {
        if(window.currentInfo != undefined) {
            window.currentInfo.remove();
            window.currentInfo.setMap(null);
            window.currentInfo = null;
        }
        //window.currentInfo = new InfoBox({latlng: marker.getPosition(), map: map, infoContent:info, tiderContent: tider, indexVal: index, title: name, logo: logo });
        window.currentInfo = new InfoBox(infoBoxObject);
    });
    //marker.click();
    window.mapMarkers[segment] = marker;
    window.mapInfo[segment] = infoBoxObject;
    window.hashLocators[index] = segment
}

function calcRoute() {
  var start = document.getElementById("fromAddress").value;
  var end = document.getElementById("forhandlerSelect").value;
  var request = {
    origin:start, 
    destination:end,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
      var FullscreenURL = "http://www.google.com/maps?saddr="+start+",Norge&daddr="+end;
      $("a#routeFullscreen").attr("href", FullscreenURL).attr("target","_blank").css({display:"block"});
    } else {
      $("a#routeFullscreen").css({display: "none"}); 
    }
  });
}

function centerFylke(fylkesnavn, mapReferance) {
    fylkesnavn = fylkesnavn+", Norge";
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': fylkesnavn }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
      }
    });
}

function setDestination(latlon) {
    if(latlon) {
        jQuery("#forhandlerSelect").val(latlon);
        jQuery("form#drivingRoute").show();
    }
}

function calculateTimeout(currElement, nextElement, opts, isForward) { 
    var index = opts.currSlide; 
    return timeouts[index] * 1000; 
} 
