$(document).ready(function () {

    //tooltips
    tooltipFunctionality();

    //tab functionality
    tabFunctionality();

    //infobubble functionality
    infoBubbleFunctionality();
    traficInfoBubble();

    //form functionality for reseplanerare
    travelplanerSearchform();
    travelplanerFillForm();

    //textfield functionality
    textfieldFunctionality();

    $("span.readmore[rel]").click(function () {
        var url = $(this).attr("rel");
        window.location = url;
    });

    $(".timetables-table tr").each(function () {
        $(this).find("td:eq(2)").addClass("filesize");
    });

    $(".timetables-table a").click(function (e) {
        e.preventDefault();
        var url = $(this).attr("href").replace("./Blue","/Blue");
        window.open(url, "Tidtabell", "menubar=1,resizable=1,width=800,height=650");
    });

    if ($(".maincolumnframe .smallblockwithpadding").length > 0) {
        var columnheight = 0;
        $(".maincolumnframe .smallblockwithpadding").each(function () {
            var height = $(this).outerHeight();
            if (height > columnheight) {
                columnheight = height;
            }
        });
        $(".maincolumnframe .smallblockwithpadding").height(columnheight);
    }

});

function travelplanerSearchform() {

    if ($("#frmMain").length > 0) {
        //set date and time on form
        var currentTime = new Date();
        var time = currentTime.getHours() + ":" + formatNumber(currentTime.getMinutes(), 0);
        var date = currentTime.getFullYear() + "-" + formatNumber(currentTime.getMonth(), 1) + "-" + formatNumber(currentTime.getDate(), 0);

        //write values
        $("input[name='inpTime']").attr("value", time).attr("alt", time);
        $("input[name='inpDate']").attr("value", date).attr("alt", date);
    }
    

    //get all form data on submit and create GET string
    $("#frmMain").submit(function (e) {
        e.preventDefault();

        var targetURL = $("input[name='__EasyPostBackAction']").val();
        var vars = "";
        $(this).find("input").each(function () {
            try {
                if (!$(this).attr("name").match("Easy")) {
                    vars = vars + $(this).attr("name") + "=" + $(this).val() + "&";
                }
            } catch (err) { 
                //ie throws error when attr[name] not present, try/catch is just a way to ignore this... 
            }
        });
        var fullURL = targetURL + "?" + encodeURIComponent(vars);
        window.location = fullURL;

    });
}

function formatNumber(month, factor) {
    var monthStr = "" + (month+factor);
    if (monthStr.length == 1) {
        return "0" + monthStr;
    } else {
        return monthStr;
    }
}

function travelplanerFillForm() {

    //only when the form is present
    if ($("#travelplannerform").length > 0) {
        var variablesStr = window.location.href.split("?")[1];
        var variablesArr = decodeURIComponent(variablesStr).split("&");

        //go through all GET variables and enter value into corresponding input field
        for (var i = 0; i < variablesArr.length; i++) {
            if (variablesArr[i].length > 2) {
                var name = variablesArr[i].split("=")[0];
                var varValue = decode(variablesArr[i].split("=")[1]);

                var field = $("input[name='" + name + "']");
                field.attr("value", varValue)
            }

        }

        //ok, we're done, post the form!
        $("#travelplannerform").submit();
    }
}

function decode(str) {
    var newstr = decodeURIComponent(str.replace(/\+/g, " "));
    return newstr;
}



//  --------------------- OS, BROWSER SPCIFIC FUNCTIONALITY --------------------- //

//for mac only, add own stylesheet
function macSpecificFunctionality() {
	$("head").append("<link>");
	css = $("head").children(":last");
	css.attr({
	  rel:  "stylesheet",
	  type: "text/css",
	  href: "/BluerangeEasy/templates/1003/css/mac.css"
	});
}

//for ie6 only, add own stylesheet
function ie6SpecificFunctionality() {
	$("head").append("<link>");
	css = $("head").children(":last");
	css.attr({
	  rel:  "stylesheet",
	  type: "text/css",
	  href: "/BluerangeEasy/templates/1003/css/ie6.css"
	});
}


//  --------------------- INPUT-FUNCTIONALITY --------------------- //

function textfieldFunctionality() {
	
	// SET ON FOCUS VALUES FOR ALL TEXTFIELDS
    $("input.textfield:not(.nofocus), #searchfield").each(function () {
		$(this).val($(this).attr("alt"));
	});
	// CLEAR VALUES ON FOCUS FOR ALL TEXTFIELDS
    $("input.textfield:not(.nofocus), #searchfield").focus(function () {
		if($(this).val()==$(this).attr("alt")) {
			$(this).val("");
		}
	});
	// ADD ORIGINAL VALUE IF EMPTY FOR ALL TEXTFIELDS
    $("input.textfield:not(.nofocus), #searchfield").blur(function () {
		if($(this).val()=="") {
			$(this).val($(this).attr("alt"));
		}
    });

    //check if time is in correct format
    $("#inpTime").change(function () {
        var oInpTime = document.getElementById('inpTime');
        checkTime(oInpTime);
    });
}

function checkTime(oInpTime) {
    var retVal = false
    var strVal = oInpTime.value

    //try to correct userinput

    if (strVal.length == 4 && !isNaN(strVal)) { strVal = strVal.substr(0, 2) + ':' + strVal.substr(2, 2) } //case ####
    strVal = strVal.replace(".", ":") //case ##.##

    if (strVal.length == 1 && !isNaN(strVal)) { strVal = "0" + strVal + ':' + "00" } //case #
    if (strVal.length == 2 && !isNaN(strVal)) { strVal = strVal + ':' + "00" } //case ##
    if (strVal.length == 3 && !isNaN(strVal)) { strVal = "0" + strVal.substr(0, 1) + ':' + strVal.substr(1, 2) } //case ###
    oInpTime.value = strVal

    strVal = strVal.substr(0,2) + strVal.substr(3,2)

    if(strVal.length == 4){

        if(!isNaN(strVal)){

            while(strVal.charAt(0) == '0') strVal = strVal.substring(1, strVal.length)

            if(strVal == '') strVal = '0'

            var intTime = parseInt(strVal)

            if(intTime<2400 && intTime >= 0){

                if(intTime%100<60){
                    retVal = true

                }

            }

        }

    }

    if (retVal == false) {

        alert("Felaktig värde för klockslag:" + oInpTime.value)

        oInpTime.focus()

    }

}

// --------------------- INFO BUBBLES --------------------- //
var firstSlideShowing = 0;

function infoBubbleFunctionality() {
	
	//show infobubble when image is clicked
	$("img.imgWithInfoBubble").click(function() {
		
		//is there any info to show in infobubble?
		if ($(this).attr("alt").length > 0) {
			
			//create info in bubble
			var bubbleInfo = $(this).attr("alt");
			if (bubbleInfo.match("::")) {
				bubbleInfo = "<h2>"+bubbleInfo.split("::")[0]+"</h2><p>"+bubbleInfo.split("::")[1]+"</p>";
			} else {
				bubbleInfo = "<p>"+bubbleInfo+"</p>";
			}
			
			//create the bubblecontainer
			var bubbleContainer = createInfoBubbleContainer(bubbleInfo, true, true);
			
			//position infobubblearrow over image
			var slideNr = parseInt($(this).attr("ref"));
			var left = 57 + (92 * (slideNr - firstSlideShowing - 1));
			bubbleContainer.find(".infoBubbleArrow").css("left", left);
				
		    //fade in the bubble
			bubbleContainer.appendTo(".weeklyBubbleFrame");
		    bubbleContainer.css("opacity", 0).show().animate({ bottom: 0, opacity: 1 }, 500); //.fadeIn(200);
		    $("body").addClass("noOverflow");
		
		}
	});
	
	//fade out bubble when clicked on page, but not when clicking inside the infobubble
	$(".infoBubble").mouseup(function() {
		return false
	});
    $("#darkframe, .closeInfoBubble").live("mouseup", function () {
	    $(".infoBubble").animate({ bottom: 40, opacity: 0 }, 400, function () { $(this).remove() }); //.fadeOut(100).remove();
	    $(".startpagenews .fullcontent").animate({ bottom: 110, opacity: 0 }, 400); //.fadeOut(100).remove();
	    $("#darkframe").fadeOut(100);
	    $("body").removeClass("noOverflow");
	});
}

function traficInfoBubble() {
    $(".startpagenews a").not("[rel='newpage']").click(function (e) {
        e.preventDefault();

        var bubbleContainer = $(this).next(".fullcontent");
        bubbleContainer.css("opacity", 0).show().animate({ bottom: 70, opacity: 1 }, 500); //.fadeIn(200);
        $("body").addClass("noOverflow");

        //fadeout background?
        if (!($.browser.msie)) {
            $("#darkframe").width($(document).width()).height($(document).height()).fadeIn(400);
        }

    });

    //fade out bubble when clicked on page, but not when clicking inside the infobubble
    $(".startpagenews .fullcontent").mouseup(function () {
        return false
    });

    $(".fullcontent .closeInfoBubble").click(function () {
        $(".startpagenews .fullcontent").animate({ bottom: 110, opacity: 0 }, 400); //.fadeOut(100).remove();
        $("#darkframe").fadeOut(100);
        $("body").removeClass("noOverflow");
    });
}

function createInfoBubbleContainer(content, darkbg, showClose) {
	var bubbleContainer = $("<div></div>").addClass("infoBubble rounded_M");
	var innerBubbleContainer = $("<div></div>").addClass("innerBubble rounded_S").html(content).appendTo(bubbleContainer);
	if (showClose == true) {
	    $("<img/>").addClass("closeInfoBubble").attr("src", "/BluerangeEasy/templates/1003/images/closeInfoBubble.gif").prependTo(innerBubbleContainer);
	}
	$("<img/>").addClass("infoBubbleArrow").attr("src", "/BluerangeEasy/templates/1003/images/spot.gif").appendTo(innerBubbleContainer);
	
	//fadeout background?
	if (darkbg != null && !($.browser.msie)) {
		$("#darkframe").width($(document).width()).height($(document).height()).fadeIn(400);
	}
	
	return bubbleContainer;
}
function setInfoBubbleArrowPos(currentSlideNumber, totalSlideQty, currentSlideHtmlObject, moveSlideQt) {
	firstSlideShowing = currentSlideNumber;
}


// --------------------- TOOLTIPS --------------------- //

function tooltipFunctionality() {

    if (!($.browser.msie && parseInt($.browser.version) < 7)) {
	    //create tooltip functionality IF this is not IE6
	    $("a[tooltip]").hover(function(e) {
		    e.preventDefault(); 

		    //create tooltipcontainer
		    var tiptext = $(this).attr("tooltip");
		    var bubbleContainer = createInfoBubbleContainer("<p>"+tiptext+"</p>", null, false);
		
		    //animate the bubble info position
		    bubbleContainer.appendTo($(this).parent("li")).stop(true, true).delay(1000).show().css("opacity", 0).animate({opacity: 1, bottom: 44}, 300);//.fadeIn(300);
	
	    }, function() {
		    //hide and then remove the bubble
		    $(this).parent().find(".infoBubble").stop(true, true).animate({opacity: 0, bottom: 65}, 200, function() {$(this).remove()});//.fadeOut(200, function() {$(this).remove()});
        });
    }
}


// --------------------- TABS --------------------- //
var tabFadeInTime = 200;
var tabFadeOutTime = 100;
var animateTabHeight = true;
var fixedHeight = 0;

//if this is IE 6-8, dont fade in, just show
if ($.browser.msie && $.browser.version < 9) {
	tabFadeInTime = 0;
	tabFadeOutTime = 0;
}

function tabFunctionality() {

    //set some margins
    $(".tabblock .tab-table-2-columns td:first h3, .tabblock .tab-table-2-columns td:first p, .tabblock .tab-table-2-columns td:first ul").css("margin-right", 30);
    $(".tabblock .tab-table-2-columns td:last").css("padding-left", 30);
	
	//tabs, initiate
    $(".tabblock").each(function () {

        //should block have fixed height?
        if ($(this).attr("fixedheight") !== undefined) {
            fixedHeight = parseInt($(this).attr("fixedheight"));
            
            //set height of container and columns (if any)
            $(this).outerHeight(fixedHeight);
            $(this).find(".yellowborderblock-rightimage").height(fixedHeight - 35);
        }

        var containerWidth = parseInt($(this).width());
        var containerPadding = parseInt($(this).find(".blockbody").css("padding-left").split("px")[0]) + parseInt($(this).find(".blockbody").css("padding-right").split("px")[0]);

        $(this).find(".blockbody").css("opacity", 0).css("display", "none").width(containerWidth - containerPadding);
        setSelectedTab($(this));
    });
	
	//tabs, functionality
    $(".tabblock .tabheader a").not('[rel="link"]').click(function (e) {
        e.preventDefault();
        if ($(this).parent(".tabheader").find("a").length > 1) {
            //get id's for old and new container
            var showingTabId = $(this).parents(".tabblock").find(".tabheader a.selected").attr("rel");
            var toShowTabId = $(this).attr("rel");

            //get new and old container
            var oldTab = $(this).parents(".tabblock").find("div[rel='" + showingTabId + "']");
            var newTab = $(this).parents(".tabblock").find("div[rel='" + toShowTabId + "']");

            //show-new-tab animation
            showNewTab(oldTab, newTab);

            //remove prev selected tab
            $(this).parents(".tabblock").find(".tabheader a").removeClass("selected");

            //highlight new tab
            $(this).addClass("selected");

            //save selected tab in cookie
            saveSelectedTabToCookie(newTab.parents(".tabblock").attr("id"), toShowTabId);

            //update breadcrumb? = show selected tab tital in the breadcrumb
            updateBreadCrumb($(this));
        } else {
            //only one tab - nothing should happen!
        }
    });
	
	// readmore-links (within tabs)
	$("span.readmore").hover(function() {$(this).addClass("readmorehover");}, function() {$(this).removeClass("readmorehover");});
	
	$(".tabheader span").click(function() {
		var url = $(this).attr("rel");
		window.location = url;
	});
}

function updateBreadCrumb(newTab) {
	if(newTab.parents(".maintabcontainer").length > 0) {
	    var tabTitle = newTab.text();
		$("#tabCrumb").text(tabTitle);
		
		//show prev span as link? (if it isn't allready)
		if (!($("#tabCrumb").prev("span").hasClass("showaslink"))) {
			$("#tabCrumb").prev("span").addClass("showaslink");
		}
	}
}
function showNewTab(oldTab, newTab) {
	
	//must set display = block to get height-value
	newTab.css("display","block");
	var newHeight = getElementHeight(newTab) - 10;
	
	//diff-value must be positive, unless animteTabHeight = false
	var diff = newHeight - getElementHeight(oldTab);
	if (animateTabHeight == false) {
		diff = 0;
	} else if (diff < 0) {
		diff = diff - (diff * 2);
	}

    if (fixedHeight == 0) {
        //animate the new tab in three steps: 1. hide the old tab 2. change container height 3. show the new tab
        oldTab.animate({ opacity: 0 }, tabFadeOutTime, function () {
            newTab.parents(".tabblock").animate({ height: newHeight }, diff * 2, function () {
                newTab.animate({ opacity: 1 }, tabFadeInTime, function () {
                    fixIeClearTypeIssue(this);
                    oldTab.css("display", "none");
                });
            });
        });
    } else {
        oldTab.animate({ opacity: 0 }, tabFadeOutTime, function () {
            //newTab.parents(".tabblock").animate({ height: newHeight }, diff * 2, function () {
                newTab.animate({ opacity: 1 }, tabFadeInTime, function () {
                    fixIeClearTypeIssue(this);
                    oldTab.css("display", "none");
                });
            //});
        });
    }
}

function getElementHeight(object) {
	var innerHeight = parseInt(object.height());
	var outerHeight = parseInt(object.outerHeight());
	var padding = parseInt((outerHeight - innerHeight) / 2);
	var height = outerHeight + padding;

    //fix for tabs without padding (they contain columns)
	if (object.parents(".tabwithcolumns")) {
	    height = height + 25;
    }
	return parseInt(height);
}

function fixIeClearTypeIssue(container) {
	//fix cleartype problem in IE 6-8
	if ($.browser.msie && $.browser.version < 9) {
		container.style.removeAttribute('filter');
	}
}

function setSelectedTab(tabContainer) {
	var tabContainerId = tabContainer.attr("id");
	var selectedTab = getSavedTab(tabContainer); //getSelectedTabsFromCookie(tabContainerId);
	var innerContainer;

	//remove prev selected tab
	tabContainer.find(".tabheader a").removeClass("selected");
	tabContainer.find(".blockbody").animate({opacity: 0}, tabFadeInTime);


	if (selectedTab != false) {
		//show selected tab
		innerContainer = tabContainer.find(".blockbody[rel='"+selectedTab+"']");
		innerContainer.css("display", "block").animate({opacity: 1}, tabFadeInTime, function () {
			fixIeClearTypeIssue(this);
		});
		
		//highlight new tab
		tabContainer.find(".tabheader a[rel='"+selectedTab+"']").addClass("selected");
		updateBreadCrumb(tabContainer.find(".tabheader a[rel='"+selectedTab+"']"));
		
	} else {
		//no tab selected, show first
		innerContainer = tabContainer.find(".blockbody:first");
		innerContainer.css("display", "block").animate({opacity: 1}, tabFadeInTime, function () {
			fixIeClearTypeIssue(this);
		});
		
		//highlight new tab
		tabContainer.find(".tabheader a:first").addClass("selected");
		updateBreadCrumb(tabContainer.find(".tabheader a:first"));
	}

    //set height to fixed if chosen for tabcontainer
	if (fixedHeight == 0) {
	    var containerHeight = getElementHeight(innerContainer);
	    tabContainer.height(containerHeight);
	} else {
	    tabContainer.height(fixedHeight);
    }
		
}

function getSavedTab(tabContainer) {
    var selectedTab = false;
    if (tabContainer.hasAttr("rel")) {
        if (window.location.href.match("#" + tabContainer.attr("rel").split(":")[0])) {
            var hashTagVar = window.location.href.split("#")[1];
            selectedTab = "tab" + hashTagVar.split(":")[1];
        } else {
            var tabContainerId = tabContainer.attr("id");
            selectedTab = getSelectedTabsFromCookie(tabContainerId);
        }
    } else {
        var tabContainerId = tabContainer.attr("id");
        selectedTab = getSelectedTabsFromCookie(tabContainerId);
    }

    return selectedTab;
}

function getSelectedTabsFromCookie(tabContainerId) {
    //checks to see if the tabcontainer has a saved value for active tab
	if ($.cookie("tabsCookie") && $.cookie("tabsCookie").match(tabContainerId)) {
		var tabsCookie = $.cookie("tabsCookie").split("|");
		var rel = false;
		
		//go through cookie to find the right value, and return the correct tab-value
		for (var i=0;i<tabsCookie.length;i++) {
			if (tabsCookie[i].split("=")[0] == tabContainerId) {
				rel =  tabsCookie[i].split("=")[1];
				break;
			}
		}
		return rel;
	} else {
		return false;
	}
}

function saveSelectedTabToCookie(tabContainerId, tabRel){
    //save which tab is selected for certain tabcontainer
	if ($.cookie("tabsCookie") && $.cookie("tabsCookie").match(tabContainerId)) {
		var tabsCookie = $.cookie("tabsCookie").split("|");
		var newCookie = "";
		
		//find the right value in cookie
		for (var i=0;i<tabsCookie.length;i++) {
			if (i != 0) {
				newCookie += "|";
			}
			if (tabsCookie[i].split("=")[0] == tabContainerId) {
				//change the value
				newCookie += tabContainerId + "=" + tabRel;
			} else  {
				newCookie += tabsCookie[i];
			} 
		}
		createCookie("tabsCookie",newCookie,7);
		
	} else if ($.cookie("tabsCookie")) {
		//tabcontainer does not exist in cookie, add info to cookie
		var tabsCookie = $.cookie("tabsCookie");
		createCookie("tabsCookie",tabsCookie + "|" + tabContainerId + "=" + tabRel,7);
	} else {
		//no cookie exists, add info to new cookie
		createCookie("tabsCookie",tabContainerId + "=" + tabRel,7);
	}
}


//-------------------------- COOKIE FUNCTIONS --------------------------//

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}


//-------------------------- GOOD-TO-HAVE-FUNCTIONS --------------------------//

$.fn.hasAttr = function (name) {
    return this.attr(name) !== undefined;
};
