var broken = Class.create();
broken.visitSite = Class.create();
window.newRequest = true;
broken.cookie = {
    set: function(name, value, days, path, domain, secure) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            var expires = "; expires=" + date.toGMTString();
        }
        else var expires = "";

        var curCookie = name + "=" + escape(value) +
		    ((expires) ? "; expires=" + expires : "") +
		    ((path) ? ";path=/" : ";path=/") +
		    ((domain) ? "; domain=" + domain : "") +
		    ((secure) ? "; secure" : ";");

        document.cookie = curCookie;

        return this.get(name);
    },

    get: function(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 unescape(c.substring(nameEQ.length, c.length));
        }
        return null;
    }

};

/* 
function broken.visitSite.page
*/
broken.visitSite.page = {

	/* 
	function broken.visitSite.page.init()
	*/
	init: function() {
		this.initializeSWFObjects();
	},

	initializeSWFObjects: function() {
		
		if ($('ClockWithText') != null) {
			var currentTime = new Date();
			var flashvars = {
				gmt: '1',
				time: currentTime.getTime()
			};
			var params = {
				wmode: 'opaque'
			};
			var attributes = {};
			swfobject.embedSWF("/UI/Flash/ClockWithText.swf", "ClockWithText", "220", "30", "8.0.0", "/UI/Flash/expressInstall.swf", flashvars, params, attributes);
		}

		if ($('myMap') != null) {
			var flashvars = {
				path: "/UI/flash/ammap/",
				data_file: escape("/UI/flash/ammap/maps/ammap_data.xml"),
				settings_file:escape("/UI/flash/ammap/maps/ammap_settings.xml"),
				preloader_color:"#999999"
			};
			var params = { wmode: "transparent" };
			var attributes = { id:"ammap", name:"ammap" };
			swfobject.embedSWF("/UI/Flash/ammap/ammap.swf", "myMap", "430", "320", "9.0.0", "/UI/Flash/expressInstall.swf", flashvars, params, attributes);
		}

		if ($('StartPageFlash') != null) {
			/*var startFlashValues = $('startFlashValues').value.split('|');
			var startXmlPath = startFlashValues[0];
			var startSwfFilePath = startFlashValues[1];
			var startImage = startFlashValues[3];
			var startHighJackPath = startFlashValues[2];*/

			var flashvars = {
				_overlay:"no",
				_overlayFILE:"",
				file:"/slide/home.xml",
				config:"/slide/config.xml",
				width:940,
				height:420,
				shownavigation:false
				//xmlPath: startXmlPath,
				//imagePath: startImage,
				//xflashPath: startHighJackPath
			};
			var params = { wmode: 'transparent' };
			var attributes = {};
			//swfobject.embedSWF(startSwfFilePath, "StartPageFlash", startFlashValues[5], startFlashValues[4], "8.0.0", "http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75", flashvars, params, attributes, callbackFn = function(e) { if (!e.success) { $(imgFallback).style.display = "block" } });
			swfobject.embedSWF("/slide/imagerotator.swf", "StartPageFlash", "940", "420", "8.0.0", "/UI/Flash/expressInstall.swf", flashvars, params, attributes);
		}

		if ($('myGall') != null) {
			var flashvars = {
				_overlay:"no",
				_overlayFILE:"",
				file:"/slide/hotel-malaspina.xml",
				config:"/slide/config.xml",
				width:460,
				height:240,
				shownavigation:false
			};
			var params = { wmode: 'transparent' };
			var attributes = {};
			swfobject.embedSWF("/slide/imagerotator.swf", "myGall", "940", "240", "8.0.0", "/UI/Flash/expressInstall.swf", flashvars, params, attributes);
		}


	},
	
	/* 
	function broken.visitSite.page.toggleEvents()
	*/
	toggleEvents: function(sender, target, closeTarget) {
		var l = $$('#' + target + ' li');
		var lCloseTarget = $$('#' + closeTarget + ' li');

		var p = sender.parentNode;

		var sh = 0;
		var shAdd = 0;

		if (target == 'startPageEvents' || target == 'contactList1' || target == 'contactList2') {
			sh = 16;
			shAdd = 19;
		}
		else {
			sh = 32;
			shAdd = 20;
		}
		//var sh = target == 'startPageEvents' ? 16 : 32;
		//var shAdd = target == 'startPageEvents' ? 19 : 20;

		if (p.hasClassName('active'))
			var open = false;
		else
			var open = true;

		lCloseTarget.each(function(item) {
			if (item.hasClassName('active')) {
				item.removeClassName('active');
				item.getElementsByClassName('information')[0].style.display = 'none';

				new Effect.Morph(item, { duration: 0.5, style: { height: sh + 'px'} });
			}
		});

		l.each(function(item) {
			if (item.hasClassName('active')) {
				item.removeClassName('active');
				item.getElementsByClassName('information')[0].style.display = 'none';

				new Effect.Morph(item, { duration: 0.5, style: { height: sh + 'px'} });
			}
		});

		if (open) {
			p.addClassName('active');
			p.getElementsByClassName('information')[0].style.display = 'block';

			var h = sh + shAdd;

			if (broken.util.isIE)
				h += parseInt(p.getElementsByClassName('information')[0].getHeight());
			else
				h += parseInt(p.getElementsByClassName('information')[0].clientHeight);


			new Effect.Morph(p, { duration: 0.5, style: { height: h + 'px'} });
		}
	},

	/* 
	function broken.visitSite.page.setCursor()
	Function to handle a cursors destiny a x-browser way.
	*/
	setCursor: function(dom, remove) {
		/* Should we remove it? */
		if (remove) {
			/* Set the cursor to 'default' */
			dom.style.cursor = 'default';
		}
		/* Show it! */
		else {
			/* Since FF throws errors with cursor:hand; we handle it here. */
			/* Is the browser IE?*/
			if (document.all) {
				/* Set the cursor to 'hand' */
				dom.style.cursor = 'hand';
			}
			else {
				/* Set the cursor to 'pointer' */
				dom.style.cursor = 'pointer';
			}
		}
	},

	/*
	function broken.visitSite.page.switchTempAndCookie()
	*/
	switchTempAndCookie: function(sender, tempType) {
		if (tempType == 'C') {
			$('lblFToday', 'lblFDay1', 'lblFDay2', 'lblFDay3', 'lblFDay4', 'lblFDay5').invoke('hide');
			$('lblCToday', 'lblCDay1', 'lblCDay2', 'lblCDay3', 'lblCDay4', 'lblCDay5').invoke('show');
			$('aCelsius').removeClassName('active');
			$('aFahrenheit').removeClassName('border');
			$('aCelsius').addClassName('border');
			$('aFahrenheit').addClassName('active');
			broken.cookie.set('visitswedentemp', 'C', 9999, '/', false, false);
		}
		else if (tempType == 'F') {
			$('lblFToday', 'lblFDay1', 'lblFDay2', 'lblFDay3', 'lblFDay4', 'lblFDay5').invoke('show');
			$('lblCToday', 'lblCDay1', 'lblCDay2', 'lblCDay3', 'lblCDay4', 'lblCDay5').invoke('hide');
			$('aCelsius').removeClassName('border');
			$('aFahrenheit').removeClassName('active');
			$('aCelsius').addClassName('active');
			$('aFahrenheit').addClassName('border');
			broken.cookie.set('visitswedentemp', 'F', 9999, '/', false, false);
		}
	}

};

broken.widgetCollection = Class.create();
broken.widget = Class.create();
broken.widget.prototype = {

    /* 
    function broken.prototype.initialize()
    Function used to initialize the class.
    */
    initialize: function() {
        /* Fetch all arguments */
        this.arguments = arguments[0];

        /* Itterate through the arcuments.widgets collection*/
        for (var x in this.arguments.widgets) {
            /* Set the current id to the active widget id. */
            this.id = this.arguments.widgets[x].id;
            /* Set the current target to the active widget target. */
            this.target = this.arguments.widgets[x].target;

            /* Check if the widgetLoader doesnt exist? */
            if (!$('widgetLoader') && this.target == 'widgetLoader') {
                /* Call the createWidgetLoader */
                this.createWidgetLoader();
            }

            /* Check if the current widget.id exist. */
            if (typeof broken.widgetCollection[this.id] == 'undefined') {
                /* Set the current widget to the active widget. */
                this.widget = this.arguments.widgets[x];
                /* Set the styles from the active widget. */
                this.applyStyleSheets(this.arguments.widgets[x].style);
                /* Populate the html from the active widget. */
                this.loadHtml(this.arguments.widgets[x].html);
            }
            /* The active widget exist in the collection. */
            else {
                /* Populate the html from the active widget. */
                $(this.target).innerHTML = broken.widgetCollection[this.id].html;
                /* Does the onSuccess event exist? */
                if (typeof this.arguments.onSuccess == 'function') {
                    /* Call the event */
                    this.arguments.onSuccess();
                }
            }
        }
    },

    /* 
    function broken.prototype.createWidgetLoader()
    Function used to build the HTML of the widgetLoader.
    */
    createWidgetLoader: function() {
        /* Build the div called 'widgetLoader' */
        $$('body')[0].appendChild(Builder.node("div", { id: 'widgetLoader', className: 'widgetWrapper' }));
        /* Set the proper height of the div. */
        $('widgetLoader').style.height = $$('html')[0].scrollHeight + 'px';
    },

    /* 
    function broken.prototype.applyStyleSheets()
    Parameter string url = the href to the widget.
    Function used to add rel=stylesheet to the url-link.
    */
    applyStyleSheets: function(url) {
        /* Declare the add variable. */
        var add = true;

        /* Itterate through all links in the head. */
        $$("head link").each(function(item) {
            /* Check if the current item is the url. */
            if (item.url == url) {
                /* Set the add variable to false. */
                add = false;
            }
        });

        /* Should we add the url? */
        if (add) {
            /* Add HTML to the link. */
            $$('head')[0].appendChild(Builder.node("link", {
                /* Set the href to url. */
                href: url,
                /* Set the rel to 'stylesheet' */
                rel: 'stylesheet'
            }));
        }
    },

    /* 
    function broken.prototype.loadHtml()
    Parameter string src = the fully qualified path to the widget.
    Function used to load HTML into widgets.
    */
    loadHtml: function(src) {
        /* Declare _this and populate it with the current this. */
        var _this = this;
        /* Make the AJAX-call with the param src.*/
        new Ajax.Request(src, { method: 'get', evalScripts: true, onSuccess: _this.onLoaded.bind(this) });
    },

    /* 
    function broken.prototype.onLoaded()
    Parameter object transport = the transport from the AJAX-call
    Function used to handle the onLoaded event in a AJAX-call.
    */
    onLoaded: function(transport) {
        /* Check if the target exists in the current this. */
        if ($(this.target)) {
            /* Set the targets innerHTML to the responseText. */
            $(this.target).innerHTML = transport.responseText;
        }
        /* No target exists, use 'poiWrapper' instead. */
        else if ($('poiWrapper')) {
            /* Set the 'poiWrapper' innerHTML to the responseText. */
            $('poiWrapper').innerHTML = transport.responseText;
        }

        /* Set the current this html to the responsetext. */
        this.html = transport.responseText;

        /* Does the onSuccess function exist in the current this arguments? */
        if (typeof this.arguments.onSuccess == 'function') {
            /* Execute the event */
            this.arguments.onSuccess();
        }

        /* Add the current this to the widgetcollection. */
        broken.widgetCollection[this.id] = this;
        /* Make the current widget active. */
        broken.widgetCollection.activeWidget = this;

        /* GoogleAnalytics Added by Tor */
        /* Does the pageTracker Exist and does any of the poiwrappers exist? */
        if (pageTracker != null && ($('mappoi') || $('mappoilight'))) {
            /* Add the pagename to the tracker. */
            pageTracker._trackPageview($('hidden_pageName').value);
        }
    },

    /* 
    function broken.prototype.closeWidget()
    Function is called to remove any widgets/widgetLoaders from the page. 
    Used with the postcardwidget etc.
    */
    closeWidget: function() {
        /* is the browser IE? */
        if (broken.util.isIE) {
            /* Remove the widgetLoader */
            $('widgetLoader').remove();
        } else {
            /* Start the effect fade. */
            new Effect.Fade(this.id, { duration: 0.5,
                /* When finished: */
                afterFinish: function() {
                    /* Remove the widgetLoader */
                    $('widgetLoader').remove();
                }
            });
        }
    }
};


/* 
namespace broken.util
Genereal functions/methods to handle data. 
*/
broken.util = {
    /* Variable used to determine if the browser is Internet Explorer. */
    isIE: Prototype.Browser.IE,
    /* Variable used to determine if the browser is Internet Explorer version 6.x. */
    isIE6: !!(typeof document.body.style.maxHeight == 'undefined' && Prototype.Browser.IE),
    /* Variable used to determine if the browser is Internet Explorer version 7.x. */
    isIE7: !!(typeof document.body.style.maxHeight != 'undefined' && Prototype.Browser.IE),
    /* Variable used to determine if the page and scripts are fully loaded. */
    isLoaded: false,

    /* 
    function broken.util.isEnter()
    Parameter event event = the keypress event.
    Function is called to determine if a event-keypress is ENTER-key.
    Used from input-fields on the page, ie: the search-fields.
    Returns a boolean, true if the key pressed was ENTER.
    */
    isEnter: function(event) {
        /* Return the tested key. */
        return (event.keyCode == Event.KEY_RETURN);
    },

    /* 
    function broken.util.scrollToTop()
    Parameter int target = the pixel value from the pages top the scroller should stop at.
    Parameter int offset = the pixel-offset value from the pages top.
    Parameter int direction = 0 for up, 1 for down.
    Function to scroll the page to the top.
    */
    scrollToTop: function(target, offset, direction) {
        /* Declare the variable t, n pixles from the top. Populate it with fallback if undefined. */
        var t = typeof target == 'undefined' ? 0 : target;
        /* Declare the variable scrollY with the viewports offset top. */
        var offset = typeof offset == 'undefined' ? 0 : offset;
        var direction = typeof direction == 'undefined' ? 0 : direction;
        var scrollY = document.viewport.getScrollOffsets().top;

        /* Declare the variable ppms, pixles per millisecond. Determines the speed of the scroller. */
        var ppms = 30;

        /* sub-function used to scroll ppms pixtels. */
        function doScrollY() {
            /* Declare the variable used to determine the current viewport top. */
            var scrollY = document.viewport.getScrollOffsets().top - offset;


            if (direction == 0) {
                /* Test if the viewport should be scrolled.  */
                if (scrollY > t) {
                    /* Scroll the viewport up. The speed is based on the ppms variable */
                    scrollBy(0, (scrollY - (scrollY + ppms)));
                }
                else {
                    /* Clear the interval/Stop the scrolling */
                    clearInterval(si);
                }
            }
            else {
                /* Test if the viewport should be scrolled.  */
                if (scrollY < t) {
                    /* Scroll the viewport up. The speed is based on the ppms variable */
                    scrollBy(0, (scrollY + (scrollY + ppms)));
                }
                else {
                    /* Clear the interval/Stop the scrolling */
                    clearInterval(si);
                }
            }
        }

        /* Declare the interval, one call per millisecond. */
        var si = setInterval(doScrollY, 1);
    },

    /* 
    function broken.util.trim()
    Parameter string str = the string thats supposed to be trimmed.
    Returns = trimmed string.
    Used to trim strings (remove leading and tailing whitespaces)
    */
    trim: function(str) {
        /* Return the trimmed string, string if modified with regexp. */
        return str.replace(/^\s+/, "").replace(/\s+$/, '');
    },

    /* 
    function broken.util.encode()
    Parameter string string = the string to be encoded.
    Return = the encoded string.
    Function used as a sluice to the private encoding method.
    */
    encode: function(string) {
        /* Return the encoded string, fetched from the private encoding method. */
        return escape(this._utf8_encode(string));
    },


    /* 
    function broken.util.decode()
    Parameter string string = the string to be decoded.
    Return = the decoded string.
    Function used as a sluice to the private decoding method.
    */
    decode: function(string) {
        /* Return the decoded string, fetched from the private decoding method. */
        return this._utf8_decode(unescape(string));
    },

    /* 
    function broken.util._utf8_encode()
    Parameter string string = the string to be encoded.
    Return = the encoded string.
    Function used to encode strings.
    */
    _utf8_encode: function(string) {
        /* Clean the the string */
        string = string.replace(/\r\n/g, "\n");
        /* Declare a empty variable to be used with the return. */
        var utftext = "";

        /* Itterate through the strings characters. */
        for (var n = 0; n < string.length; n++) {
            /* Declare a variable for the active character. */
            var c = string.charCodeAt(n);

            /* Test if the character is ASCII (one bit per character). */
            if (c < 128) {
                /* Add the unmodified character to the return string */
                utftext += String.fromCharCode(c);
            }
            /* Else - test if the character is ANSI (two bits per character). */
            else if ((c > 127) && (c < 2048)) {
                /* Move the character bits. */
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            /* Else - The character is extended ANSI (three bits per character). */
            else {
                /* Move the character bits. */
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        }
        /* Return the encoded string. */
        return utftext;
    },

    /* 
    function broken.util._utf8_decode()
    Parameter string utftext = the string to be decoded.
    Return = the decoded string.
    Function used to decode UTF-8-encoded strings.
    */
    _utf8_decode: function(utftext) {
        /* Declare a empty variable to be used with the return. */
        var string = "";
        /* Declarare the starting position */
        var i = 0;
        /* Declare character variables. */
        var c = c1 = c2 = 0;

        while (i < utftext.length) {
            /* Populate the c-variable with the current character. */
            c = utftext.charCodeAt(i);

            /* Test if the character is ASCII (one bit per character). */
            if (c < 128) {
                /* Add the character to the return string. */
                string += String.fromCharCode(c);
                /* Add one to the itterator. */
                i++;
            }
            /* Else - test if the character is ANSI (two bits per character). */
            else if ((c > 191) && (c < 224)) {
                /* Populate the c2-variable with the next character. */
                c2 = utftext.charCodeAt(i + 1);
                /* Add the characters to the return string. */
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                /* Add two to the itterator. */
                i += 2;
            }
            /* Else - The character is extended ANSI (three bits per character). */
            else {
                /* Populate the c2-variable with the next character. */
                c2 = utftext.charCodeAt(i + 1);
                /* Populate the c3-variable with the second-next character. */
                c3 = utftext.charCodeAt(i + 2);
                /* Add the characters to the return string. */
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                /* Add three to the itterator. */
                i += 3;
            }
        }

        /* Return the decoded string. */
        return string;
    },

    /* Variable to be used with the debugging timer. */
    time: 0,

    /* 
    function broken.util.timeNow()
    Return = the current time.
    Function to get the current time.
    */
    timeNow: function() {
        /* Return the current time. */
        return (new Date()).getTime();
    },

    /* 
    function broken.util.timerStart()
    Function to start the timer.
    */
    timerStart: function() {
        /* Update the time-variable with the current time. */
        this.time = this.timeNow();
    },



    /* 
    function broken.util.timeNow()
    Return = the current tick (difference between the start and the current time).
    Function to tick the debugging timer..
    */
    timerSince: function() {
        /* Return the defferential between the initialization and the current time. */
        return this.timeNow() - this.time;
    }
},

Array.prototype.randomize = function() {
    var i = this.length;
    if (i == 0) return;
    while (--i) {
        var j = Math.floor(Math.random() * (i + 1));
        var tmp1 = this[i];
        var tmp2 = this[j];
        this[i] = tmp2;
        this[j] = tmp1;
    }
    return this;
}


Event.observe(window, 'load', function(event) {
    /* Initialize the broken.visitSite.map. */
    //broken.visitSite.map.init();
    /* Initialize the broken.visitSite.page */
    broken.visitSite.page.init();

    /* Set the broken.util.isLoaded - used to determine that the scripts are fully loaded. */
    broken.util.isLoaded = true;
    enableTooltips();
});

/*javascript for Bubble Tooltips by Alessandro Fulciniti
- http://pro.html.it - http://web-graphics.com */

function enableTooltips(id) {
    var links, i, h;
    if (!document.getElementById || !document.getElementsByTagName) return;
    AddCss();
    h = document.createElement("span");
    h.id = "btc";
    h.setAttribute("id", "btc");
    h.style.position = "absolute";
    document.getElementsByTagName("body")[0].appendChild(h);
    if (id == null) links = document.getElementsByClassName("coords");
    else links = document.getElementById(id).getElementsByClassName("coords");
    for (i = 0; i < links.length; i++) {
        Prepare(links[i]);
    }
}


function Prepare(el) {
    var tooltip, t, b, s, l;
    t = el.getAttribute("title");
    if (t == null || t.length == 0) t = "link:";
    el.removeAttribute("title");
    tooltip = CreateEl("span", "tooltip");
    s = CreateEl("span", "top");
    s.appendChild(document.createTextNode(t));
    tooltip.appendChild(s);
    b = CreateEl("b", "bottom");
    l = el.getAttribute("href");
    //b.appendChild(document.createTextNode(l));
    tooltip.appendChild(b);
    //setOpacity(tooltip);
    el.tooltip = tooltip;
    el.onmouseover = showTooltip;
    el.onmouseout = hideTooltip;
    el.onmousemove = Locate;
}

function showTooltip(e) {
    document.getElementById("btc").appendChild(this.tooltip);
    Locate(e);
}

function hideTooltip(e) {
    var d = document.getElementById("btc");
    if (d.childNodes.length > 0) d.removeChild(d.firstChild);
}

function setOpacity(el) {
    el.style.filter = "alpha(opacity:95)";
    el.style.KHTMLOpacity = "0.95";
    el.style.MozOpacity = "0.95";
    el.style.opacity = "0.95";
}

function CreateEl(t, c) {
    var x = document.createElement(t);
    x.className = c;
    x.style.display = "block";
    return (x);
}

function AddCss() {
    var l = CreateEl("link");
    l.setAttribute("type", "text/css");
    l.setAttribute("rel", "stylesheet");
    l.setAttribute("href", "/UI/Styles/bt.css");
    l.setAttribute("media", "screen");
    document.getElementsByTagName("head")[0].appendChild(l);
}

function Locate(e) {
    var posx = 0, posy = 0;
    if (e == null) e = window.event;
    if (e.pageX || e.pageY) {
        posx = e.pageX; posy = e.pageY;
    }
    else if (e.clientX || e.clientY) {
        if (document.documentElement.scrollTop) {
            posx = e.clientX + document.documentElement.scrollLeft;
            posy = e.clientY + document.documentElement.scrollTop;
        }
        else {
            posx = e.clientX + document.body.scrollLeft;
            posy = e.clientY + document.body.scrollTop;
        }
    }
    document.getElementById("btc").style.top = (posy + 10) + "px";
    document.getElementById("btc").style.left = (posx - 20) + "px";
}