/*
*	box3document 						- Manipulações gerais do documento
*	box3document.baseURL 				- Url base
*	box3document.fixMasks 				- Ativa o plugin de mascaras
*	box3document.fixPlaceholder 		- Ativa o plugin de placeholder
*	box3document.fixMasksPlace 			- Ativa os dois plugins informados acima
*	box3document.redirect 				- Redireciona o documento (usado bastante com o flash)
*	box3document.resizeEvent 			- Verificador do evento de resize
*	box3document.resizeWindow			- Adiciona evento de resize, que chama o box3document.resize a cada 100 milesegundos
*	box3document.resize(func)			- Método que recebe uma função com o que deve ser feito, quanto a janela sofrer resize
*	box3document.fixFlashs				- Adiciona o flash nas divs com classe 'flash', mais detalhes e exemplo no método
*/
var box3document ={
		gatewayURL: '',
      baseURL: location.protocol+'//'+location.host+'/',
      baseFront: location.protocol+'//' + location.host + location.pathname,
      fixMasks: function(){
            $('[data-mask]').bind('focus', function(e){
                  $(this).unmask().mask($(this).attr('data-mask'),{
                        placeholder: "_"
                  });
            }).bind('focusout', function(){
                  $('[placeholder]').placehold();
            });
      },
      fixPlaceholder: function(){
            $('[placeholder]').placehold();
      },
      fixMasksPlace: function(){
            box3document.fixMasks();
            box3document.fixPlaceholder();
      },
      redirect: function(where){
            window.location = box3document.baseURL + where;
      },
      resizeEvent: true,
      resizeWindow: function(){
            var resizeTimer = null;
            $(window).bind('resize', function(){
                  if (resizeTimer) clearTimeout(resizeTimer);
                  resizeTimer = setTimeout(box3document.resize, 100);
                  box3document.resizeEvent = false;
            });
      },
      resize: function(callback){
            if(box3document.resizeEvent){
                  box3document.resizeWindow();
                  box3document.resizeCallback = callback;
            }
            box3document.resizeCallback();
      },
      fixFlashs: function(){
            /*
		<div class="flash">
			<?php
				$flash['id'] 			= 'universodakota';
				$flash['swf']			= 'universodakota.swf';
				$flash['vars'] 			= '';  //Passa baseURL por default
				list($width, $height) 	= getimagesize(($flash['swf']));
				$flash['width']	 	= $width;
				$flash['height']		= $height;
				echo json_encode($flash);
			?>
		</div>
		*/
            $('div.flash').each(function(){

                  var config = $.parseJSON($(this).html());

                  config.id = config.id == '' ? $(this).parent().attr('id') + '-swf' : config.id;

                  $(this)
                  .removeClass('flash')
                  .attr('id', config.id)
                  .css({
                        'width':config.width+'px',
                        'height':config.height+'px'
                  })
                  .flash({
                        swf: config.swf,
                        id: config.id + "-swf",
                        width: '100%',
                        height: '100%',
                        wmode: "transparent",
                        flashvars: config.vars,
                        allowScriptAccess: "sameDomain",
                        allowFullScreen: true,
                        hasVersion: 10,
                        hasVersionFail: function(){
                        //box3document.redirect('noflash');
                        }
                  })
            })
      }
}

var box3flash = {
      fix: function ()
      {

      },

      get: function (id)
      {
            if(window.document[id])
                  return window.document[id];

            if(navigator.appName.indexOf("Microsoft Internet")==-1)
            {
                  if(document.embeds && document.embeds[id])
                        return document.embeds[id];
            }
            else
                  return document.getElementById(id);
      }
}
/*
*	box3image                               - Manipulações das imagens em geral
*	box3image.preload(caminho, callback)	- Pré-carrega uma imagem
*/
var box3image = {

      preload: function (caminho, callback)
      {
            var img = new Image();

            $(img)
            .load( function () {
                  $(this).hide();

                  if(typeof(callback) == 'function') callback(caminho);

                  $(this).remove();
            })
            .error( function () {
//                  console.log('image not found: ' + caminho);
            })
            .attr('src', caminho);
      }
}
/*
*	box3string 							- Manipulações de strings em geral
*	box3string.ucFirst(string)			- Transforma em maiusculo o primeiro caractere de uma string
*	box3string.removeAcento(string)		- Remove todos os acentos de uma string
*/
var box3string ={
      ucFirst: function(string){
            return string.substring(0, 1).toUpperCase() + string.substring(1).toLowerCase();
      },
      removeAcento: function(string){
            string = string.replace(new RegExp('[ÁÀÂÃ]','gi'), 'A');
            string = string.replace(new RegExp('[ÉÈÊ]','gi'), 'E');
            string = string.replace(new RegExp('[ÍÌÎ]','gi'), 'I');
            string = string.replace(new RegExp('[ÓÒÔÕ]','gi'), 'O');
            string = string.replace(new RegExp('[ÚÙÛ]','gi'), 'U');
            string = string.replace(new RegExp('[Ç]','gi'), 'C');
            string = string.toLowerCase();
            return string;
      }
}
/*
*	box3form 									- Manipulações dos forms
*	box3form.reset($.form)						- Reseta o formulário
*	box3form.validate($.scope, 'errorselector')	- Valida um formulário/elemento que contenha elementos com classe 'required'
*/
var box3form ={
      reset: function(form){
            form.find('select').val('');
            form.find('select[name=cidade]').html('<option value="">Cidade*</option>');
            form.find('input, textarea').val('');
            form.find('.error').removeClass('error');
            form.find('.errormessage').text('');
      },
      validate: function(scope, errorElement, fieldErrorClass){

            var valid;
            var scopeElm = $(scope);
            var errorClass = fieldErrorClass == undefined ? 'field-error' : fieldErrorClass;
            var error = $(errorElement);
            scopeElm.find('.'+errorClass).removeClass(errorClass);
            error.text('');
			
            var seletor = '[class^="required"]:visible, [class~="required"]:visible, [class^="required"][type="hidden"], [class~="required"][type="hidden"]';
            scopeElm.find(seletor).each(function () {
                  var self = $(this);
                  var value = self.val();
                  var className = self.attr('class');
                  var placeholderValue = self.attr('placeholder');
                  valid = true;
                  rulesParsing = className;
                  rulesRegExp = /\[(.*)\]/;
                  getRules = rulesRegExp.exec(rulesParsing);
				  
				  //console.log(self);
				  
                  if(getRules != null)
                  {
                        str = getRules[1];
                        pattern = /\W+/;
                        result = str.split(pattern);
                        switch(result[0])
                        {
                              case "email":
                                    // expressão para validar o email
                                    var pattern = new RegExp(/^[a-zA-Z0-9_\.\-]+\@([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/);
                                    if(!pattern.test(value))
                                          valid = false;
                                    break;
                              case "confirm":
                                    var valueToCompare = $('#' + result[1]).val();
                                    //console.log("Valor: '"+value+ "' Compare com: '" + valueToCompare + "' campo "+result[1]);
                                    if(value != valueToCompare)
                                          valid = false;
                                    break;
                              case "date":
                                    // expressão para verificar se o campo contém somente números
                                    var pattern = new RegExp(/^[0-9\ ]+$/);
                                    var value = self.val();
                                    if(!pattern.test(value))
                                          valid = false;
                                    else
                                    {
                                          var currentDate = new Date();
                                          var currentYear = currentDate.getFullYear();
                                          switch(result[1])
                                          {
                                                case "day":
                                                      if(parseInt(value, 10) < 1 || parseInt(value, 10) > 31)
                                                            valid = false;
                                                      break;
                                                case "month":
                                                      if(parseInt(value, 10) < 1 || parseInt(value, 10) > 12)
                                                            valid = false;
                                                      break;
                                                case "year":
                                                      if(parseInt(value, 10) < 1900 || parseInt(value, 10) > currentYear)
                                                            valid = false;
                                                      break;
                                          }
                                    }
                                    break;
                              case "fullDate":
                                    var value = self.val();
                                    var dates = value.split('/');
                                    var currentDate = new Date();
                                    var currentYear = currentDate.getFullYear();

                                    if(value == "")
                                          valid = false;
                                    if(parseInt(dates[0], 10) < 1 || parseInt(dates[0], 10) > 31)
                                          valid = false;
                                    else if(parseInt(dates[1], 10) < 1 || parseInt(dates[1], 10) > 12)
                                          valid = false;
                                    else if(parseInt(dates[2], 10) < 1900 || parseInt(dates[2], 10) > currentYear)
                                          valid = false;

                                    break;
                              case "vimeo":
                                    var pattern = /http:\/\/(www\.)?vimeo.com\/(\d+)($|\/)/;
                                    valid = pattern.test(value);
                                    break;
                        }
                  }
                  else
                  {
                        if(value == "" || value == placeholderValue)
                              valid = false;
                  }

                  // se o campo atual não passou em uma das validações
                  if(valid === false)
                  {
                        self.addClass(errorClass);
                        self.focus();

                        error.text(self.attr('data-errormessage'));
                        return false;
                  }
                  else
                  {
                        self.removeClass(errorClass);
                        return true;
                  }
            });
            return valid;
      }
}

var BrowserDetection = {
      browser: '',
      version: '',
      classNames: {
            ie: 'ie',
            chrome: 'chrome',
            safari: 'safari',
            firefox: 'firefox',
            mozilla: 'mozilla',
            opera: 'opera'
      },
      init: function(selector)
      {
            selector = selector || 'html';

            var $element = $(selector);
            var userAgent = navigator.userAgent.toLowerCase();
            $.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());
            if($.browser.msie)
            {
                  BrowserDetection.browser = BrowserDetection.classNames.ie;
                  BrowserDetection.version = $.browser.version.substring(0,1);
            }
            if($.browser.chrome)
            {
                  BrowserDetection.browser = BrowserDetection.classNames.chrome;
                  userAgent = userAgent.substring(userAgent.indexOf('chrome/')+7);
                  userAgent = userAgent.substring(0,userAgent.indexOf('.'));
                  BrowserDetection.version = userAgent;
                  $.browser.safari = false;
            }
            if($.browser.safari)
            {
                  BrowserDetection.browser = BrowserDetection.classNames.safari;
                  userAgent = userAgent.substring(userAgent.indexOf('version/') +8);
                  userAgent = userAgent.substring(0,1);
                  BrowserDetection.version = userAgent;
            }
            if($.browser.mozilla)
            {
                  if(navigator.userAgent.toLowerCase().indexOf('firefox') != -1)
                  {
                        BrowserDetection.browser = BrowserDetection.classNames.firefox;
                        userAgent = userAgent.substring(userAgent.indexOf('firefox/') +8);
                        userAgent = userAgent.substring(0,1);
                        BrowserDetection.version = userAgent;
                  }
                  else
                  {
                        BrowserDetection.browser = BrowserDetection.classNames.mozilla;
                        BrowserDetection.version = '';
                  }
            }
            if($.browser.opera)
            {
                  BrowserDetection.browser = BrowserDetection.classNames.opera;
                  BrowserDetection.version = '';
            }
            $element.addClass(BrowserDetection.browser);
            $element.addClass(BrowserDetection.browser + BrowserDetection.version);

            window.browser = BrowserDetection.browser;
            window.browserVersion = BrowserDetection.version;
      }
}

/*
*	Extenção do jQuery para resolver problemas com fadeIn e fadeOut no IE
*	fadeInIE(duration, callback)				- Se for IE, show, caso contrário dá um fadeIn
*	fadeOutIE(duration, callback)				- Se for IE, hide, caso contrário dá um fadeOut
*/
$.fn.extend({
      fadeInIE: function(duration, callback)
      {
            var elm = $(this);
            if($.browser.msie){
                  elm.show();
                  if(typeof(callback) == 'function'){
                        setTimeout(callback, 100);
                  }
            } else {
                  elm.fadeIn(duration, callback);
            }
            return elm;
      },
      fadeOutIE: function(duration, callback)
      {
            var elm = $(this);
            if($.browser.msie){
                  elm.hide();
                  if(typeof(callback) == 'function'){
                        setTimeout(callback, 100);
                  }
            } else {
                  elm.fadeOut(duration, callback);
            }
            return elm;
      },
      fadeToIE: function (duration, opacity, callback)
      {
            var elm = $(this);
            if($.browser.msie)
            {
                  elm.css('opacity', opacity);
                  if(typeof(callback) == 'function')
                        setTimeout(callback, 100);
            }
            else
            {
                  elm.fadeTo(duration, opacity, callback);
            }
            return elm;
      },
      opacity: function (opacity, duration, callback)
      {
            var $elm = $(this);

            var params = {
                  opacity: opacity,
                  filter: ''
            };
            var opts = new Object;

            opts.duration = duration || 'fast';

            if(typeof(callback) == 'function')
                  opts.complete = callback;

            /*if(BrowserDetection.browser == 'ie' && BrowserDetection.version <= 8)
                  $elm.css(params);
            else*/
                  $elm.animate(params, opts);

            return $elm;
      }
});
$.fn.extend({
      href: function(){
            var self = this;
            return self.attr('href').substring(self.attr('href').indexOf('#'));
      }
})
$.extend({
      keys: function(obj)
      {
            var arr = [];
            $.each(obj, function(key){
                  arr.push(key)
            });
            return arr;
      }
});
/*
Array.prototype.clean = function(deleteValue){
  for (var i = 0; i < this.length; i++){
	if (this[i] == deleteValue){
	  this.splice(i, 1);
	  i--;
	}
  }
  return this;
}; */
$.fn.extend({
      setVars: function(){
            try{
                  var self = this;
                  var json = jQuery.parseJSON(self.html()) || self;
                  jQuery.each(json, function(key, value){
                        self.data(key, value);
                  })
            } catch(e){
                  return false;
            }
            return self;
      }
})

var CustomHover ={
      init: function (elmLink)
      {
            var elm = $(elmLink);
            $.each(elm, function (){
                  var self = $(this);
                  self
                  .append('<span class="transparent"></span>')
                  .bind('mouseover', CustomHover.mouseIn)
                  .bind('mouseout', CustomHover.mouseOut)
                  .find('.transparent').css('opacity', 'hide')
            });
      },
      mouseIn: function (e)
      {
            e.preventDefault();
            var self = $(this);
            var span = self.find('span');
            span.css({
                  'background-image': self.css('backgroundImage'),
                  'background-color': self.css('backgroundColor')
            });
            if($.browser.msie && self.css('backgroundColor') == 'transparent')
            {
                  span.css('opacity','show');
            }
            else
            {
                  span.stop().animate({
                        opacity: 1
                  }, 'fast');
            }
      },
      mouseOut: function (e)
      {
            e.preventDefault();
            var self = $(this);
            var span = self.find('span');
            if(self.hasClass('ativo')) return false;
            if($.browser.msie && self.css('backgroundColor') == 'transparent')
            {
                  span.css('opacity',0);
            // span.stop().animate({opacity: 'hide'}, 'fast');
            }
            else
            {
                  span.stop().animate({
                        opacity: 0
                  }, 'normal');
            }
      }
}
$.fn.extend({
      dnone: function(){
            this.css('display', 'none');
            return this;
      },
      dblock: function(){
            this.css('display', 'block');
            return this;
      }
});
/*--------------------------------------------------------------------
 * Plugin para customizar os Radios
--------------------------------------------------------------------*/
jQuery.fn.box3Radio = function(){
      $(this).each(function(i){
            if($(this).is('[type=checkbox],[type=radio]')){
                  var input = $(this);
                  var label = $('label[for='+input.attr('id')+']');
                  var inputType = (input.is('[type=checkbox]')) ? 'checkbox' : 'radio';
                  $('<div class="custom-'+ inputType +'"></div>').insertBefore(input).append(input, label);
                  var allInputs = $('input[name='+input.attr('name')+']');
                  label.hover(
                        function(){
                              $(this).addClass('hover');
                              if(inputType == 'checkbox' && input.is(':checked')){
                                    $(this).addClass('checkedHover');
                              }
                        },
                        function(){
                              $(this).removeClass('hover checkedHover');
                        }
                        );
                  input.bind('updateState', function(){
                        if (input.is(':checked')){
                              if (input.is(':radio')){
                                    allInputs.each(function(){
                                          $('label[for='+$(this).attr('id')+']').removeClass('checked');
                                    });
                              };
                              label.addClass('checked');
                        }
                        else {
                              label.removeClass('checked checkedHover checkedFocus');
                        }
                  })
                  .trigger('updateState')
                  .click(function(){
                        $(this).trigger('updateState');
                  })
                  .focus(function(){
                        label.addClass('focus');
                        if(inputType == 'checkbox' && input.is(':checked')){
                              $(this).addClass('checkedFocus');
                        }
                  })
                  .blur(function(){
                        label.removeClass('focus checkedFocus');
                  });
            }
      });
};
$.fn.wait = function(time, type){
      time = time || 1000;
      type = type || "fx";
      return this.queue(type, function(){
            var self = this;
            setTimeout(function(){
                  $(self).dequeue();
            }, time);
      });
};

