var msep = {};

msep.core = {

      browser: navigator.userAgent.toLowerCase(),

      baseUrl: "",

      baseUrlRaw: ""

};

msep.core.element = {

      browserWindowSize: function()
      {
            var browserWinWidth = 0, browserWinHeight = 0;

            if(typeof( window.innerWidth ) == 'number')
            {
                  //Non-IE
                  browserWinWidth = window.innerWidth;
                  browserWinHeight = window.innerHeight;
            }
            else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight))
            {
                  browserWinWidth = document.documentElement.clientWidth;
                  browserWinHeight = document.documentElement.clientHeight;
            }
            else if(document.body && (document.body.clientWidth || document.body.clientHeight))
            {
                  browserWinWidth = document.body.clientWidth;
                  browserWinHeight = document.body.clientHeight;
            }

            return [browserWinWidth, browserWinHeight];
      },

      scrollingOffset: function()
      {
            var x, y;

            if (self.pageYOffset)
            {
                  x = self.pageXOffset;
                  y = self.pageYOffset;
            }
            else if (document.documentElement && document.documentElement.scrollTop)
            {
                  x = document.documentElement.scrollLeft;
                  y = document.documentElement.scrollTop;
            }
            else if (document.body)
            {
                  x = document.body.scrollLeft;
                  y = document.body.scrollTop;
            }

            return [x, y];
      },

      findPos: function(obj)
      {
            var curleft = curtop = 0;
            if (obj.offsetParent) {
              curleft = obj.offsetLeft
              curtop = obj.offsetTop
              while (obj = obj.offsetParent) {
                curleft += obj.offsetLeft
                curtop += obj.offsetTop
              }
            }
            return [curleft,curtop];
      }


};

msep.core.tag = {

      elements: [],

      register: function(input, container, hidden, form)
      {
            var self = this;

            var id = this.elements.length;

            this.elements[id] = [input, container, []];

            input.onkeydown = function(e)
            {
                  var char;
                  var evt = (e) ? e : window.event;       //IE reports window.event not arg
                  
                  if (evt.type == "keydown")
                  {
                        char = evt.keycode;
                  }
                  else
                  {
                        char = (evt.charCode) ? evt.charCode : evt.keyCode;
                  }
                  
                  if (char == 13 && this.value.length > 0)
                  {
                        self.addTag(id);

                        return false;
                  }
            };
            
            input.onkeypress = function(e)
            { 
                  var char;
                  var evt = (e) ? e : window.event;       //IE reports window.event not arg
                  
                  if (evt.type == "keydown")
                  {
                        char = evt.keycode;
                  }
                  else
                  {
                        char = (evt.charCode) ? evt.charCode : evt.keyCode;
                  }
                  
                  if (char == 13 && this.value.length > 0)
                  {
                        self.addTag(id);

                        return false;
                  }
            };

            if (typeof(form) != "undefined")
            {
                  form.onsubmit = function()
                  {
                        if (self.elements[id][2].length > 0) hidden.value = JSON.encode(self.elements[id][2]);
                  };
            }

            return id;
      },

      addTag: function(id, value)
      {
            var value = ((!this.elements[id][0].value && value) ? value : this.elements[id][0].value);

            if (!this.tagExists(id, value))
            {
                  var tag_element = document.createElement('span');
                  tag_element.setAttribute('class', 'tag');
                  tag_element.setAttribute('className', 'tag'); //IE
                  setStyle(tag_element, 'margin-bottom: 15px;');
                  tag_element.innerHTML = value+"<a onclick='msep.core.tag.removeTag("+id+", \""+value+"\", this);' href='javascript:void(0);'>x</a>";

                  this.elements[id][2].push(value);
                  this.elements[id][1].appendChild(tag_element);
                  this.elements[id][0].value = "";
            }
      },

      removeTag: function(id, value, tag)
      {
            for (var i in this.elements[id][2])
            {
                  if (this.elements[id][2][i] == value)
                  {
                        this.elements[id][2].splice(i, 1);
                        tag.parentNode.destroy();

                        break;
                  }
            }
      },
      
      removeTags: function(id)
      {
            for (var i in this.elements[id][2]) this.elements[id][2].splice(i, 1);

            this.elements[id][1].empty();
      },

      tagExists: function(id, value)
      {
            for (var i in this.elements[id][2])
            {
                  if (this.elements[id][2][i] == value)
                  {
                        return true;

                        break;
                  }
            }

            return false;
      }

};




msep.core.category = {

      categories: [],

      init: function(options)
      {
            this.setOptions(options);
            this.getCategories();
      },

      setOptions: function(options)
      {
            for (var key in options)
            {
                  if (options.hasOwnProperty(key))
                  {
                        this[key] = options[key];
                  }
            }
      },

      getCategories: function(callback)
      {
            var self = this;

            new Request.JSON(
            {
                  url: msep.core.baseUrlRaw+"msep-core/json/categories/api/"+self.api+"/",

                  onSuccess: function(jsonObj)
                  {
                        if (!jsonObj.error)
                        {
                              self.categories = jsonObj.categories;

                              var cat_select = document.createElement('select');

                              setStyle(cat_select, 'margin-right: 5px');

                              cat_select.onchange = function()
                              {
                                    var id = this.options[this.selectedIndex].value;
                                    self.draw(id);
                              };

                              var option = document.createElement('option');
                              option.value = 0;
                              option.text = " ";
                              cat_select.options.add(option);

                              for (var key in self.categories)
                              {
                                    if (self.categories.hasOwnProperty(key))
                                    {
                                          option = document.createElement('option');
                                          option.value = self.categories[key].info.category_id;
                                          option.text = self.categories[key].info.category_name;
                                          cat_select.options.add(option);
                                    }
                              }

                              self.container.appendChild(cat_select);
                        }
                  }
            }).send();
      },

      draw: function(value)
      {
            this.clearUpperLevel(value.split("_"));

            var self = this;

            var has_options = false;

            var current_object = self.getObject(value.split("_"));

            var cat_select = document.createElement('select');

            setStyle(cat_select, 'margin-right: 5px');

            cat_select.onchange = function()
            {
                  var id = this.options[this.selectedIndex].value;
                  self.draw(id);
            };

            var option = document.createElement('option');
            option.value = value+"_"+0;
            option.text = " ";
            cat_select.options.add(option);

            if (typeof(current_object) != "undefined")
            {
                  for (var key in current_object.childs)
                  {
                        if (current_object.childs.hasOwnProperty(key))
                        {
                              has_options = true;

                              option = document.createElement('option');
                              option.value = value+"_"+current_object.childs[key].info.category_id;
                              option.text = current_object.childs[key].info.category_name;
                              cat_select.options.add(option);
                        }
                  }

                  if (has_options) self.container.appendChild(cat_select);
            }
      },

      getObject: function(parts)
      {
            var index = parts.shift();
            var obj = this.categories[index];

            for (var key in parts)
            {
                  if (parts.hasOwnProperty(key))
                  {
                        obj = obj.childs[parts[key]];
                  }
            }

            return obj;
      },

      clearUpperLevel: function(parts)
      {
            var reg_exp = "";

            var i = 0;

            while (i < parts.length)
            {
                  reg_exp += "[0-9]+_";

                  i++;
            }

            getByAttribute(document.body, 'option', 'value', RegExp(reg_exp)).each(function(item)
            {
                  var remove_parent = false;
                  var parent_node = item.parentNode;

                  if (item.parentNode.childNodes.length == 1) remove_parent = true;

                  item.parentNode.removeChild(item);

                  if (remove_parent) parent_node.parentNode.removeChild(parent_node);
            });
      }

};

msep.core.tip = {

      register: function(a, opt, html, options)
      {
            var defaults =
            {
                   content:
                   {
                        text: html
                   },
                   position:
                   {
                        viewport: jQuery(window)
                   },
                   show:
                   {
                        delay: opt['show-delay'],
                        solo: true,
                        effect: function() { jQuery(this).fadeIn(200); }
                   },
                   hide:
                   {
                        delay: opt['hide-delay'],
                        fixed: true,
                        effect: function() { jQuery(this).fadeOut(200); }
                   },
                   events:
                   {
                        render: function(event, api)
                        {
                              if (typeof opt['follow'] != 'undefined' && opt['follow'] == 1)
                              {
                                    var menuYloc = parseInt(api.elements.tooltip.css("top").substring(0,api.elements.tooltip.css("top").indexOf("px")));
                              
                                    jQuery(window).scroll(function ()
                                    { 
                                          offset = menuYloc+jQuery(document).scrollTop()+"px";
                                          api.elements.tooltip.animate({top:offset},{duration:1000,queue:false});
                                    });
                              }
                              
                              api.elements.tip.css('display', 'none');

                              api.elements.content.css(
                              {
                                    border: opt['border']+"px solid #"+opt['border-color'],
                                    backgroundColor: "#"+opt['background-color'],
                                    padding: opt['padding-top']+"px "+opt['padding-right']+"px "+opt['padding-bottom']+"px "+opt['padding-left']+"px",
                                    color: "#"+opt['color'],
                                    fontSize: opt['font-size']+"px"
                              });
  
                              var elm = getById(api.elements.content.attr('id'));
                              
                              jQuery(elm.getElementsByTagName('img')).each(function()
                              {
                                    jQuery(this).css(
                                    {
                                          maxWidth: opt['thumb-max-width']+"px",
                                          maxHeight: opt['thumb-max-height']+"px",
                                          width: "expression(this.width > "+opt['thumb-max-width']+" ? "+opt['thumb-max-width']+" : true)",
                                          height: "expression(this.height > "+opt['thumb-max-height']+" ? "+opt['thumb-max-height']+" : true)"
                                    });
                              });
                              
                              setStyle(elm, "border-radius: "+opt['tl']+"px "+opt['tr']+"px "+opt['br']+"px "+opt['bl']+"px; -moz-border-radius: "+opt['tl']+"px "+opt['tr']+"px "+opt['br']+"px "+opt['bl']+"px; -khtml-border-radius: "+opt['tl']+"px "+opt['tr']+"px "+opt['br']+"px "+opt['bl']+"px; -webkit-border-radius: "+opt['tl']+"px "+opt['tr']+"px "+opt['br']+"px "+opt['bl']+"px;");
                
                              elm.style.MozBorderRadius = opt['tl']+"px "+opt['tr']+"px "+opt['br']+"px "+opt['bl']+"px";
                              elm.style.khtmlBorderRadius = opt['tl']+"px "+opt['tr']+"px "+opt['br']+"px "+opt['bl']+"px";
                              elm.style.webkitBorderRadius = opt['tl']+"px "+opt['tr']+"px "+opt['br']+"px "+opt['bl']+"px";
                              elm.style.borderRadius = opt['tl']+"px "+opt['tr']+"px "+opt['br']+"px "+opt['bl']+"px";
                              
                              elm.className += ' curvyAccept curvyRedraw';

                              curvyCorners.init();

                              if (typeof opt['shadows'] != 'undefined' && opt['shadows'] != "")
                              {
                                    if (msep.core.browser.match(/msie/))
                                    {

                                    }
                                    else if (!msep.core.browser.match(/(msie|opera)/))
                                    {
                                          setStyle(getById(api.elements.content.attr('id')), "box-shadow: "+opt['shadows']+"; -moz-box-shadow: "+opt['shadows']+"; -webkit-box-shadow: "+opt['shadows']+"; -khtml-box-shadow: "+opt['shadows']+";");
                                    }
                              }
                        }
                  }
            };

            jQuery(a).qtip(Object.deepExtend(defaults, options));
      }

};

msep.core.color = {

      Rgb2Hex: function(red, green, blue)
      {
            var hexArray = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F");
            var red1 = Math.floor(red / 16);
            var red2 = red - red1 * 16;
            var green1 = Math.floor(green / 16);
            var green2 = green - green1 * 16;
            var blue1 = Math.floor(blue / 16);
            var blue2 = blue - blue1 * 16;

            var decToHex="";
            decToHex += hexArray[red1]+hexArray[red2]+hexArray[green1]+hexArray[green2]+hexArray[blue1]+hexArray[blue2];

            return decToHex;
      },

      pad: function(num, totalChars)
      {
          var pad = '0';
          num = num + '';
          while (num.length < totalChars) {
              num = pad + num;
          }
          return num;
      },

      changeColor: function(color, ratio, darker)
      {
          // Trim trailing/leading whitespace
          color = color.replace(/^\s*|\s*$/, '');

          // Expand three-digit hex
          color = color.replace(
              /^#?([a-f0-9])([a-f0-9])([a-f0-9])$/i,
              '#$1$1$2$2$3$3'
          );

          // Calculate ratio
          var difference = Math.round(ratio * 256) * (darker ? -1 : 1),
              // Determine if input is RGB(A)
              rgb = color.match(new RegExp('^rgba?\\(\\s*' +
                  '(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])' +
                  '\\s*,\\s*' +
                  '(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])' +
                  '\\s*,\\s*' +
                  '(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])' +
                  '(?:\\s*,\\s*' +
                  '(0|1|0?\\.\\d+))?' +
                  '\\s*\\)$'
              , 'i')),
              alpha = !!rgb && rgb[4] != null ? rgb[4] : null,

              // Convert hex to decimal
              decimal = !!rgb? [rgb[1], rgb[2], rgb[3]] : color.replace(
                  /^#?([a-f0-9][a-f0-9])([a-f0-9][a-f0-9])([a-f0-9][a-f0-9])/i,
                  function() {
                      return parseInt(arguments[1], 16) + ',' +
                          parseInt(arguments[2], 16) + ',' +
                          parseInt(arguments[3], 16);
                  }
              ).split(/,/),
              returnValue;

          var self = this;

          // Return RGB(A)
          return !!rgb ?
              'rgb' + (alpha !== null ? 'a' : '') + '(' +
                  Math[darker ? 'max' : 'min'](
                      parseInt(decimal[0], 10) + difference, darker ? 0 : 255
                  ) + ', ' +
                  Math[darker ? 'max' : 'min'](
                      parseInt(decimal[1], 10) + difference, darker ? 0 : 255
                  ) + ', ' +
                  Math[darker ? 'max' : 'min'](
                      parseInt(decimal[2], 10) + difference, darker ? 0 : 255
                  ) +
                  (alpha !== null ? ', ' + alpha : '') +
                  ')' :
              // Return hex
              [
                  '#',
                  self.pad(Math[darker ? 'max' : 'min'](
                      parseInt(decimal[0], 10) + difference, darker ? 0 : 255
                  ).toString(16), 2),
                  self.pad(Math[darker ? 'max' : 'min'](
                      parseInt(decimal[1], 10) + difference, darker ? 0 : 255
                  ).toString(16), 2),
                  self.pad(Math[darker ? 'max' : 'min'](
                      parseInt(decimal[2], 10) + difference, darker ? 0 : 255
                  ).toString(16), 2)
              ].join('');
      },

      lighterColor: function(color, ratio)
      {
            return this.changeColor(color, ratio, false).replace(/#/, "");
      },

      darkerColor: function(color, ratio)
      {
            return this.changeColor(color, ratio, true).replace(/#/, "");
      },

      hsvToRgb: function(h,s,v)
      {
            var s = s / 100, v = v / 100;

            var hi = Math.floor((h/60) % 6);
            var f = (h / 60) - hi;
            var p = v * (1 - s);
            var q = v * (1 - f * s);
            var t = v * (1 - (1 - f) * s);

            var rgb = [];

            switch (hi)
            {
                  case 0: rgb = [v,t,p];break;
                  case 1: rgb = [q,v,p];break;
                  case 2: rgb = [p,v,t];break;
                  case 3: rgb = [p,q,v];break;
                  case 4: rgb = [t,p,v];break;
                  case 5: rgb = [v,p,q];break;
            }

            var r = Math.min(255, Math.round(rgb[0]*256)),
                g = Math.min(255, Math.round(rgb[1]*256)),
                b = Math.min(255, Math.round(rgb[2]*256));

            return [r,g,b];
      },

      rgbToHsv: function(r, g, b)
      {
            var r = (r / 255), g = (g / 255), b = (b / 255);

            var min = Math.min(Math.min(r, g), b), max = Math.max(Math.max(r, g), b), delta = max - min;

            var value = max, saturation, hue;

            if (max == min)
            {
                  hue = 0;
            }
            else if (max == r)
            {
                  hue = (60 * ((g-b) / (max-min))) % 360;
            }
            else if (max == g)
            {
                  hue = 60 * ((b-r) / (max-min)) + 120;
            }
            else if (max == b)
            {
                  hue = 60 * ((r-g) / (max-min)) + 240;
            }

            if (hue < 0) hue += 360;

            // Saturation
            if (max == 0)
            {
                  saturation = 0;
            }
            else
            {
                  saturation = 1 - (min/max);
            }

            return [Math.round(hue), Math.round(saturation * 100), Math.round(value * 100)];
      }

};

Array.prototype.in_array = function(p_val)
{
      for(var i = 0, l = this.length; i < l; i++)
      {
            if (this[i] == p_val)
            {
                  return true;
            }
      }

      return false;
};

Object.deepExtend = function(destination, source) {
  for (var property in source) {
    if (source[property] && source[property].constructor &&
     source[property].constructor === Object) {
      destination[property] = destination[property] || {};
      arguments.callee(destination[property], source[property]);
    } else {
      destination[property] = source[property];
    }
  }
  return destination;
};

getByClassName = function(element, classname)
{
      var a = [];
      var re = new RegExp('\\b' + classname + '\\b');
      var els = element.getElementsByTagName("*");

      for(var i=0,j=els.length; i<j; i++)
            if(re.test(els[i].className))a.push(els[i]);

      return a;
};

setStyle = function(element, css)
{
      if (window.attachEvent && navigator.userAgent.toLowerCase().indexOf("opera") == -1)
      {
            var cssText = element.style.getAttribute('cssText');

            if (cssText == "" || cssText == null || cssText == "undefined")
            {
                  element.style.setAttribute('cssText', css);
            }
            else
            {
                  var semicolon = "";

                  if (cssText.substr(cssText.length-1, 1) != ';') semicolon = ";";

                  element.style.setAttribute('cssText', cssText+semicolon+css);
            }
      }
      else
      {
            if (element.getAttribute('style') == "" || element.getAttribute('style') == null || element.getAttribute('style') == "undefined")
            {
                  element.setAttribute('style', css);
            }
            else
            {
                  element.setAttribute('style', element.getAttribute('style')+css);
            }
      }
};

getByAttribute = function(element, strTagName, strAttributeName, strAttributeValue)
{
      var arrElements = (strTagName == "*" && element.all)? element.all : element.getElementsByTagName(strTagName);
      var arrReturnElements = new Array();
      var oAttributeValue = (typeof strAttributeValue != "undefined")? new RegExp("(^|\\s)" + strAttributeValue + "(\\s|$)") : null;
      var oCurrent;
      var oAttribute;

      for(var i=0; i<arrElements.length; i++)
      {
            oCurrent = arrElements[i];
            oAttribute = oCurrent.getAttribute && oCurrent.getAttribute(strAttributeName);

            if(typeof oAttribute == "string" && oAttribute.length > 0)
            {
                  if(typeof strAttributeValue == "undefined" || (oAttributeValue && oAttribute.match(strAttributeValue)))
                  {
                        arrReturnElements.push(oCurrent);
                  }
            }
      }

      return arrReturnElements;
};

getCssRule = function(element, strCssRule)
{
      var strValue = "";

      if (document.defaultView && document.defaultView.getComputedStyle)
      {
            strValue = document.defaultView.getComputedStyle(element, "").getPropertyValue(strCssRule);
      }
      else if(element.currentStyle)
      {
            strCssRule = strCssRule.replace(/\-(\w)/g, function(strMatch, p1)
            {
                  return p1.toUpperCase();
            });

            strValue = element.currentStyle[strCssRule];
      }

      return strValue;
};

getById = function(id)
{
      return document.getElementById(id);
};;
