/*
 * The function is intended for all elements which are submitting form onClick event
 */
function submitParentForm(calledElement) {
  var parentElement = calledElement.parentNode;
  while (parentElement != null) {
    if (parentElement.tagName == 'FORM') {
      input_tags = $(parentElement).getElementsBySelector('input','button');
      
      for (n = 0; n < input_tags.length; n++) {
        if (input_tags[n].type == 'submit') {
          if (arguments[1] != undefined) {
            if (input_tags[n].id == arguments[1]) {
              input_tags[n].click();
              break;
            }
          } else {
            input_tags[n].click();
            break;  
          }
        }  
      }
      break;
    } else {
      parentElement = parentElement.parentNode;
    }
  }
}

function getWindowWH() {
  var windowWidth = 0, windowHeight = 0;
  if (window.innerHeight) { // all except Explorer
    windowWidth = self.innerWidth;
    windowHeight = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
    windowWidth = document.documentElement.clientWidth;
    windowHeight = document.documentElement.clientHeight;
  } else if (document.body) { // other Explorers
    windowWidth = document.body.clientWidth;
    windowHeight = document.body.clientHeight;
  }
  return [windowWidth, windowHeight];
}

/*boxSearchAfter*/

function changePrice(el) {
  for (var i=0; i < el.options.length; i++)
  {
      if (el.options[i].selected) {
        var name_field = document.getElementById('box_search_after_price_title');
        
        if (el.options[i].value) {
          var text = "";
          text = el.options[i].innerHTML;
          var re = / (\(\d+\))/;
          text = text.replace(re, "");
          name_field.value = text;
        } else {
          name_field.value = '';
        }
        break;
      } 
  }
  el.form.submit();
}

function resetFilter(filter_name) {
  var filter = document.getElementById('box_search_after_'+filter_name);
  filter.value = '';
  filter.form.submit();
  return false;
}

function changeCategory(select, categoryID, cPath) {
  var new_category = 0;
  if (select) {
    new_category = select.value;
  } else {
    new_category = categoryID?categoryID:'';
  }

  var cPath_field = document.getElementById('box_search_after_cPath');
  if (cPath_field) {
    if (!cPath) {
      if (cPath_field.value && new_category) {
        cPath  = cPath_field.value+'_'+new_category;
      } else {
        cPath  = new_category?new_category:'';
      }
    }
    cPath_field.value = cPath;
  }
  
  var new_category_input = document.getElementById('box_search_after_category');
  if (new_category_input) {
    new_category_input.value = new_category;
  }

  cPath_field.form.submit();
  return false;
}

/*boxProductListing*/
  function goCompare(product_link, product_id, compare_error, seo_enabled, mod_rewrite_enabled) {
    compare_link = product_link+"&c_products[]="+product_id;
    cmpa = $$(".compareCheckBox");
    checked_count = 0;

    var delimeter_1 = '&';
    var delimeter_2 = '[]=';

    if (seo_enabled) {
      delimeter_1 = delimeter_2 = '/';
      var re  = /\?(.+)$/g;
      if (!product_link.match(re)) {
        delimeter_1 = '?';
      } else {
         if (!mod_rewrite_enabled) {
           delimeter_1 = '&';
         }
      }
    }

    if(cmpa) {
      compare_link = product_link;
      for(i=0;i<cmpa.length;i++) {
        if(cmpa[i]) {
           if (cmpa[i].checked) {
             compare_link += delimeter_1 + "c_products" + delimeter_2 + cmpa[i].value;
             if (seo_enabled && delimeter_1 != '/') {
               delimeter_1 = '/';
             }
             checked_count++;
           }
        }
      }
    }

    if (checked_count > 1)
      document.location = compare_link;
    else
      ajax.btv_Alert(compare_error);
  }

  function getScrollXY() {
    var scrOfX = 0, scrOfY = 0;
    if( typeof( window.pageYOffset ) == 'number' ) {
      //Netscape compliant
      scrOfY = window.pageYOffset;
      scrOfX = window.pageXOffset;
    } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
      //DOM compliant
      scrOfY = document.body.scrollTop;
      scrOfX = document.body.scrollLeft;
    } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
      //IE6 standards compliant mode
      scrOfY = document.documentElement.scrollTop;
      scrOfX = document.documentElement.scrollLeft;
    }
    return [ scrOfX, scrOfY ];
  }

  function fade(obj, maximum, step){
     if ($(obj)) {
       if ($(obj).getOpacity() <= maximum) {
         nextValue = $(obj).getOpacity() + step;
         $(obj).setOpacity((nextValue < 1)?nextValue:1.05);
         setTimeout("fade('"+obj+"',"+maximum+","+step+")", 50);
       }
     }
  }

  function showImage(path, width, height) {
      var x,y;
      coords  = getScrollXY();
      x = coords[0];
      y = coords[1];

      pnl = document.createElement("div");
      pnl.innerHTML = '&nbsp;';
      pnl.className = 'previewPanel';
      pnl.id = 'prwPanel';
      pnl.style.width = Math.ceil(WinW) + 'px';
      pnl.style.height = Math.ceil(WinH) + 'px';

      document.body.insertBefore(pnl, document.body.childNodes[0]);

      img = document.createElement("img");
      img.className = 'previewImage';
      img.id = 'prwImage';
      img.src = path;
      img.width = width;
      img.height = height;
      t = WinH / 2 - height / 2;
      img.style.top = Math.ceil(t)+'px';
      l = WinW / 2 - width / 2;
      img.style.left = Math.ceil(l)+'px';

      img.onclick = function () {document.body.removeChild(img); document.body.removeChild(document.getElementById("prwPanel"));};
      first = document.body.childNodes[0];
      document.body.insertBefore(img, first);
      fade('prwPanel',0.25,0.10);
      fade('prwImage',1,0.20);
  }

  //boxShoppingCart
 function ShoppingCart_check_value(obj, message) {
  oldvalue = obj.value;
  newvalue = parseInt(obj.value);
  if (oldvalue == newvalue) {
    obj.form.submit();
  } else {
    obj.value = oldvalue;
    alert(message);
  }
}

function showOverlayWithBox(path, width, height) {
    WindowWH = getWindowWH();
    WinW = WindowWH[0];
    WinH = WindowWH[1];
    pnl = document.createElement("div");
    pnl.innerHTML = '&nbsp;';
    pnl.className = 'translucent';
    pnl.id = 'prwPanel';
    document.body.insertBefore(pnl, document.body.childNodes[0]);

    box = document.createElement("iframe");

    box.style.width = width + 'px';
    box.style.height = height + 'px';

    var x,y;
    coords  = getScrollXY();
    x = coords[0];
    y = coords[1];

    t = WinH / 2 - height / 2;
    box.style.top = Math.ceil(t)+'px';
    l = WinW / 2 - width / 2;
    box.style.left = Math.ceil(l)+'px';

    box.className = 'containerIframe';
    box.id = 'prwImage';
    box.src = path;

    box.onclick = function () {
      document.body.removeChild(img);
      document.body.removeChild(document.getElementById("prwPanel"));
      window.onscroll = null;
    };
    first = document.body.childNodes[0];
    document.body.insertBefore(box, first);

}

function hideOverlayWithBox() {
  elem = window.parent.document.getElementById('prwImage');
  div_grey = window.parent.document.getElementById('prwPanel');

  if(elem && div_grey) {
    div_grey.style.display = 'none';
    elem.style.display = 'none'
  } else {
    alert('not elem');
  }
}


/*need to solve bug with Enter pressing*/
var enterPressed = false;

/*Decreases value of any field*/
function decreaseValue(object_id) {
  if (enterPressed) {
    enterPressed = false;
    return false;
  }
  object = $(object_id);

  if ( object != undefined)
    if (object.value > 1) {
      object.value--;
      if (undefined != object.onchange) {
        object.onchange();
      }
    }

  return false;
}

/*Increases value of any field*/
function increaseValue(object_id) {
  if (enterPressed) {
    enterPressed = false;
    return false;
  }
  object = $(object_id);

  if ( object != undefined)
    if (object.value <= 2147483647) {
      object.value++;
      if (undefined != object.onchange) {
        object.onchange();
      }
    }

  return false;
}

/*Function that gets source of array or any object*/
toS = function(obj) {
  var con = obj.constructor;
  if(con == String) {
      return '"' + obj + '"';
  } else if(con == Number) {
      return obj;
  } else if(con == Array) {
      var res = '[';
      for(var i=0,len=obj.length;i<len;i++) {
          if(i == len-1)
              res += toS(obj[i]) + ']';
          else
              res += toS(obj[i]) + ', ';
      }
      return res;
  } else if(con == RegExp) {
      return obj;
  } else if(con == Object) {
      var res = '{';
      var i=0;
      for(var j in obj) {
          if(j != 'toS') {
              if(i == 0) {
                  res += j + ':' + toS(obj[j], 1);
              } else {
                  res += ', ' + j + ':' + toS(obj[j], 1);
              }
              i++;
          }
      }
      res += '}';
      if(arguments.length > 1) {
          return res;
      } else {
          return '(' + res + ')';
      }
  }
};

/*creates onload function*/
scriptOnloadFunc = function(scriptsArray, callback) {
  var scripts    = new Array();
  scripts = scriptsArray;
  var scriptsStr = toS(scripts);
  var callbackStr = 'function(){}';
  if (callback != undefined) {
    callbackStr = callback.toString();
  }
  return Function('attachScripts(' + scriptsStr +', ' + callbackStr + ')');
};

/*creates onreadystatechange function*/
scriptOnreadystatechangeFunc = function(scriptsArray, callback) {
  var scripts    = new Array();
  scripts = scriptsArray;
  var scriptsStr = toS(scripts);
  var callbackStr = 'function(){}';
  if (callback != undefined) {
    callbackStr = callback.toString();
  }
  return Function('if (this.readyState == \'complete\' || this.readyState == \'loaded\') {attachScripts(' + scriptsStr +', ' + callbackStr + ')}');
};

/*function to attach scripts. First argument is array of filenames, second is callback function (if needed) */
attachScripts = function(scriptsArray, callback) {
  var scripts = new Array();
  scripts = scriptsArray;
  var script = scripts.shift();
  var callbackFunc = null;
  if (callback != undefined) {
    callbackFunc = callback;
  }
  var html_doc = document.getElementsByTagName('head').item(0);
  var js = document.createElement('script');
  js.setAttribute('type', 'text/javascript');
  js.setAttribute('src', script);
  if (scripts.length > 0) {
    js.onload = scriptOnloadFunc(scripts, callbackFunc);
  } else if (callbackFunc != undefined) {
    var re  = /\r\n/g;
    var re1 = /\n/g;
    var re2 = /'/g;
    var callbackStr = (callbackFunc.toString()).replace(re, '');
    callbackStr = callbackStr.replace(re1, '');
    callbackStr = callbackStr.replace(re2, '\\\'');
    js.onload = Function('window.eval(\'(' + callbackStr + ')()\')');
  }
  html_doc.appendChild(js);
  if (scripts.length > 0) {
    js.onreadystatechange = scriptOnreadystatechangeFunc(scripts, callbackFunc);
  } else if (callbackFunc != undefined) {
    var re  = /\r\n/g;
    var re1 = /\n/g;
    var re2 = /'/g;
    var callbackStr = (callbackFunc.toString()).replace(re, '');
    callbackStr = callbackStr.replace(re1, '');
    callbackStr = callbackStr.replace(re2, '\\\'');
    js.onreadystatechange = Function('if (this.readyState == \'complete\' || this.readyState == \'loaded\') {window.eval(\'(' + callbackStr + ')()\')}');
  }
};

attachCSS = function(cssArray) {
  for (var i=0; i<cssArray.length; i++) {
    var html_doc = document.getElementsByTagName('head').item(0);
    var css = document.createElement('link');
    css.setAttribute('type', 'text/css');
    css.setAttribute('rel', 'stylesheet');
    css.setAttribute('href', cssArray[i]);
    html_doc.appendChild(css);
  }
}

Event.observe(window, 'load', function(event){
  window.DOMLoaded = true;
});


/** Used for saving request data at page change**/
if(!paging) {
  var paging = {
    submit:function(link){
      var forms = document.getElementsByClassName('paging-form');
      var form = forms[0];
      if (form) {
        form.action=link.href;
        form.submit();
        return false;
      } else {
        return true;
      }
    }
  }
}

