/*jslint browser: true */ /*global jQuery: true */

/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

// TODO JsDoc

/**
 * Create a cookie with the given key and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String key The key of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given key.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String key The key of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function (key, value, options) {

    // key and value given, set cookie...
    if (arguments.length > 1 && (value === null || typeof value !== "object")) {
        options = jQuery.extend({}, options);

        if (value === null) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? String(value) : encodeURIComponent(String(value)),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

/* Swedish initialisation for the jQuery UI date picker plugin. */
/* Written by Anders Ekdahl ( anders@nomadiz.se). */
jQuery(function($){
    $.datepicker.regional['sv'] = {
		closeText: 'Välj',
        prevText: '&laquo;Förra',
		nextText: 'Nästa&raquo;',
		currentText: 'Idag',
        monthNames: ['Januari','Februari','Mars','April','Maj','Juni','Juli','Augusti','September','Oktober','November','December'],
        monthNamesShort: ['Jan','Feb','Mar','Apr','Maj','Jun', 'Jul','Aug','Sep','Okt','Nov','Dec'],
		dayNamesShort: ['Sön','Mån','Tis','Ons','Tor','Fre','Lör'],
		dayNames: ['Söndag','Måndag','Tisdag','Onsdag','Torsdag','Fredag','Lördag'],
		dayNamesMin: ['Sö','Må','Ti','On','To','Fr','Lö'],
		weekHeader: 'V',
        dateFormat: 'yy-mm-dd',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: '',
		stepHours: 1,
		stepMinutes: 5,
		time24h: true,
		constrainInput: false,
    	duration: '',
        showTime: true,
        showWeek: true};
    $.datepicker.setDefaults($.datepicker.regional['sv']);
});

setCookieArray = function (name, title){
	var i,
		data,
		cookie = $.cookie(name); 
	if(!cookie){
		$.cookie(name,title, {expires: 30});
		return;
	}
	data = cookie.split('^');
	for(i=0; i<data.length; i++){
		if(data[i] == title)
			return;
	}
	$.cookie(name, cookie + '^' + title, {expires: 30});
}

delCookieArray = function (name, title){
	var i,
		oldCookie,
		newCookie,
		cookie = $.cookie(name);
	if(!cookie)
	    return;
	oldCookie = cookie.split('^');
	newCookie = new Array(); 
	for(i=0; i<oldCookie.length; i++){
		if (oldCookie[i] != title)
			newCookie.push(oldCookie[i]);
	}
	$.cookie(name, newCookie.join('^'), {expires: 30});
}

/**
 * Image preview script 
 * powered by jQuery (http://www.jquery.com)
 * 
 * @author by Alen Grakalic (http://cssglobe.com)
 * 
 * for more info visit http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
 */
imagePreview = function(large){	
	xOffset = 10;
	yOffset = 20;
	$('img.preview').hover(function(e){
		var src = this.src.replace('preview', 'day') +'?' + Math.random();
		if (large) {
			src = src.replace('graph/', 'graph/large_')
		}
		$('body').append('<p id="preview"><img src="'+ src + '" alt="Laddar bild..." /></p>');								 
		$('#preview')
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");						
    },
	function(){
		$('#preview').remove();
    });	
	$("img.preview").mousemove(function(e){
		$('#preview')
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});	
	if (!large) {
		$('#tabs-graphs a').click(function() {
			$('#preview').remove();
			$('#tabs').tabs('url', 'tabs-detail', this.href).tabs('select', 'tabs-detail');
			return false;
		});
	}
	setTimeout(updateGraphs, 600000);
	
};

updateGraphs = function(){
	$('#tabs').tabs('load', 'tabs-graphs');
};

resizeWindow = function( e ) {
	var height = $(window).height() - $('#ui-tabs-nav').height() - 110;
	$('.ui-tabs-panel').css({'height': height, 'overflow': 'auto'});
}

// starting the script on page load
$(function() {
	$("#tabs").tabs({
		cache: false,
		ajaxOptions:{cache:false},
		spinner: 'Laddar...',
		cookie: { expires: 30, path: '/', name: 'Dahlen.WS-Tab' }
//		select: function(e, ui) {
//			location.hash = ui.tab.hash;
//		}	
//	}).bind('tabsshow', function(e, tab){
//		if(typeof(window.localUpdate) == 'function')
//			localUpdate();
	});
	$('#graphs > img').live('click', function() {
		delCookieArray('DahlenCompare', this.id);
		$(this).remove();
	});
	if ($.browser.webkit && $.browser.version == '528.5')
		return;
	if ($.browser.opera && $.browser.version == '9.80')
		return;
	resizeWindow();
	$(window).bind('resize', resizeWindow);
//	$("#tabs").tabs('select', location.href.replace(/^.*#/, "#"))
});

