﻿if (typeof console === "undefined" || typeof console.log === "undefined") {
	console = {};
	console.log = function () { };
}

$('html').addClass('js');
// Document ready
$(document).ready(function () {
    $('html').removeClass('js');

    try {
        $("#ctl00_MainBodyRegion_ddlCityList").msDropDown({ rowWidth: 120 });
    } catch (e) {
    }

    $(".boendeListan #ctl00_MainBodyRegion_ddlCityList").change(function () {
        window.location = $(this).find("option:selected").val();
    });

    $(document).click(function () {
        if ($("#shareDrop").is(":visible")) {
            $("#shareDrop").hide();
        }
    });

    $("#shareDrop").click(function (e) {
        e.stopPropagation();
    });

    $("#yourname").focus(function () {
        if ($(this).val() == "Ditt namn") {
            $(this).val("");
        }
    });

    $("#yourname").blur(function () {

        if ($(this).val() == "") {
            $(this).val("Ditt namn");
        }
    });

    $("#mail").focus(function () {
        if ($(this).val() == "Din väns e-postadress") {
            $(this).val("");
        }
    });

    $("#mail").blur(function () {
        if ($(this).val() == "") {
            $(this).val("Din väns e-postadress");
        }

    });

    $("#text").focus(function () {
        if ($(this).val() == "Ditt meddelande") {
            $(this).val("");
        }
    });

    $("#text").blur(function () {
        if ($(this).val() == "") {
            $(this).val("Ditt meddelande");
        }
    });

    // Alert-IR Iframe auto height
    document.domain = document.domain.replace(/(.*\.)?([^.]+\.[^.]+)$/, '$2');

    //bubbla lista
    $(".PuffItem").hoverIntent({
        sensitivity: 5,
        interval: 20,
        over: showBubbla,
        timeout: 20,
        out: hideBubbla
    });

    function showBubbla() {
        var bubbla = $(this).find('.PuffItemBubbla');
        var width = $(this).width();
        var pos = $(this).offset();
        var eWidth = $(this).outerWidth();
        var mWidth = $(bubbla).outerWidth();
        var left = (pos.left + eWidth - mWidth) + "px";
        var top = 80 + pos.top + "px";

        $(bubbla).css({
            position: 'absolute',
            zIndex: 5000,
            left: left,
            top: top
        });

        $(bubbla).show();
    }

    function hideBubbla() {
        $(this).find('.PuffItemBubbla').hide();
    }

    // jQuery - hoverIntent configuration
    $("#siteswitchcontainer").hoverIntent({
        sensitivity: 3,
        interval: 200,
        over: ShowSiteSwitch,
        timeout: 500,
        out: HideSiteSwitch
    });

    function ShowSiteSwitch() {
        $(this).css('background', 'url(/Templates/images/siteswitch_arrow_hover.gif) top right no-repeat');

        var navoffset = $('#navigation').offset();
        var siteswitchposition = navoffset.left + $('#navigation').width() + 14 - $('#siteswitch').width();

        // Fix weird IE6 margin error by adding 11px.
        if ($.browser.msie && $.browser.version < 7)
            siteswitchposition = siteswitchposition + 11;

        $('#siteswitch').css('left', siteswitchposition + 'px');
        $('#siteswitch').css('visibility', 'visible');
    }

    function HideSiteSwitch() {
        $('#siteswitch').css('visibility', 'hidden');
        $(this).css('background', 'url(/Templates/images/siteswitch_arrow.gif) top right no-repeat');
    }

    // Tab script
    if (typeof (selectedTab) == 'undefined') {
        selectedTab = 0;
    }

    if ($('#TabContainer').length > 0) {
        var pIndex = -1;
        var images = $('#TabContainer').find('img');

        $(images).each(function (index) {
            if ($(this).is(':visible')) {
                pIndex++;
            }

            if (selectedTab == pIndex) {
                $(this).hide();
                $(images[index + 1]).show();
            }
        });

        $('#TabContainer > ul').tabs({
            selected: selectedTab,
            select: function (e, ui) {
                $(images).each(function () {
                    if ($(this).attr("class") == "highlight")
                        $(this).hide();
                    else
                        $(this).show();
                });
                var currentTabImages = $(ui.tab).find('img');
                $(currentTabImages[0]).hide();
                $(currentTabImages[1]).show();
                var uiIndex = ui.index;

                $.ajax({
                    type: "POST",
                    url: "/tab.aspx?tab=" + uiIndex + "",
                    data: "",
                    success: function (msg) {

                        reInitMap();

                    }
                });
            }
        });
    }

    if ($('#tabs').length > 0) {
        var pIndex = -1;
        var images = $('#tabs').find('img');

        $(images).each(function (index) {
            if ($(this).is(':visible')) {
                pIndex++;
            }

            if (selectedTab == pIndex) {
                $(this).hide();
                $(images[index + 1]).show();
            }
        });

        $('#tabs > ul').tabs({
            selected: selectedTab,
            select: function (e, ui) {
                location.href = ui.tab;
                return false;
            }
        });
    }

    // Snabbfakta - tabs
    var mapIsReLoaded = false;
    if ($("#right").find("img").length == 0) {
        $("#right").hide();
    }
    $(".tab1").click(function () {
        $(".karta").hide();
        $(".fakta").show();
        $(".tab1").removeClass("bbottom");
        $(".tab2").addClass("bbottom");
        $(".tab1").find("img").attr("src", "/templates/images/snabbfakta.gif");
        $(".tab2").find("img").attr("src", "/templates/images/visakarta.gif");
    });

    $(".tab2").click(function () {
        $(".karta").show();
        $(".fakta").hide();
        $(".tab1").addClass("bbottom");
        $(".tab2").removeClass("bbottom");
        $(".tab1").find("img").attr("src", "/templates/images/snabbfakta_link.gif");
        $(".tab2").find("img").attr("src", "/templates/images/visakarta_active.gif");

        if (!mapIsReLoaded) {
            reInitMap();
            mapIsReLoaded = true;
        }

    });

});
var exp = false;
var exp1 = false;
function ToggleUtilityNav(obj) {
    if (exp) {
        $("#search").hide(300);
    	$(obj).css("color", "#a8a8a8");
        exp = false;
    }
    else {
        $("#Tipsa").hide(300);
        $("#tipsC").hide(300);
        $("#search").show(300);
    	$(obj).css("color", "#89cce2");
        exp = true;
        exp1 = false;

        // Set focus on searchfield, delay required because of fade effect
        var timer = setTimeout(function() { $("#searchfield").focus(); }, 350);
    }
}

function sendTips() {
    var from = $("#yourname").val();
    var to = $("#mail").val();
    var msg = $("#text").val();
    var urls = escape(document.location);
    urls = urls.replace("http%3A//", "");

    if (from == "") return;
    if (to == "") return;
    if (!checkEmail(to)) return;

    $("#tipsButton").hide();

    $.ajax({
        url: "/Templates/Handlers/tipsa.ashx",
        data: { from: from, to: to, msg: msg, urls: urls, rnd: (new Date().getTime()) },
        success: function(data) {
            if (data.OK) {
                openShare();
                exp1 = false;
                exp = false;
                $("#yourname").val("Ditt namn");
                $("#mail").val("Din väns e-postadress");
                $("#text").val("Ditt meddelande");
                $("#tipsButton").show();
                $('#dialog').dialog({ modal: true });
            } else {
                openShare();
                exp1 = false;
                exp = false;
                $("#yourname").val("Ditt namn");
                $("#mail").val("Din väns e-postadress");
                $("#text").val("Ditt meddelande");
                $("#tipsButton").show();
                $('#dialog').dialog({ modal: true });
            };
        }
    });
    
    /*$.ajax({
    type: "POST",
    url: "/Templates/Handlers/tipsa.ashx",
    data: {
    ajax: 'true', from: from, to: to, msg: msg, urls: urls
    },
    dataType: "json",
    success: function(result) {
    if (result.OK) {
    $("#Tipsa").hide(300);
    $("#tipsC").hide(300);
    exp1 = false;
    exp = false;
    $("#yourname").val("");
    $("#mail").val("");
    $("#text").val("");
    } else {
    $("#Tipsa").hide(300);
    $("#tipsC").hide(300);
    exp1 = false;
    exp = false;
    }
    }
    });*/

}
function checkEmail(email) {

    var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
    if (!filter.test(email)) {

        return false;
    }
    else {
        return true;
    }
}

function ToggleUtilityNavTips(obj) {
    if (exp1) {
        $("#Tipsa").hide(300);
        $(obj).css("color", "#a8a8a8");
        $("#tipsC").hide(300);
        exp1 = false;
    }
    else {
        $("#search").hide(300);
        $("#Tipsa").show(300);
        var off = $("#Tipsa").offset();

        $("#tipsC").css("left", off.left - 178);
        $("#tipsC").css("top", off.top - 17);
        $("#tipsC").show(300);
        $(obj).css("color", "#89cce2")
        exp1 = true;
        exp = false;

        // Set focus on searchfield, delay required because of fade effect
        var timer = setTimeout(function() { $("#mail").focus(); }, 350);
    }
}

$("#Tipsbox").click(function() {
    $("#Tipsa").hide(300);
    $("#tipsC").hide(300);
    exp1 = false;
    exp = false;
});
// Ladda events
function addLoadEvent(func) {
    var oldonload = window.onload;

    if (typeof window.onload != 'function') {
        window.onload = func;
    }
    else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

function LoadImage(src, callback) {
    var i = new Image();
    i.onLoad = callback();
    i.src = src;
}

function SetHeadline(t, s, a) {
    LoadImage(s, function() {
        var img = jQuery("<img>").attr("src", s).attr("alt", a);
        if (s.indexOf(".png") > -1)
            img.attr("class", "png");
        $(t).html(img);
    });
}

function GetAreaContainerId(item) {
    if (item != null) {
        var latitude = item.getLatLng().lat();
        var longitude = item.getLatLng().lng();

        return latitude.toString().replace(".", "") + longitude.toString().replace(".", "");
    }
    return false;
}

function ShowLocationInfo(item) {
    $("#" + GetAreaContainerId(item) + "").css("border", "dotted 2px #c5c5c5");
}

function HideLocationInfo(item) {
    $("#" + GetAreaContainerId(item) + "").css("border", "solid 2px #fff");
}

function GoToLocation(item) {
    var link = $("#" + GetAreaContainerId(item) + "").find('div.linkholder').html();
    window.location.href = link;
}

function ShowLocationInfo2(item) {
    $("#" + item + "").css("border", "dotted 2px #c5c5c5");
}

function HideLocationInfo2(item) {
    $("#" + item + "").css("border", "solid 2px #fff");
}

function GoToLocation2(item) {
    var link = $("#" + item + "").find('a').attr('href');
    window.location.href = link;
}

$('.round').each(function() {
    var b = $(this);
    var tt = b.html() || b.val();
    //var html = b.html();
//    if ($(':div', this)) {
        
        //b = $('<div>').insertAfter(this).addClass(this.className).attr('id', this.id);
        //$(this).remove();
//    }
    b.text('').prepend('<i></i>').append($('<span>').html(tt).append('<i></i><span></span>'));
});

function openShare() {
    if ($("#shareDrop").is(":visible")) {
        $("#shareDrop").hide();
    }
    else 
    {
        
        $.get('/share.aspx', function(data) {
          $('#shareDiv').html(data);
          $("#shareDrop").show();
        });

        //if ($.browser.safari()) {
	    	$("#shareDrop").css("left", "-298px");
        //}
        //else {
//            if ($.browser.win() || $.browser.safari()) {
		    	$("#shareDrop").css("left", "-299px");
//            } else {
//                $("#shareDrop").css("left", "-297px")
//            }
        //}
    	$("#shareDrop").css("top", "-5px");
    }
    
}

function reInitMap() {
	$(".googlemap").each(
		function () {
			var clientId = this.id;
			var artemId = (clientId.indexOf("_") != -1) ? clientId.slice(clientId.lastIndexOf("_")+1) : clientId;
			_reInitMap(artemId, clientId);
		}
	);
}

function _reInitMap(artemId, clientId) {
	
	var ArtemMap = window[artemId];
	var map = (ArtemMap != null) ? ArtemMap.get_map() : null;
	var domMap = document.getElementById(clientId);
	var mapCenter = (ArtemMap != null) ? ArtemMap.Center : null;
	
	if (domMap && map && mapCenter) {
		domMap.style.width = ArtemMap.Width;
		domMap.style.height = ArtemMap.Height;
		
		google.maps.event.trigger(map, 'resize');
		map.setZoom( map.getZoom() );
		map.setCenter( new google.maps.LatLng(mapCenter.Latitude, mapCenter.Longitude) );
	}
}

var GoogleMapMarkerEvents = {
	click: function () { /*console.log('click');*/ },
	mouseover: function () { /*console.log('mouseover');*/ },
	mouseout: function () { /*console.log('mouseout');*/ }
};

function GoogleGetItem(marker) {
	var item;
	if (marker.metadata != null) {
		item = $("#item_" + marker.metadata.id + "");
	} else {
		var itemId = marker.position.lat().toString().replace(/\./, "") + marker.position.lng().toString().replace(/\./, "");
		item = $("#item_" + itemId + "");
	}
	return item;
}

function GoogleGotoLocation(marker) {
	var item = GoogleGetItem(marker);
	var link = item.find('a').attr('href');
	if (link != null) {
		window.location.href = link;
	}
}

function GoogleShowLocationInfo(marker) {
	var item = GoogleGetItem(marker);
	item.css("border", "dotted 2px #c5c5c5");
}

function GoogleHideLocationInfo(marker) {
	var item = GoogleGetItem(marker);
	item.css("border", "solid 2px #fff");
}


$(document).ready(
	function () {

		$(".googlemap").each(
			function () {
				var clientId = this.id;
				var artemId = (clientId.indexOf("_") != -1) ? clientId.slice(clientId.lastIndexOf("_") + 1) : clientId;
				var ArtemMap = window[artemId];
				var map = (ArtemMap != null) ? ArtemMap.get_map() : null;
				var mapCenter = (ArtemMap != null) ? ArtemMap.Center : null;

				if (map != null && mapCenter != null) {

					for (var i = 0; i < ArtemMap.Markers.length; i++) {
						var marker = ArtemMap.Markers[i];

						if (marker != null && marker.get_marker != null) {
							var gmarker = marker.get_marker();

							// hack for ledigalyanobject utan koordinat
							if (marker.Text != null) {
								gmarker.metadata = { id: marker.Text };
							}
							else if (marker.Position) {
								gmarker.metadata = { id: marker.Position.Latitude.toString().replace(/\./, "") + marker.Position.Longitude.toString().replace(/\./, "") };
							}

							google.maps.event.addListener(gmarker, 'click', function () {
								GoogleMapMarkerEvents.click(this);
							});
							google.maps.event.addListener(gmarker, 'mouseover', function () {
								GoogleMapMarkerEvents.mouseover(this);
							});
							google.maps.event.addListener(gmarker, 'mouseout', function () {
								GoogleMapMarkerEvents.mouseout(this);
							});

						}

					}

				}
			}
		);

	}
);
