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.debug != 'boolean') || (Config.debug == 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.autoLink = function(el) {
      $(el).click(function() {
         var href = $(this).attr('href');

         if(typeof this.onclick == 'function')
            return true;

         if ($(this).attr('target') != '')
            return true;
         
         if (href == '')
            return true;
         
         if (/^(?:javascript|mms|mailto):/.test(href))
            return true;
         
         var matches;

         var re = /^(?:https?:\/\/[^\/]+)?(\/.*)$/;
         
         if($(this).attr('ignore') == '1') {
            return true;
         }
         
         if((matches = /^\s*([0-9]+)\s*,\s*([0-9]+)\s*(?:,\s*(.*))?\s*$/.exec($(this).attr('popup'))) != null) {
            var width = parseInt(matches[1]), height = parseInt(matches[2]), title;
               
            if ((matches.length >= 4) && (typeof matches[3] == 'string') && (matches[3] != ''))
               title = matches[3];
            else
               title = href;

            Utils.popup(href, title, width, height);
            return false;
         }
         
         if((matches = re.exec($(this).attr('href'))) === null) {
            if($(this).attr('nopopup') == '1')
               return true;
            
            Utils.popup(href, href, 600, 500);
            return false;
         }
         
         href = matches[1];

         if ((matches = /^\/upplevelser\/([0-9]+)\/?$/.exec(href)) !== null) {
            Content.showProduct(matches[1]);
            return false;
         }

         if ((matches = /^\/kategori\/([^\/]+)\/?$/.exec(href)) !== null) {
            Utils.request({
               url: '/backend/get_category_by_ident.php',
               data: { ident: matches[1] },
               type: 'GET',
               success: function(category) {
                  Content.showCategory(category.katid, undefined);
               }
            });
            return false;
         }

         Content.load(href);
         return false;
      });
   }
   
   _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() {
            _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();
      
      /*window.onscroll = undefined;*/
      
      _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';
      }*/
      
      $('#center').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.popup = function(url, title, width, height) {
      if (typeof title != 'string')
         title = 'Web';
         
      if (typeof width != 'number')
         width = 800;
         
      if (typeof height != 'number')
         height = 500;

      _this.createOverlay('<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%;"/>', width, height);
         
      $('.overlay-content', _overlay).css('padding-bottom', '25px'); // todo
   }
     
   _this.closePopup = function() {
      _this.destroyOverlay();
   }
      
   _this.showDialog = function(options) {
      var html, html2;
         
      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/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;
      
      html  = '<div>';
      html += '<div class="dialog" style="background-image:url(' + options.icon + ')">';
      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');
      });

      var overlay;
      
      if (options.modal && (typeof _overlay == 'undefined')) {
         _overlay = overlay = $('<div class="overlay"><div class="overlay-darken"></div>');
         $('#center').append(overlay);
      }
      
      buttons.click(function() {
         if (typeof overlay != 'undefined') {
            _overlay.remove();
            _overlay = undefined;
         }
      
         jq.remove();

         if ((typeof options.handler) != 'undefined') {
            options.handler.call(jq[0], parseInt($(this).attr('index')));
         }

         return false;
      });
         
         
      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,
         close: function (e) {
            if (typeof overlay != 'undefined') {
               overlay.remove();
               _overlay = undefined;
            }
         
            $(this).remove();
            if ((typeof options.handler) != 'undefined') {
               options.handler.call(jq[0]);
            }
         }
      });
         
      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
                });
             }
          });
          return;
       }
          
      if (typeof options != 'object')
         return;
         
      if ((typeof options.title != 'string') || (typeof options.text != 'string'))
         return;
         
      _this.showDialog({
         title: options.title,
         text: options.text,
         image: '/images/info.png',
         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/error.png',
         width: (typeof width == 'number') ? width : undefined,
         buttons: [ 'OK' ],
         handler: function() {
            $(this).remove();
         }
      });
   }      
      
   _this.formatPrice = function(price) {
      str = price.toFixed(2).replace(/[.]/, ',');
      
      str = str.replace(/-/, '- ');
      
      reg = /(-?[0-9]+)([0-9]{3})/;
      
      while(reg.test(str))
         str = str.replace(reg, '$1,$2');
      
      return str;
      
      
      
      
      /*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;
   }
      
   _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; 
   }

   _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(Config.SID);
      
      $.ajax({
         url: url,
         type: (typeof options.type == 'string') ? options.type : 'GET',
         cache: false,
         data: options.data,
         dataType: 'json',
         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.');
            }
         }
      });
   }
      
   /* 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/bug.png',
               //buttons: [ 'OK' ],
               handler: function() {
                  $(this).remove();
               }
            });
         },
         error: function(errno, error) {
            alert('uh-oh...('+ errno +')\n'+ error);
         }
      });
   }
   
   _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.activateBox = function(options) {
      this.request({
         url: '/backend/confirm_box.php',
         data: options.data,
         success: function(box) {
            _box = box;

            if ((box.ptype == 0) || ((box.ptype == 3) && (box.prod_id != 0)))
               loadContent('pages/boxinfo.php', null);
         },
         error: function(errno, error) {
            if ($('#_info').children().length > 0) {
               $('#_info').children().fadeOut(1000, function() {
                  $(this).remove();
               });
            }
               
            var html;
               
            html  = '<div class="ui-state-error ui-corner-all" style="margin-bottom: 5px;">';
            html += '<div style="margin:10px 5px 10px 5px">';
            html += '<span class="ui-icon ui-icon-alert" style="float: left; margin-right: 0.3em;"></span>';
            html += '<strong>Fel:</strong> ' + error + '</div></div>';
               
            $('#_info').append(html);
         }
      });
   }

   _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>');
               $('#center').append(this.overlay);
            }
         },
         close: function (e) {
            $('#bsSurvey').css('display', 'none');
            if (typeof this.overlay != 'undefined') {
               this.overlay.remove();
               _overlay = undefined;
            }
         }
      });
   });
});

