var _me = top.location.pathname;

/* Byter ut meny-bild vid onMouseOver/Out
 */
function menuHoover(e) {
   var match = e.src.match(/^(.*\/)m(\d)\w\.gif$/);
   if (!match) {
      return false;
   }
   var path = match[1];
   var num = match[2];

   if (!e.imgMem) {
      e.imgMem = e.src;
      e.src = path + 'm' + num + 'b.gif';
   }
   else {
      e.src = e.imgMem;
      e.imgMem = false;
   }
}


/* Table row hover in
 */
function hIn(rowElement) {
   // Remember current bgcolor so hOut() can restore it
   hInMem = rowElement.style.backgroundColor;

   // Set new color
   rowElement.style.backgroundColor = '#ececec';
}


/* Table row hover out
 */
function hOut(rowElement) {
   // Restore color from mem
   rowElement.style.backgroundColor=hInMem;
}


/* When changeing product group
 * in product_admin.
 */
function editSelection1(arg) {
   top.location.href = _me + '?action=edit&' + arg;
}


/* When changeing product sub group
 * in product_admin.
 */
function editSelection2(cat2Id) {
   top.location.href = _me + '?action=edit&cat2='+cat2Id;
}


/* When focus a editable field
 */
function editFocus(element) {
   element.style.border='1px solid black';
   element.style.color='#659ACF';
}


/* When bluring a editable field
 */
function editBlur(element) {
   element.style.border='0px';
   element.style.color='';

   var eId = element.id;

   element.value = trim(element.value);

   var val = element.value;
   val += '';

   for (i = 0; i < fldData.length; i++) {
      var id     = fldData[i][0];
      var type   = fldData[i][1];
      var isNull = fldData[i][2];

      if (eId == 'fld' + id) {
         // Empty fields will be saved as NULL in db
         if (val == '') {
            return;
         }
         switch (type) {
            case 'int':
               if (!val.match(/^\d+$/)) {
                  alert('Värdefel. "' + val + '" är inte ett heltal.');
                  element.focus();
                  element.select();
               }
               break;

            case 'string':
               // Always valid...
               break;

            case 'real':
               if (val.match(/^\d+\.\d{2}$/)) {
                  return;
               }

               if (val.match(/^\d+$/)) {
                  val += '.00';
                  element.value = val;
                  return;
               }

               if (val.match(/^\d+\.$/)) {
                  val += '00';
                  element.value = val;
                  return;
               }

               if (val.match(/^\d+\.\d$/)) {
                  val += '0';
                  element.value = val;
                  return;
               }

               alert('Värdefel. "' + val + '" är inte ett decimaltal.');
               element.focus();
               element.select();
               break;         
         }
      }
   }
}


/* Show selected product image in new window.
 */
function openImage() {
   var d = document.getElementById('imageDropDown');
   if (d && d.value == '') {
      alert("Du måste välja en bild först.");
      d.focus();
      return;
   }

   var filename = d.options[d.selectedIndex].text;
   window.open('img/products/' + filename, 'productImage', 'width=220,height=200,scrollbars,toolbar');
   return;
}


/* Open popup window where we can change productgroup
 */
function changeProductGroup() {
   var id = document.getElementById('productGroupInput').value;
   window.open('select_product_group_popup.php?cat2=' + id + '&noSubmit=1',
               'chProd', 'width=400,height=100,scrollbars,toolbar');
}


/* On pupup window cat2 submit - change values in
 * parent window.
 */
function changeParentProductGroup(id, name) {
   var d = parent.opener.document;
   textElement  = d.getElementById('productGroup');
   inputElement = d.getElementById('productGroupInput');

   textElement.innerHTML = name;
   inputElement.value = id;
   window.close();
}


// Trim a string
function trim(str) {
   str += ''; // Make sure it's a string
   return str.replace(/\s*$/, '').replace(/^\s*/, '');
}



function saveProductEdit(saveAsNew, artNrFieldId) {
   var f = document.productForm;
   if (!f) {
      alert("Error: unable to find form(!?)");
      return false;
   }

   if (f.parent.value == '') {
      alert("Du måste ange en produktgrupp");
      document.getElementById('productGroup').focus();
      return false;
   }

   if (typeof(fldData) != 'object') {
      alert("Error in application. typeof() fldData should be 'object'.");
      return false;
   }

   var res = [];

   for (i = 0; i < fldData.length; i++) {
      var id     = fldData[i][0];
      var type   = fldData[i][1];
      var isNull = fldData[i][2];

      var eId    = 'fld' + id;
      var e = document.getElementById(eId);

      if (!e) {
         alert("Error in application. Unable to find element with id: '" + eId + "'." +
               "Submit canceled!");
         return false;
      }

      if (artNrFieldId == id && e.value == '') {
         alert("Art.nr måste anges och vara unikt");
         e.focus();
         return false;
      }

      if (e.value != '') {
         res.push(id + ':' + escape(e.value));
      }
   }

   f.data.value = res.join(',');

   // Setting pid to "0" force the server to save as new product
   if (saveAsNew) {
      f.pid.value = 0;
   }

   f.submit();
}


/* Filter text when writing and cancel certain keycodes
 *
 * FIXME: function not complete
 */
function filterKeyPress(filter, event) {
   var c = event.keyCode;

   // Always allow these keys
   if ((c >= 48 && c <= 57) || // 0-9
       (c >= 37 && c <= 40) || // Arrows
       c == 8 || c == 46) {    // Delete
      return true;
   }

   if (event.ctrlKey) {

   }

   alert(event.keyCode);
   return false;
}


/* When administrating menus.
 * Load visible fields from the hidden input. Check for values
 * in the left select-box and add it to the right select-box.
 */
function initFields() {
   // Visible fields input
   var eVisibleFields = document.getElementById('visibleFields');
   // Selected fields
   var eVis = document.getElementById('visFields');
   // All fields in db
   var eDb  = document.getElementById('dbFields');

   var fields = eVisibleFields.value.split(',');

   // Iterate visible fields
   for (i = 0; i < fields.length; i++) {
      // Try to find the field-id in the left select and add it to the right
      for (j = 0; j < eDb.options.length; j++) {
         if (eDb.options[j].value == fields[i]) {
            eVis.options[i] = new Option(eDb.options[j].text, eDb.options[j].value);
            continue;
         }
      }
   }
}

/* Save selected fields as a "," separated string
 * in the visibleFields hidden input
 */
function saveFields() {
   // Visible fields input
   var eVisibleFields = document.getElementById('visibleFields');
   // Selected fields
   var eVis = document.getElementById('visFields');

   var vals = [];
   for (i = 0; i < eVis.options.length; i++) {
      vals.push(eVis.options[i].value);
   }
   eVisibleFields.value = vals.join(',');
}

function addField() {
   // Selected fields
   var eVis = document.getElementById('visFields');
   // All fields in db
   var eDb  = document.getElementById('dbFields');

   var index = eDb.selectedIndex;
   if (index < 0) {
      alert("Du måste markera ett fält först");
      eDb.focus();
      return false;
   }

   eVis.options[eVis.options.length] = new Option(eDb.options[index].text, eDb.options[index].value);
}

function saveFields() {
   // Selected fields
   var eVis = document.getElementById('visFields');
   // Visible fields input
   var eVisibleFields = document.getElementById('visibleFields');

   var fields = [];

   for (i = 0; i < eVis.options.length; i++) {
      fields.push(eVis.options[i].value);
   }

   eVisibleFields.value = fields.join(',');
}


function removeField() {
   // Selected fields
   var eVis = document.getElementById('visFields');

   var index = eVis.selectedIndex;
   if (index < 0) {
      alert("Du måste markera ett fält först");
      eVis.focus();
      return false;
   }

   eVis.options[index] = null;
}


/* OnSubmit when saving cat2 menu
 */
function saveCat2AdminForm(){
   f = document.cat2AdminForm;

   if (f.parent2.value == '') {
      alert("Du måste välja huvudmeny");
      f.parent2.focus();
      return false;
   }

   if (f.name.value == '') {
      alert("Du måste ange ett namn på underproduktgruppen");
      f.name.focus();
      return false;
   }

   saveFields();

   return true;
}


function navToCat2(id) {
   top.location.href = _me + '?cat2=' + id;
}


/* Set value in the searchform
 * if the variable gvSearchStr is present.
 */
function setSearchStr() {
   // Will fail if gvSearchStr isn't defined
   try {
      f = document.searchForm;
      if (gvSearchStr != '') {
         f.q.value = gvSearchStr;
         f.q.blur();
      }
   }
   catch (e) {
   }
}



function saveCat1AdminForm(){
   f = document.cat1AdminForm;

   if (f.parent.value == '') {
      alert("Du måste välja huvudmeny");
      f.parent.focus();
      return false;
   }

   if (f.name.value == '') {
      alert("Du måste ange ett namn på produktgruppen");
      f.name.focus();
      return false;
   }

   return true;
}

