/*!
 * jQuery JavaScript Library v1.3.2
 * http://jquery.com/
 *
 * Copyright (c) 2009 John Resig
 * Dual licensed under the MIT and GPL licenses.
 * http://docs.jquery.com/License
 *
 * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009)
 * Revision: 6246
 */

var warnIconSuffix = '_warnicon';
var defaultUserName = 'User name';
var defaultPassword = 'Password';
var BrowserDetect = {
  init: function () {
    this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
    this.version = this.searchVersion(navigator.userAgent)
        || this.searchVersion(navigator.appVersion)
        || "an unknown version";
    this.OS = this.searchString(this.dataOS) || "an unknown OS";
  },
  searchString: function (data) {
    for (var i = 0; i < data.length; i++) {
      var dataString = data[i].string;
      var dataProp = data[i].prop;
      this.versionSearchString = data[i].versionSearch || data[i].identity;
      if (dataString) {
        if (dataString.indexOf(data[i].subString) != -1)
          return data[i].identity;
      }
      else if (dataProp)
        return data[i].identity;
    }
  },
  searchVersion: function (dataString) {
    var index = dataString.indexOf(this.versionSearchString);
    if (index == -1) return;
    return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
  },
  dataBrowser: [
    {
      string: navigator.userAgent,
      subString: "Chrome",
      identity: "Chrome"
    },
    {   string: navigator.userAgent,
      subString: "OmniWeb",
      versionSearch: "OmniWeb/",
      identity: "OmniWeb"
    },
    {
      string: navigator.vendor,
      subString: "Apple",
      identity: "Safari",
      versionSearch: "Version"
    },
    {
      prop: window.opera,
      identity: "Opera"
    },
    {
      string: navigator.vendor,
      subString: "iCab",
      identity: "iCab"
    },
    {
      string: navigator.vendor,
      subString: "KDE",
      identity: "Konqueror"
    },
    {
      string: navigator.userAgent,
      subString: "Firefox",
      identity: "Firefox"
    },
    {
      string: navigator.vendor,
      subString: "Camino",
      identity: "Camino"
    },
    {    // for newer Netscapes (6+)
      string: navigator.userAgent,
      subString: "Netscape",
      identity: "Netscape"
    },
    {
      string: navigator.userAgent,
      subString: "MSIE",
      identity: "Explorer",
      versionSearch: "MSIE"
    },
    {
      string: navigator.userAgent,
      subString: "Gecko",
      identity: "Mozilla",
      versionSearch: "rv"
    },
    {     // for older Netscapes (4-)
      string: navigator.userAgent,
      subString: "Mozilla",
      identity: "Netscape",
      versionSearch: "Mozilla"
    }
  ],
  dataOS : [
    {
      string: navigator.platform,
      subString: "Win",
      identity: "Windows"
    },
    {
      string: navigator.platform,
      subString: "Mac",
      identity: "Mac"
    },
    {
      string: navigator.platform,
      subString: "Linux",
      identity: "Linux"
    }
  ]

};
BrowserDetect.init();

// Show object identified by given id
function show(id) {
  if (!id) return;
  if (document.getElementById(id) != null) {
    document.getElementById(id).style.display = "block";
  }
}


// Hide object identified by given id 
function hide(id) {
  if (!id) return;
  if (document.getElementById(id) != null) {
    document.getElementById(id).style.display = "none";
  }
}


// Check to see if element has the given class
function hasClass(element, className) {
  if (!element) return;

  var rgx = new RegExp('\\b' + className + '\\b', 'g');
  var elemClassName = element.className;

  return (elemClassName && elemClassName.search(rgx) >= 0);
}

// opaqueBox initialization fallback
var opaqueBox = {
  containerId: "moreInfoPopupContainer",
  popupId: "moreInfoPopup"
}

function hideOrShowSelectBoxes(displayType) {
  if (BrowserDetect.browser == "Explorer" && BrowserDetect.version == "6") {
    var selectBoxes = document.getElementsByTagName("select");
    if (selectBoxes) {
      for (var i = 0; i < selectBoxes.length; i++) {
        selectBoxes[i].style.display = displayType;
      }
    }
  }
}

// Show a box that covers the entire client area
function showOpaque(opaqueContainerId, opaquePopupId) {
  hideOrShowSelectBoxes('none');
  // auxiliary functions
  function getPageXScroll() {
    var xScroll = -1;
    if (self.pageXOffset) {
      xScroll = parseInt(self.pageXOffset);
    } else if (document.documentElement && document.documentElement.scrollLeft) {
      xScroll = parseInt(document.documentElement.scrollLeft);
    } else if (document.body) {
      xScroll = parseInt(document.body.scrollLeft);
    }
    return xScroll;
  }

  function getPageYScroll() {
    var yScroll = -1;
    if (self.pageYOffset) {
      yScroll = parseInt(self.pageYOffset);
    } else if (document.documentElement && document.documentElement.scrollTop) {
      yScroll = parseInt(document.documentElement.scrollTop);
    } else if (document.body) {
      yScroll = parseInt(document.body.scrollTop);
    }
    return yScroll;
  }

  function getDocumentWidth() {
    var w1 = -1;
    var w2 = -1;
    var w3 = -1;
    if (document.documentElement) {
      w1 = parseInt(document.documentElement.scrollWidth)
      w2 = parseInt(document.documentElement.offsetWidth);
    }
    if (window.innerWidth && window.scrollMaxX) {
      w3 = parseInt(window.innerWidth) + parseInt(window.scrollMaxX);
    }
    return [w1, w2, w3].sort(function(a, b) {
      return(b - a);
    })[0]; // return the greater width
  }

  function getDocumentHeight() {
    var h1 = -1;
    var h2 = -1;
    var h3 = -1;
    if (document.documentElement) {
      h1 = parseInt(document.documentElement.scrollHeight)
      h2 = parseInt(document.documentElement.offsetHeight);
    }
    if (window.innerHeight && window.scrollMaxY) {
      h3 = parseInt(window.innerHeight) + parseInt(window.scrollMaxY);
    }
    return [h1, h2, h3].sort(function(a, b) {
      return(b - a);
    })[0]; // return the greater height
  }

  function getClientWidth() {
    var width = 0;
    if (document.documentElement && document.documentElement.clientWidth) {
      width = parseInt(document.documentElement.clientWidth);
    }
    else if (window.innerWidth) {
      width = parseInt(window.innerWidth);
    }
    else if (document.body.clientWidth) {
      width = parseInt(document.body.clientWidth);
    }
    return width;
  }

  function getClientHeight() {
    var height = 0;
    if (document.documentElement && document.documentElement.clientHeight) {
      height = parseInt(document.documentElement.clientHeight);
    }
    else if (window.innerHeight) {
      height = parseInt(window.innerHeight);
    }
    else if (document.body.clientHeight) {
      height = parseInt(document.body.clientHeight);
    }
    return height;
  }

  /*
   *  opaque container
   */
  var opaqueContainer = document.getElementById(opaqueContainerId);
  var opaquePopup = document.getElementById(opaquePopupId);
  var width = 0;
  var height = 0;
  if (opaqueContainer) {
    if (opaquePopup) {
      opaquePopup.style.left = 0;
      opaquePopup.style.top = 0;
    }
    opaqueContainer.style.display = "block";
    width = getDocumentWidth();
    if (width > 0) {
      opaqueContainer.style.width = width + 'px';
    }
    height = getDocumentHeight();
    if (height > 0) {
      opaqueContainer.style.height = height + 'px';
      if (opaqueContainer.firstChild && opaqueContainer.firstChild.className == "opaqueBox") {
        opaqueContainer.firstChild.style.height = height + 'px';
      }
    }
    // popup
    if (opaquePopup) {
      width = getClientWidth();
      if (width > 0) {
        var left = 0
        var opaqueW = parseInt(opaquePopup.offsetWidth || opaquePopup.style.width) || 600;
        if (width > opaqueW) {
          left = (width - opaqueW) / 2;
        }
        var xScroll = getPageXScroll();
        if (xScroll > 0) {
          left += xScroll;
        }
        opaquePopup.style.left = left + "px";
      }
      height = getClientHeight();
      if (height > 0) {
        var top = 10; // min top margin
        var opaqueH = parseInt(opaquePopup.offsetHeight || opaquePopup.style.height) || 540;
        if (height > opaqueH) {
          top = (height - opaqueH) / 2;
        }
        var yScroll = getPageYScroll();
        if (yScroll > 0) {
          top += yScroll;
        }
        opaquePopup.style.top = top + "px";
      }
      // in case that the document space has grown to accommodate the popup
      var width2 = getDocumentWidth();
      if (width2 > width) {
        opaqueContainer.style.width = width2 + 'px';
      }
      var height2 = getDocumentHeight();
      if (height2 > height) {
        opaqueContainer.style.height = height2 + 'px';
      }
      var iFrames = opaqueContainer.getElementsByTagName('iframe');
      if (iFrames && iFrames[0]) {
        // iframe should have the same size as the opaque box
        iFrames[0].style.height = opaqueContainer.style.height;
        iFrames[0].style.width = opaqueContainer.style.width;
        //alert('iframe (w, h) = ('+ iFrames[0].style.width +', '+ iFrames[0].style.height +')');
      }
    }
    window.onresize = new Function("showOpaque('" + opaqueContainerId + "','" + opaquePopupId + "')");
  }
}

function hideOpaque(opaqueContainerId) {
  hideOrShowSelectBoxes('block');
  var opaqueContainer = document.getElementById(opaqueContainerId);
  if (opaqueContainer) {
    opaqueContainer.style.display = 'none';
  }
  window.onresize = null;
}


// Unassign class, if it was previously assigned to the object
function unassignClass(element, className) {
  if (!element) return;

  var rgx = new RegExp('\\b' + className + '\\b', 'g');
  var elemClassName = element.className;
  if (elemClassName && elemClassName.search(rgx) >= 0) {
    elemClassName = elemClassName.replace(rgx, '');
    elemClassName = elemClassName.replace(/ {2,}/g, ' ');
    elemClassName = elemClassName.replace(/^ /g, '');
    elemClassName = elemClassName.replace(/ $/g, '');
    element.className = elemClassName;
  }
}


// Assign class to an element, at the given position
function assignClass(element, className, idx) {
  if (!element) return;

  var rgx = new RegExp('\\b' + className + '\\b', 'g');
  var elemClassName = element.className;
  if (elemClassName) {
    elemClassName = elemClassName.replace(rgx, '');
    elemClassName = elemClassName.replace(/ {2,}/g, ' ');
    elemClassName = elemClassName.replace(/^ /g, '');
    elemClassName = elemClassName.replace(/ $/g, '');
    var stys = elemClassName.split(' ');
    if (!idx || idx > stys.length) {
      idx = stys.length;
    } else {
      if (idx < 0) idx = 0;
    }
    for (var i = stys.length; i > idx; i--) {
      stys[i] = stys[i - 1]; // move right
    }
    stys[idx] = className;
    elemClassName = stys.join(' ');
  }
  else {
    elemClassName = className;
  }
  if (element.className != elemClassName) {
    element.className = elemClassName;
  }
}

function getInvalidItem(msg) {
  return "<li>" + msg + "</li>";
}


// Get all elements, having the specified tag name and class, from the given container
function getElements(containerId, tagName, className) {
  var container = document.getElementById(containerId);
  var setByTag = container.getElementsByTagName(tagName);
  var elements = new Array();
  var k = 0;

  for (var i = 0; i < setByTag.length; i++) {
    if (hasClass(setByTag[i], className)) {
      elements[k++] = setByTag[i];
    }
  }

  return elements;
}

// Check if given field is empty
function isEmpty(field) {
  var isEmpty = (!field || !field.value || field.value.search(/^ *$/) == 0);
  return isEmpty;
}
function isAlphanumeric(field) {
  var regex = /^[0-9A-Za-z]+$/;
  return regex.test(field.value);
}

// Check if the selection in the dropdown is the default one
function isDefaultSelection(selectField) {
  var isDefaultSelection = (selectField.selectedIndex == 0);
  return isDefaultSelection;
}


// Reset error mark for the given element, in the case it is subject of error
function resetErrorMark(element, errorClass) {
  if (!hasClass(element, errorClass)) {
    return;
  }

  unassignClass(element, errorClass);
  // check if there is a warning icon displayed along with the field
  var elementWarnIconId = element.id + warnIconSuffix;
  var elementWarnIcon = document.getElementById(elementWarnIconId);
  if (elementWarnIcon) {
    assignClass(elementWarnIcon, 'hidden');
  }

  return true;
}


// Clear default text and reset error field (if it is the case) 
function resetField(element, defaultStr) {
  if (element && element.value == defaultStr) {
    element.value = "";
  }

  // reset error indication, if needed
  resetErrorMark(element, 'inputErr');
}


// Reset error field (if it is the case) 
function resetSelect(element) {
  // reset error indication, if needed
  resetErrorMark(element, 'inputErr');
}

// Enable/disable button
function enableButton(btnId, enabled) {
  var btn = document.getElementById(btnId);

  if (enabled) {
    unassignClass(btn, 'textBtnDisabled');
  }
  else {
    assignClass(btn, 'textBtnDisabled');
    btn.href = "javascript:void(0)";
  }
}
// Submit login form, when pressing ENTER 
function loginOnEnter(e) {
  var keycode;
  if (window.event) {    // IE
    keycode = window.event.keyCode;
  }
  else {
    if (e) keycode = e.which;
    else return true;
  }
  if (keycode == 13) {
    login();
    return false;
  }
  return true;
}

// Log in user, after performing basic login data validation
function login() {
  var userInput = document.getElementById('username');
  var pwdInput = document.getElementById('pwd');
  var validUser = true;
  var validPassword = true;

  if (!userInput || !userInput.value || userInput.value.search(/^ *$/) == 0 || userInput.value == defaultUserName) {
    // invalid username
    show('loginErr');
    assignClass(userInput, "inputErr");
    validUser = false;
  }
  if (!pwdInput || !pwdInput.value || pwdInput.value == defaultPassword) {
    // invalid password
    show('loginErr');
    assignClass(pwdInput, "inputErr");
    validPassword = false;
  }
  if (validUser && validPassword) {
    hide('loginErr');
    resetErrorMark(userInput, "inputErr");
    resetErrorMark(pwdInput, "inputErr");
    //go on with login logic
  }
}


// Get the list of filter checkboxes from the given container
function getFilterCheckboxes(containerId) {
  var filters = new Array();
  if (document.getElementById(containerId) == null) {
    return;
  }
  inputSet = document.getElementById(containerId).getElementsByTagName('input');
  k = 0;

  for (var i = 0; i < inputSet.length; i++) {
    if (inputSet[i].type == 'checkbox') {
      filters[k++] = inputSet[i];
    }
  }

  return filters;
}

// Check to see if at list a filter checkbox is checked in the given container
function isFilterChecked(containerId) {
  var filters = getFilterCheckboxes(containerId);

  for (var i = 0; i < filters.length; i++) {
    if (filters[i].checked) {
      return true;
    }
  }

  return false;
}


// Uncheck all filter checkboxes in the given container
function resetFilterCheckboxes(containerId) {
  var filters = getFilterCheckboxes(containerId);

  for (var i = 0; i < filters.length; i++) {
    filters[i].checked = false;
  }
}

// Tab switcher - initialisation 
// tabContainerId = ID of tab container
function initTabs(tabContainerId) {
  var tabContainer = document.getElementById(tabContainerId);
  if (!tabContainer) return;

  var divSet = tabContainer.getElementsByTagName('div');
  var firstTabFlag = 0;
  for (var i = 0; i < divSet.length; i++) {
    if (divSet[i].className == 'tabcontent') {
      if (!firstTabFlag) {
        divSet[i].className = '';
        firstTabFlag = 1;
      } else {
        divSet[i].className = 'hidden';
      }
    }
  }
}

// Tab switcher
// container = ID of tab container, must be used if more than one tab module is used on page (optional usage if only one tab module is displayed on a page )
// tab = ID of tab (mandatory)
function showTab(tab, container) {
  if (typeof(container) == 'undefined') {
    container = '';
  }
  var i = 1;
  do{
    document.getElementById(container + "tab" + i).className = "tab";
    if (document.getElementById(container + "tab" + i + "content")) {
      document.getElementById(container + "tab" + i + "content").style.display = "none";
    }
    i++;
  }
  while (document.getElementById(container + "tab" + i));
  document.getElementById(container + tab + "content").style.display = "block";
  document.getElementById(container + tab).className = "activeTab";
}


// Fold/unfold table rows
// optId = row to be folded/unfolded
function foldRow(optId) {
  var optHeader = document.getElementById(optId);
  if (optHeader != null) {
    var pattern = new RegExp("(^|\\s)" + optId + "(\\s|$)");
    var trList = document.getElementsByTagName('tr');
    if (optHeader.className == "optShow") {
      // hide options
      for (i = 0; i < trList.length; i++) {
        if (pattern.test(trList[i].className)) {
          assignClass(trList[i], "hidden");
        }
      }
      optHeader.className = "optHide";
    } else {
      // show options
      for (i = 0; i < trList.length; i++) {
        if (pattern.test(trList[i].className)) {
          unassignClass(trList[i], "hidden");
        }
      }
      optHeader.className = "optShow";
    }
  }
} // foldRow



// Color switcher
// colorBtnId = ID of the color button that should become the active one
function selectColor(colorBtnId) {
  var i = 1;

  do{
    var crtBtnId = "color" + i;
    var crtEl = document.getElementById(crtBtnId);
    if (crtBtnId == colorBtnId) {
      crtEl.className += " selected";
    }
    else {
      crtEl.className = crtEl.className.replace(/selected/i, "");
    }
    i++;
  }
  while (document.getElementById("color" + i));
}


// Display/Hide popup
// popupId = ID of the popup container to be displayed/hidden 
// displayMode = indicates whether to display or hide popup
function displayPopup(popupId, displayMode) {
  var container = document.getElementById(popupId);
  container.style.display = displayMode;
}


// Fold/Unfold expandable divs
// optionId = ID of the section to be folded/unfolded
function toggleOption(optId) {
  var optHeader = document.getElementById(optId);

  if (optHeader != null) {
    var pattern = new RegExp("(^|\\s)" + optId + "(\\s|$)");
    var divList = document.getElementsByTagName('div');

    if (optHeader.className == "expanderHide") {
      // hide options
      for (i = 0; i < divList.length; i++) {
        if (pattern.test(divList[i].className)) {
          var copyClassName = divList[i].className;
          divList[i].className = copyClassName.replace(/expanded/i, "collapsed");
        }
      }
      optHeader.className = "expanderShow";

    } else {
      // show options
      for (i = 0; i < divList.length; i++) {
        if (pattern.test(divList[i].className)) {
          var copyClassName = divList[i].className;
          divList[i].className = copyClassName.replace(/collapsed/i, "expanded");
        }
      }
      optHeader.className = "expanderHide";
    }
  }
}

function submitForm(formId) {
  var form = document.getElementById(formId);
  if (form != null) {
    form.submit();
  }
}

// replace submit button by a styled button
function replaceButton(formId, buttonId) {
  var form = document.getElementById(formId);
  var button = document.getElementById(buttonId);
  if (!form && !button) return;

  var text = button["value"];
  var color = button.className; // f.e. inputBtnRed
  color = color.slice(8); // f.e. Red
  switch (color) {
    case "Red":
    case "Purple":
    case "Grey":
      break;
    default:
      color = "Red";
  }
  button.className = "hidden";
  var styledBtn = "<a href='#' onclick='document.getElementById(\"" + formId + "\").submit();' class='textBtn" + color +
      " formBtn'><span>" + text + "</span></a>";
  document.write(styledBtn);
} // replaceButton


// set styles for disabled options in dropdown controls  -- CSS doesn't work for IE !
function setDisabledOptionStyle(selectList) {

  for (var k = 0; k < selectList.options.length; k++) { // set styles for disabled options
    if (selectList.options[k].disabled) {
      //assignClass(selectList.options[k], 'categoryOption');
      selectList.options[k].style.color = "#999";
    }
  }
}

// set selection in a dropdown that support item groups
function setSelectionInGroupingCombo(selectListId) {
  var selectList = document.getElementById(selectListId);
  // skip disabled option     
  if (selectList.options[selectList.selectedIndex].disabled) {
    if (selectList.options.length <= 1) {
      selectList.selectedIndex = -1;
    }
    else
    if (selectList.selectedIndex < selectList.options.length - 1) {
      var nextIndex = selectList.selectedIndex + 1;
      if (selectList.options[nextIndex].disabled)  // group separator
        selectList.selectedIndex += 2;  //select first option from the next set of numbers
      else {
        selectList.selectedIndex++;
      }
    }
    else {
      selectList.selectedIndex--;
    }
  }
}
/**
 * When logged in users click the send button from telesales box this method is invoked.
 */
function submitTelesales() {

  var dataString = "phoneNumber=" + document.telesales["phoneNumber"].value + "&formName=" +
      document.telesales["formName"].value;
  var urlstr = "/shop/telesales";
  $.ajax({
    type: "GET",
    data:dataString,
    url: urlstr,
    success: function() {
      showOpaque("telesalesSuccessPopupContainer");
    },
    error: function() {
      //do nothing
    }
  });
}
