Utils = new (function() {
   var _box, _images = [], _overlay, _this = this, _survey;

   _this.constructor = undefined;
   
   _this.getSID = function() {
      return Config.SID;
   }
      
   _this.getBox = function() {
      return _box;
   }
   
   _this.log = function(str) {
      if ((typeof console != 'object') || (typeof console.log != 'function'))
         return;
      
      if ((typeof Config.isDebug != 'boolean') || (Config.isDebug == false))
         return;
      
      console.log(str);
   }

   _this.getScrollPosition = function() {
      var result = {};
      
      result.x = typeof window.pageXOffset != 'undefined' ? 
            window.pageXOffset : document.documentElement.scrollLeft;

      result.y = typeof window.pageYOffset != 'undefined' ? 
         window.pageYOffset : document.documentElement.scrollTop;
      
      return result;
   }
   
   _this.getClientSize = function() {
      var width, height;
      
      if (typeof window.innerWidth != 'undefined') {
           width  = window.innerWidth,
           height = window.innerHeight
      }
      
      else if (typeof document.documentElement != 'undefined'
            && typeof document.documentElement.clientWidth != 'undefined' 
            && document.documentElement.clientWidth != 0) {
         width  = document.documentElement.clientWidth;
         height = document.documentElement.clientHeight;
      }
      
      else {
         width  = document.getElementsByTagName('body')[0].clientWidth,
         height = document.getElementsByTagName('body')[0].clientHeight
      }

      return { width: width, height: height }
   }
   
   _this.pagePrint = function(html, w, h)
   {
      buf = '<html>'+
            ' <head>'+
            '  <title>Print</title>'+
            '  <link rel="stylesheet" type="text/css" href="/css/liveit.css" />'+
            ' </head>'+
            ' <body style="background: #fff; margin: 10px;" onload="self.print();">'+
            '  <div style="width:'+ w +'px; height:'+ h +'px;">'+ html +'</div>'+
            ' </body>'+
            '</html>';
      
      var doc = window.open('', 'print_win', 'height='+ (h + 20) +', width= '+ (w + 20)).document;
      doc.write(buf);
      doc.close();
   }
            
   _this.newsletterSubscribe = function(txtbox) {
      var email = $('#nl_email')[0].value;
         
      if(!email || typeof email == 'undefined') return;
         
      _this.request({
         url: '/backend/newsletter_subscribe.php',
         data: { email : email },
         type: 'get',
         success: function() {
            
            if(typeof(pageTracker) == 'object')
                pageTracker._trackEvent('Banners', 'Nyhetsbrevsregistrering');
            
            _this.info({
               title: 'Tack',
               text: 'Din e-postadress har registrerats!'
            });
         },
         
         error: function(errno, error) {  
            _this.alert(error); 
         }
      });         
   }

   _this.emailToAFriend = function(tip_from, tip_to, tip_msg) {

      if(typeof tip_from == 'undefined' || tip_from == '' || !tip_from) return;
      if(typeof tip_to   == 'undefined' || tip_to   == '' || !tip_to  ) return;
      if(typeof tip_msg  == 'undefined' || tip_msg  == '' || !tip_msg ) return;
      

      _this.request({
         url: '/backend/tipsa_send.php',
         data: { tip_from : tip_from, tip_to : tip_to, tip_msg : tip_msg, uri : window.location.href },
         type: 'get',
         success: function() {
            _this.info({
               title: 'Tack',
               text: 'Meddeladet har skickats!'
            });
         },

         error: function(errno, error) {
            _this.alert(error);
         }
      });
   };

   _this.preloadImages = function(images) {
      for (var i = 0; i < images.length; i++) {
         var image = new Image(); 
            image.src = images[i];
            _images[_images.length] = image;
         }
   }
      
   _this.destroyOverlay = function() {
      if (typeof _overlay === undefined)
         return;
         
      _overlay.remove();
      
      _overlay = undefined;
   }
      
   _this.closeOverlay = function() {
      _this.log('closeOverlay() deprecated, use destroyOverlay()');
      _this.destroyOverlay();
   }
      
   _this.createOverlay = function(html, width, height) {
      if(_overlay !== undefined)
         return;
         
      _overlay = $('<div class="overlay"><div class="overlay-darken"></div>' + 
                   '<div class="overlay-content ui-dialog ui-widget ui-widget-content ui-corner-all"></div>' + 
                   '</div>');
      
      var content = _overlay.children()[1];

      height = height ? height : 300;
      
      $(content)
         .css('width', width ? width : 300)
         .css('height', height)
         .html(html);

      /*window.onscroll = function() {
         var scroll = _this.getScrollPosition(), size = _this.getClientSize(); 
         content.style.top = (scroll.y + ((size.height / 2) - (height / 2))) + 'px';
         content.style.display = 'block';
      }*/
      
      $('#canvas').append(_overlay);
      
      var scroll = _this.getScrollPosition(), size = _this.getClientSize(); 
      var top = (scroll.y + ((size.height / 2) - (height / 2)));
      content.style.top = (top < 0 ? 0 : top) + 'px';
      content.style.display = 'block';
   }
   
   _this.itsMovieTime = function(youtube,title,ww,wh)
   {
      if(typeof ww != 'number') ww = 550;
      if(typeof wh != 'number') wh = 400;
      
      $('<div><div style="overflow: auto;">'+
               '<object width="425" height="269" '+
               'data="http://www.youtube.com/v/'+youtube+'?fs=1" type="application/x-shockwave-flash">\n'+
               '<param name="data" value="http://www.youtube.com/v/'+youtube+'?fs=1" />\n<param name="src" '+
               'value="http://www.youtube.com/v/'+youtube+'?fs=1" />\n<param name="allowfullscreen"'+ 
               'value="true" />\n</object></div></div>').dialog({
         modal     : true,
         width     : ww,
         height    : wh,
         minHeight : wh,
         resizable : true,
         title     : title,
         close     : function() { $(this).remove(); } // sick
      });      
   }
   
   _this.loadPopup = function(ident, ww, wh)
   {
      if(typeof ww != 'number') ww = 550;
      if(typeof wh != 'number') wh = 400;
      
      $.ajax({
         url      : '/backend/load_popup',
         type     :  'GET',
         cache    : false,
         data     : { ident : ident },
         dataType : 'json',
         success: function(result) {
            if (typeof result.errno != 'number') {
               Utils.alert('Error', 'Ett fel uppstod', 250);
               return;
            }
            else if (result.errno == 0) {
               if(result.data.txt.length == 11){
                  $('<div><div style="overflow: auto;">'+
                    '<div style="font-size:12px"><p>\n<object width="425" height="269" '+
                    'data="http://www.youtube.com/v/'+result.data.txt+'?fs=1" type="application/x-shockwave-flash">\n'+
                    '<param name="data" value="http://www.youtube.com/v/'+result.data.txt+'?fs=1" />\n<param name="src" '+
                    'value="http://www.youtube.com/v/'+result.data.txt+'?fs=1" />\n<param name="allowfullscreen"'+ 
                    'value="true" />\n</object>\n</p></div>' +
                    '</div></div>').dialog({
                     modal     : true,
                     width     : ww,
                     height    : wh,
                     minHeight : wh,
                     resizable : true,
                     title     : result.data.title,
                     close     : function() { $(this).remove(); } // sick
                  });
               }
               else
               {
               
                  $('<div><div style="overflow: auto;">'+ result.data.txt +'</div></div>').dialog({
                     modal     : true,
                     width     : ww,
                     height    : wh,
                     minHeight : wh,
                     resizable : true,
                     title     : result.data.title,
                     close     : function() { $(this).remove(); } // sick
                  });
                  
               }
               return;
            }
         },
         error: function() {
            Utils.alert('Error', 'Ett fel uppstod', 250);
         }
      });

   }
   
   _this.popup = function(url, title, width, height) {
      
      Utils.log('popup called: '+ url +' '+ title +' '+ width +' '+ height);
      if (typeof title != 'string')
         title = 'Web';
         
      if (typeof width != 'number')
         width = 800;
         
      if (typeof height != 'number')
         height = 500;
      
      var buf = '<div class="ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix">'+
                '<div class="tM fl">'+ title +'</div>'+
                '<a class="ui-dialog-titlebar-close ui-corner-all" href="#" onclick="Utils.closePopup(); return false;" role="button" unselectable="on" style="-moz-user-select: none;">'+
                '<span class="ui-icon ui-icon-closethick" unselectable="on" style="-moz-user-select: none;">stäng</span></a>'+
                '<div class="cb"></div>'+
                '</div>'+
                '<iframe src="' + url +'" frameborder="0" style="position:relative;width:100%;height:100%;"/>';
                
      _this.createOverlay(buf, width, height);
      
      $('.overlay-content', _overlay).css('padding-bottom', '25px'); // todo
   }
     
   _this.closePopup = function() {
      _this.destroyOverlay();
   }
      
   _this.showDialog = function(options) {
      var html, html2;
      //alert('show dialog');
      html2 = '';
         
      if (typeof options != 'object')
         return;
         
      if ((typeof options.buttons != 'undefined') && $.isArray(options.buttons)) {
         for (var i = options.buttons.length - 1; i >= 0; i--) {
            html2 += '<a href="#" index="' + i + 
               '" class="fr ui-state-default button" type="submit">' + options.buttons[i] + '</a> ';
         }
      }

      if ((typeof options.image != 'string') && (typeof options.icon != 'string'))
         options.icon = '/images/ico/important.png';
      
      if ((typeof options.image == 'string') && (typeof options.icon != 'string'))
         options.icon = options.image;
         
      /*if (typeof options.text != 'string')
         options.text = '';*/

      if (typeof options.modal != 'boolean')
         options.modal = true;
      
      var dialog_class = "";
      var dialog_style = "";
      if(options.icon == 'no-icon')
         dialog_class = "no-icon";
      else
         dialog_style='background-image:url(' + options.icon + ')';
      
      //console.log(options.icon);  
      
      html  = '<div>';
      html += '<div class="dialog '+dialog_class+'" style="'+dialog_style+'">';
      html += '<div class="dialog-inner"></div>';
      html += '<div style="margin-top:15px;">' + html2 + '</div>';
      html += '</div>';

      var jq = $(html);
      
      $('.dialog-inner', jq).append(options.text);
         
      var buttons = $('a.button', jq);
         
      buttons.hover(function() {
         $(this).addClass('ui-state-hover');
      }, function() {
         $(this).removeClass('ui-state-hover');
      });

      buttons.click(function() {
         $('#top-flash').css('display', '');

         if ((typeof options.handler) != 'undefined') {
            options.handler.call(jq[0], parseInt($(this).attr('index')));
         }
         
         jq.remove();

         return false;
      });
        
      $('#top-flash').css('display', 'none');

      jq.dialog({
         title: (typeof options.title == 'string') ? options.title : '??',
         resizable: false,
         zIndex: (typeof options.zIndex == 'number') ? options.zIndex : 500000,
         width: (typeof options.width == 'number') ? options.width : 300,
         modal: options.modal,
         close: function (e) {
            $('#top-flash').css('display', '');

            if ((typeof options.handler) != 'undefined') {
               options.handler.call(jq[0]);
            }

            $(this).remove();
         }
      });
         
      return jq[0];
   }
      
   _this.info = function(options) {
       if (typeof options == 'string') {
          _this.request({
             url: '/backend/get_info.php',
             data: { ident: options },
             type: 'GET',
             success: function(data) {
                _this.info({
                   title: data.title,
                   text: data.text,
                   width: data.width
                });
             }
          });
          return;
       }
          
      if (typeof options != 'object')
         return;
         
      if ((typeof options.title != 'string') || (typeof options.text != 'string'))
         return;
      
      if (typeof options.icon != 'string')
         options.icon = '/images/ico/info.png';
         
      _this.showDialog({
         title: options.title,
         text: options.text,
         image: options.icon,
         width: (typeof options.width == 'number') ? options.width : undefined,
         buttons: [ 'OK' ],
         handler: function() {
            $(this).remove();
         }
      });
   }

   _this.alert = function(title, text, width) {
      if (typeof title != 'string')
         return;
         
      if (typeof text != 'string') {
         text  = title;
         title = "Varning";
      }
         
      _this.showDialog({
         title: title,
         text: text,
         modal: true,
         image: '/images/ico/error.png',
         width: (typeof width == 'number') ? width : undefined,
         buttons: [ 'OK' ],
         handler: function() {
            $(this).remove();
         }
      });
   }      
      
   _this.formatPrice = function(price) {
      price = parseFloat(Math.round(price));
       
      var int = Math.floor(price);
      var fra = price - int;
         
      var p1 = (int % 1000);
      var p2 = Math.floor(int / 1000);

      var str = '';
        
      if (p2) {
         str = p2.toString() + '.';
           
         if (p1 < 10)
            str += '00';
         else if (p1 < 100)
            str += '0';
      }
         
      str += p1.toString();
         
      str += ',' + fra.toFixed(2).split(/[.,]/)[1];
         
      return str;
   }
   
   /* move to Lang.xxx          */   
   _this.formatTime = function(date) {
      var str;
         
      str  = (date.getHours() < 10) ? '0' : '';
      str += date.getHours();
      str += ':'
      str += (date.getMinutes() < 10) ? '0' : '';
      str += date.getMinutes();
         
      return str; 
   }
   
   /* move to Lang.xxx          */
   _this.formatDate = function(date) {
      var str;
         
      str  = date.getFullYear();
      str += '-';
      str += (date.getMonth() < 9) ? '0' : '';
      str += date.getMonth() + 1;
      str += '-';
      str += (date.getDate() < 10) ? '0' : '';
      str += date.getDate();
         
      return str;
   }
      
   _this.request = function(options) {
      if ((typeof options != 'object') || (typeof options.url != 'string'))
         return;

      var url = options.url, query;
         
      query = 'SID=' + this.getSID();  
         
      if (url.split('?').length > 1) {
         var urlArray = url.split('?');
         url = urlArray[0] + '?' + query + '&' + urlArray[1]; 
      } else {
         url += '?' + query;
      }
         
      Utils.log('SID: '+ Config.SID +' '+ url);
      
      $.ajax({
         url: url,
         type: (typeof options.type == 'string') ? options.type : 'GET',
         cache: false,
         data: options.data,
         dataType: 'json',
         async: (options.async !== undefined) ? options.async : true,
         success: function(result) {
            if (typeof result.errno != 'number') {
               if (typeof options.error == 'function') {
                  options.error(Number.NaN, 'Ogiltigt svar från servern.');
                  return;
               }
            } else if (result.errno == 0) {
               if ((typeof result.sid == 'string') && result.sid.match(/[A-F0-9]{40}/))
                  Config.SID = result.sid;
               
               if ($.isFunction(options.success))
                  options.success(result.data);
               
               return;
            } else {
               if ((typeof result.sid == 'string') && result.sid.match(/[A-F0-9]{40}/))
                  Config.SID = result.sid;
               
               if ($.isFunction(options.error)) 
                  options.error(result.errno, result.error);
            }
         },
         error: function() {
            if ($.isFunction(options.error)) {
               options.error(Number.NaN, 'Kunde inte ansluta till servern');
            }
         }
      });
   }
   
   _this.frmSubmit = function(frm)
   {
      if(typeof frm != 'object') return;

      _this.request({
         url: frm.action,
         data: $(frm).serialize(),
         type: frm.method,
         success: function() {
            Utils.clearForm(frm);
            Utils.info({
               title   : L('LBL_THANK_YOU'),
               text    : L('LBL_THANK_YOU')
            });
         },
         error: function(errno, error) {
            alert(error);
         }
      });
   }
   
   /* old dump session is now more generic object dump */
   _this.dumpSession = function() {
      _this.request({
         url: '/backend/dump_session.php',
         success: function(data) {
            _this.showDialog({
               title: 'Session',
               text: '<div class="dump"><pre>' + _this.dumpData(data) + '</pre></div>',
               width: 600,
               icon: '/images/ico/bug.png',
               //buttons: [ 'OK' ],
               handler: function() {
                  $(this).remove();
               }
            });
         },
         error: function() {
            alert('uh-oh....');
         }
      });
   }

   _this.dumpData = function(data, padding) {
      var v = '{', i;
      
      if ((typeof padding) == 'undefined') {
         padding = '';
      }
      
      if ($.isArray(data)) {
         for (i = 0; i < data.length; i++) {
            if ((typeof data[i]) == 'object') {
               v += '\n' + padding + '   ' + i + _this.dumpData(data[i], padding + '   ');
            } else {
               v += '\n' + padding + '   ' + i + ' : ' + data[i] + '';
            }
         }
      } else if((typeof data) == 'object') { 
         for (i in data) {
            if ((typeof data[i]) == 'object') {
               v += '\n' + padding + '   ' + i + ' : ' + _this.dumpData(data[i], padding + '   ');
            } else {
               v += '\n' + padding + '   ' + i + ' : ' + data[i] + '';
            }
         }
      }
         
      v += '\n' + padding + '}';
      
      return v;
   }
   
   _this.showSurvey = function() {
      if($('#bsSurvey').css('display') != 'none')
         _survey.dialog('open');
      else
         alert('Du har redan deltagit i undersökningen');
   }
   
   /*
    * Generates a random number between 0 and maxVal.
    */
   _this.randomToN = function(maxVal, floatVal) {
      var randVal = Math.random() * maxVal;
      return (typeof floatVal == 'undefined') ? Math.round(randVal) : randVal.toFixed(floatVal);
   }

   _this.showCategory = function(id) {
      Utils.log('Use of deprecated function Utils.showCategory()');
      Content.showCategory(id);
   }
   
   /* TODO: Make it better.. */
   _this.clearForm = function(form) {
      for (var i = 0; i < form.elements.length; i++) {
         switch(form.elements[i].type.toLowerCase()) {
         case "text":
         case "password":
         case "textarea":
         case "hidden":
            form.elements[i].value = "";
         }
      }
   }
   
   $(function() {
      
      //_this.autoLink('a');
      
      _survey = $('<div style="position:relative;top:15px;"></div>').append($('#bsSurvey'));
      $('body').append(_survey);
      
      _survey.dialog({
         title: 'Enkät',
         resizable: false,
         zIndex: 500000,
         autoOpen: false,
         width: 650,
         open: function(e) {
            if(typeof _overlay == 'undefined') {
               this.overlay = _overlay = $('<div class="overlay"><div class="overlay-darken"></div>');
               $('#canvas').append(this.overlay);
            }
         },
         close: function (e) {
            $('#bsSurvey').css('display', 'none');
            if (typeof this.overlay != 'undefined') {
               this.overlay.remove();
               _overlay = undefined;
            }
         }
      });
   });
});

/* wrappers for popupOpen     */
var popupOpen  = Utils.popup;
var popupClose = Utils.popupClose;

var Li$ = Utils;


