// bleau.utils.js
// version 1.0

var Bleau = {
  init: function() {
    setupRequiredFields();
  },
  Util: {
    gotoPage: function(sPageId) {Bleau.Util.gotoURL('/default.aspx?id='+sPageId)},
    gotoURL: function(sURL) {document.location = sURL},
    logOff: function() {logOff();},
    toggleForgotPassword: function(sFormId) {
      var oExtUserForm = jQuery('#ExtUserForm');

      var oFrmForgotPassword = jQuery('#frmForgotPassword');
      var oFrmClicked = jQuery('#'+sFormId);
      
      var oForgotPassword = jQuery('#forgotPassword');
      var oForgotPassword1 = jQuery('#forgotPassword1');
      
      oFrmClicked.css('display', 'none');
      if (oFrmClicked.attr('id')==oExtUserForm.attr('id')) {
        oForgotPassword.attr('checked', '')
        oForgotPassword1.attr('checked', 'checked')
        oFrmForgotPassword.css('display', 'inline');
        jQuery('#email').focus();
      } else {
        oForgotPassword.attr('checked', '')
        oForgotPassword1.attr('checked', '')
        oExtUserForm.css('display', 'inline');
      }
    },
    isValidEmail: function() {isValidEmail();},
    editExtranetInformation: function(sPageID) {
      var sLoc = document.location+'';
      if (sLoc.indexOf('&Action=2')==-1) {
        sLoc = location.protocol+'//'+location.host+((location.port!='') ? ':'+location.port : '')+'/?id='+sPageID+'&Action=2';
        document.location = sLoc;
      };
    },
    restoreExtranetUsernameAndPassword: function(options) {
      var defaults = {
        username: 'username',
        password: 'password',
        rememberUsername: 'DWExtranetUsernameRemember',
        rememberPassword: 'DWExtranetPasswordRemember'
      };
      var options = jQuery.extend(defaults, options);
      
      if (jQuery('#'+options.rememberUsername).attr('checked')==true) {
        jQuery('#'+options.username).attr('value', Bleau.Util.getCookie('DWExtranetUsername'));
      }
      if (jQuery('#'+options.rememberPassword).attr('checked')==true) {
        jQuery('#'+options.password).attr('value', Bleau.Util.getCookie('DWExtranetPassword'));
      }
    },
    getCookie: function(name) {return _getCookie(name)}
  },
  Ecom: {
    writeNavigation: function(oParams) {writeNavigation(oParams);},
    emptyBasket: function(sAskFirst, sPageId) {
      var bEmpty = (typeof sAskFirst!='undefined') ? confirm(sAskFirst) : true;
      if (bEmpty) {
        document.location = '/default.aspx?CartCmd=EmptyCart'+((typeof sPageId!='undefined') ? '&id='+sPageId : '');
      }
    }
  }
};

var sCookies = document.cookie+'';
function _getCookie(name) {
  var iStart = sCookies.indexOf(name);
  if (iStart==-1) return null;
  iStart = sCookies.indexOf('=', iStart)+1;
  var iEnd = sCookies.indexOf('&', iStart);
  iEnd = (iEnd==-1) ? sCookies.indexOf(';', iStart) : iEnd;
  iEnd = (iEnd==-1) ? sCookies.length : iEnd;
  return sCookies.substr(iStart, iEnd-iStart);
}

var aFormsWithRequiredFields = [];
function setupRequiredFields() {
  jQuery('form: *[class*="required"]').each(function() {
    var oForm = jQuery(this).parents("form");
    if (typeof aFormsWithRequiredFields[oForm.attr('id')] == 'undefined') {
      aFormsWithRequiredFields[oForm.attr('id')] = oForm;
      jQuery(oForm).bind('submit', checkRequiredAndCustom);
      //jQuery(oForm).bind('submit', function() {alert(jQuery(this).html())});
    }
  });
  
}

function checkRequiredAndCustom() {
  var sInfo = '';
  var oFocus = null;
  jQuery('*[class*="required"]', jQuery(this)).each(function() {
    var o = jQuery(this);
    o.removeClass(sClassNotValid);
    if (jQuery.trim(o.attr('value')).length==0) {
      if (oFocus==null) oFocus = o;
      sInfo+='- '+o.attr('title')+'\n';
      o.addClass(sClassNotValid);
    }
  })
  
  // BleauCustomValidation
  /* Inds?t en hidden v?rdi i din form - eks:
     <input type="hidden" name="BleauCustomValidation" value="isValidEmail,Email" title="E-mail ikke valid" />
     Parametre:
     name: BleauCustomValidation
     value: ["funktionsnavn", [param1,param2,...paramX]
     title: Fejlbeskeden der skal vises hvis funktion retunerer false
  */
  sInfo+= (sInfo!='') ? '\n' : '';
  jQuery('*[name="BleauCustomValidation"]', jQuery(this)).each(function() {
    var o = jQuery(this);
    var aFunctionCall = jQuery.trim(o.attr('value')).split(',');
    if (aFunctionCall.length>0) {
      var sFunctionCall = aFunctionCall[0]+'(';
      for(var i=1; i<aFunctionCall.length; i++) {
         sFunctionCall+= ((i>1) ? ' ,' : '')+'"'+aFunctionCall[i]+'"';
      }
      sFunctionCall+=')';
      var oResult = eval(sFunctionCall);
      if (oResult!=true) {
        if (oFocus==null) oFocus = o;
        sInfo+='- '+o.attr('title')+'\n';
        jQuery.each(oResult, function() {
          jQuery(this).addClass(sClassNotValid);
          }
        )
      }
    }
  });
  
  if (sInfo=='') {
    jQuery('*[name="BleauCustomValidation"]', jQuery(this)).each(function() {
      jQuery(this).remove();
    })
    return true;
  }
  alert('Udfyld venligst felterne:\n'+sInfo)
  oFocus.focus();
  return false;
}

function logOff() {
  document.location='http://'+document.location.host+'/admin/public/extranetlogoff.aspx';
}

function isElementValidEmail(sElementId) 
{
  var o = jQuery('#'+sElementId)
  if (isValidEmail(o.attr('value'))) return true;
  return o;
}

function isValidEmail(sEmail) 
{
  sEmail = jQuery.trim(sEmail);
  return (sEmail.length>0 && sEmail.search(oReEmail)>-1);
}
function areFieldEqual(v1, v2) 
{
 var o1 = jQuery('#'+v1);
 var o2 = jQuery('#'+v2);
 if (jQuery.trim(o1.attr('value'))==jQuery.trim(o2.attr('value'))) return true;
 return [o1, o2];
}

/* STH: 2009-01-27, Writes a eCommerce navigation panel from some given parameters
   It has default settings, which will be used if they are not supplied through parameters
   Example:
    Bleau.Ecom.writeNavigation({'TotalPages':<!--@Ecom:ProductList.TotalPages-->, 'CurrentPage':<!--@Ecom:ProductList.CurrentPage-->, 'PageProdCnt':<!--@Ecom:ProductList.PageProdCnt-->, 'PageSize':<!--@Ecom:ProductList.PageSize-->, 'PrevPage':'<!--@Ecom:ProductList.PrevPage.Clean-->', 'NextPage':'<!--@Ecom:ProductList.NextPage.Clean-->'});
   CSS:
    .navigation {clear: both;}
    .navigation a { margin-left: 5px; }
    .navigation a.current {font-size: 13px; font-weight: bold; }
    .navigation a.prev, .navigation a.next {}
*/
function writeNavigation(oParams) {
  var oDefault = {
    'TotalPages':1,
    'CurrentPage':1,
    'PageProdCnt':3,
    'PageSize':9,
    'PrevPage':'',
    'NextPage':'',
    'PrevSymbol':'<<',
    'NextSymbol':'>>',
    'ShowIfOnlyOnePage':false
  };
  var sURL = getLocationWithoutParams(['PageNum']);
  var oSettings = getSettings(oDefault, oParams);
  
  
  var sNavigation = '<div class="navigation">';
  if (oSettings.ShowIfOnlyOnePage==false && parseInt(oSettings.TotalPages)==1) {
    return
  }
    sNavigation+= (oSettings.PrevPage!='') ? '<a href="'+sURL+'&PageNum='+(oSettings.CurrentPage-1)+'" class="prev">'+oSettings.PrevSymbol+'</a>' : '';
    for(var iPage=1; iPage<=oSettings.TotalPages; iPage++) {
      var sClass = (iPage==oSettings.CurrentPage) ? ' class="current"' : '';
      sNavigation+='<a href="'+sURL+'&PageNum='+iPage+'"'+sClass+'>'+iPage+'</a>';
    }
    sNavigation+= (oSettings.NextPage!='') ? '<a href="'+sURL+'&PageNum='+(oSettings.CurrentPage-0+1)+'" class="next">'+oSettings.NextSymbol+'</a>' : '';
  
  sNavigation+='</div>'
  // PrevPage PAGES NextPage
  document.write(sNavigation);
}

/* STH: 2009-01-27, Returns document location where the paramnames specified in array has been removed */
function getLocationWithoutParams(aParams) {
  var sUrl = document.location+'';
  for(var iParam=0; iParam<aParams.length; iParam++) {
    var oPageNum = new RegExp('&'+aParams[iParam]+'.*', 'ig');
    sUrl = sUrl.replace(oPageNum, '');
  }
  return sUrl;
}

function getSettings(oDefault, oParams) {
  var oSettings = [];
  for(key in oDefault) {
    oSettings[key] = (isDefined(oParams[key])) ? oParams[key] : oDefault[key];
  }
  return oSettings;
}

function isDefined(o) {
  return (typeof o!='undefined')
}

/* CONSTANTS */
var oReEmail          = /([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})/;
var oReEmail          = /^[^@]+@[^@]+.[a-z]{2,}$/i;
var sClassNotValid    = 'notValid'; // When validating af form, this class is added if field required or not valid

/* Usability goodies */

/* Generelt statup kode */
var oReKr = /^(kr.)/ig
jQuery(document).ready(function() {
  if (jQuery('.help') != null)
  {
  jQuery('.help').each(function() {
    jQuery(this).bind('mouseover', showTooltip);
    jQuery(this).bind('mouseleave', hideTooltip);
  });
  }

  if (jQuery('.date') != null)
  {  
  jQuery('.date').each(function() {
    var oThis = jQuery(this);
    oThis.text(oThis.text().replace('-', '.').replace('-', '.'));
  });
  }

  if (jQuery('.number.DKK') != null)
  {
  jQuery('.number.DKK').each(function() {
    var oThis = jQuery(this);
    oThis.text(jQuery.trim(oThis.text()).replace(oReKr, 'DKK'));
  });
  }

  if (jQuery('.number, .bignumber, .biggernumber') != null)
  {
  jQuery('.number, .bignumber, .biggernumber').each(function() {
    var oThis = jQuery(this);
    oThis.text(jQuery.trim(oThis.text()).replace(oReKr, ''));
  });
  }
  
  // H?ndteringen af defaultv?rdier for input felter
  handleDefaultValue();
  
  // replaceBrackets
  replaceBrackets();
})

var oBrackets = new RegExp('(\\[(.*)\\])', 'g');
function replaceBrackets() {
  jQuery('.replaceBrackets').each(function() {
    jQuery(this).html((jQuery(this).html()+'').replace(oBrackets, '<span class="brackets">Bleau</span>'));
  });
}

function handleDefaultValue() {

  jQuery('input.defaulttext').each(function() {
    jQuery(this).bind('click', function() {
      var oThis = jQuery(this);
      var sDefault = oThis.attr('title');
      if (oThis.attr('value')==sDefault) {
        oThis.attr('value', '')
      }
    });
    jQuery(this).bind('blur', function() {
      var oThis = jQuery(this);
      var sDefault = oThis.attr('title');
      if (jQuery.trim(oThis.attr('value'))=='') {
        oThis.attr('value', sDefault)
      }
    });
 });

}

var oTooltip, sToottip, oTooltipElement;
function showTooltip() {
  oTooltipElement = jQuery(this);
  var offset = oTooltipElement.offset();
  
  var top = -28;
  var left = -100;
  sToottip = oTooltipElement.attr('title');
  oTooltip = jQuery('<div class="tooltip" style="left:'+(offset.left+left)+'px; top: '+(offset.top+top)+'px; color: black;">'+sToottip+'</div>')
  oTooltipElement.attr('title', '');
  oTooltip.insertBefore(oTooltipElement);
}
function hideTooltip() {
  jQuery(oTooltip).remove();
  oTooltipElement.attr('title', sToottip);
}
/* tooltip END */

/* EXTRA */
    function microformatWriteDateTime(yy, mm, dd, hh, mi, se) {
       var sFormat = '<abbr class="date" title="%yy%-%mm%-%dd%T%hh%:%mi%:%se%Z+01:00">%dd%.%mm%.%yy%</abbr>';
       mm = pad(mm);
       dd = pad(dd);
       hh = pad(hh);
       mi = pad(mi);
       se = pad(se);
       sFormat = replace(sFormat, 'yy', yy);
       sFormat = replace(sFormat, 'mm', mm);
       sFormat = replace(sFormat, 'dd', dd);
       sFormat = replace(sFormat, 'hh', hh);
       sFormat = replace(sFormat, 'mi', mi);
       sFormat = replace(sFormat, 'se', se);
       document.write(sFormat);
    }
    
    function replace(sSource, sPattern, sReplaceWith) {
      var oRe = new RegExp('%'+sPattern+'%', 'g');
      return sSource.replace(oRe, sReplaceWith);
    }
    
    function pad(sString, iLength, sPadChar, bAfterString) {
       var iL = sString.length;
       iLength = (typeof iLength=='undefined') ? 2 : iLength;
       if (iL>=iLength) return sString;
       
       sPadChar = (typeof sPadChar=='undefined') ? '0' : sPadChar;
       bAfterString = (typeof bAfterString=='undefined') ? false : bAfterString;
       var sTemp = sPadChar;
       for(var i=1; i<iLength-iL; i++) {
         sTemp+=sPadChar;
       }
       return (bAfterString) ? sString+sTemp : sTemp+sString;
    }
