var usAgent = 'mozilla';
var usAg = navigator.userAgent.toLowerCase();
if (usAg.indexOf("opera") != -1) {
  usAgent = 'opera';
} else if (usAg.indexOf("msie") != -1) {
  usAgent = 'msie';
}

function objListener(obj, eventName, func){
  if (usAgent=='msie') {
    obj.attachEvent("on"+eventName, func);
  } else {
    try {
      obj.addEventListener(eventName, func, false);
    } catch(e) {
      alert("Error: "+e+", event="+eventName);
    }
  } 
}


function applyFunc(object, methodName){
  return function(){
    object[methodName].apply(object, arguments);
  }
}


function ZoomTool(nameImgDiv, nameImg, closeImgId, zoomlinkId, aPrefix){
  for (var i in aPrefix) {
    this[aPrefix[i]+'ImgDiv'] = document.getElementById(aPrefix[i]+'_'+nameImgDiv);
    this[aPrefix[i]+'Img'] = document.getElementById(aPrefix[i]+'_'+nameImg);
  }
  this.zoomlinkId = document.getElementById(zoomlinkId);
  this.closeImgId = document.getElementById(closeImgId);
}


ZoomTool.prototype = {
  init : function() {
    if (!this.dynamicImg.complete || !this.smImg.complete) {
      setTimeout(applyFunc(this, "init"), 100);
      return
    }
    //set flags
    this.isShowBigImg = false;
   // set start data
    this.posX = this.posY = 0;
    this.mouseDiv = 0;
    this.mouseDivSizeX = this.mouseDivSizeY = 20;
    
   // set start coord
    this.dynamicImgSizeX = this.dynamicImg.width;
    this.dynamicImgSizeY = this.dynamicImg.height;
    this.smImgSizeX = this.smImg.width;
    this.smImgSizeY = this.smImg.height;
    this.smImgDiv.style.width = this.smImg.width+"px";
    this.smImgDiv.style.height = this.smImg.height+"px";
    this.dynamicImgSrc = this.dynamicImg.src;
    this.dynamicImgId = this.dynamicImg.id;
    this.dynamicImgDiv.style.top = '-11px';
    if (typeof(dynamic_div_offset) != 'undefined' && dynamic_div_offset != 0) {
      this.dynamicImgDiv.style.left = (dynamic_div_offset - parseInt(this.dynamicImgDiv.style.width))+'px';
    } else {
      this.dynamicImgDiv.style.left = '-'+(95 + parseInt(this.dynamicImgDiv.style.width))+'px';
    }
    this.dynamicImgDivStyleLeft = this.dynamicImgDiv.style.left; 
    
    this.prepareElem();
      objListener(this.smImgDiv, "mousemove", applyFunc(this, "mouseEvtMove")); 
      objListener(window.document, "mousemove", applyFunc(this, "checkMousePos"));
      objListener(this.smImgDiv, "click", applyFunc(this, "showBigImg")); 
      objListener(this.zoomlinkId, "click", applyFunc(this, "showBigImg"));
    this.anableView = (parseInt(this.dynamicImgDiv.style.width) < this.dynamicImgSizeX 
      ||  parseInt(this.dynamicImgDiv.style.height) < this.dynamicImgSizeY) ? true : false;
  },
  
  prepareElem : function() {
    // creates small div which follows mouse
    this.mouseDiv = document.createElement("DIV");
    this.mouseDiv.style.visibility = 'hidden';
    this.mouseDiv.style.position = 'absolute';
    this.mouseDiv.style.border = '1px solid silver';
    this.mouseDiv.style.background = 'white';
    if (usAgent == 'msie') {
      this.mouseDiv.style["filter"] = "alpha(Opacity=50)";
    } else {
      this.mouseDiv.style["opacity"] = 0.5;
    }
    this.mouseDiv.style.zIndex = 100;
    this.smImgDiv.appendChild(this.mouseDiv);
    // prepare coordinate
    this.mouseDivSizeX = (parseInt(this.dynamicImgDiv.style.width) / (this.dynamicImgSizeX / this.smImgSizeX));// * 0.8;
    this.mouseDivSizeY = (parseInt(this.dynamicImgDiv.style.height) / (this.dynamicImgSizeY / this.smImgSizeY));// * 0.8;
    this.mouseDiv.style.width = (Math.round(( this.mouseDivSizeX > this.smImgSizeX) ? this.smImgSizeX : this.mouseDivSizeX))+'px';
    this.mouseDiv.style.height = (Math.round((this.mouseDivSizeY > this.smImgSizeY) ? this.smImgSizeY : this.mouseDivSizeY))+'px';  
  
    // prepare big Image's elements
    while (this.dynamicImgDiv.firstChild) {
      this.dynamicImgDiv.removeChild(this.dynamicImgDiv.firstChild);
    }
    
    var tmpDiv = document.createElement("DIV");
    tmpDiv.style.overflow = "hidden";
    this.dynamicImgDiv.appendChild(tmpDiv);
    this.dynamicImg = document.createElement("IMG");
    this.dynamicImg.style.position = 'relative';
    this.dynamicImg.style.borderWidth = '0px';
    this.dynamicImg.src = this.dynamicImgSrc;
    this.dynamicImg.id = this.dynamicImgId;
    this.dynamicImg.style.padding = '0px';
    this.dynamicImgDiv.style.visibility = "hidden";
    tmpDiv.appendChild(this.dynamicImg);
  },

  mouseEvtMove : function(e) {
    if(this.anableView && !this.isShowBigImg && zoomObj.bigImgDiv.style.display != 'block'){
      if (usAgent == 'msie' && this.smImgDiv.getBoundingClientRect) {
        var smImgR = this.smImgDiv.getBoundingClientRect();  
        var docScroll = this._getWinParam('scroll');
      }
      var smDivOffsetLeft = ((usAgent == 'msie') ? (smImgR['left'] + docScroll.x) : this.smImgDiv.offsetLeft)
      var smDivOffsetTop = ((usAgent == 'msie') ? (smImgR['top'] + docScroll.y) : this.smImgDiv.offsetTop);
      this.posX = e.clientX - smDivOffsetLeft;
      this.posY = e.clientY - smDivOffsetTop + document.documentElement.scrollTop;
      if ((this.posX + this.mouseDivSizeX/2) >= this.smImgSizeX) {
        this.posX = this.smImgSizeX - this.mouseDivSizeX/2;
      } else if ((this.posX - this.mouseDivSizeX/2) <= 0) {
        this.posX = this.mouseDivSizeX/2;
      }
      if ((this.posY + this.mouseDivSizeY/2) >= this.smImgSizeY) {
        this.posY = this.smImgSizeY - this.mouseDivSizeY/2;
      } else if ((this.posY - this.mouseDivSizeY/2) <= 0) {
        this.posY = this.mouseDivSizeY/2;
      }
      
      // show dynamic divs
      var mouseLeft = ((smDivOffsetLeft + this.posX - this.mouseDivSizeX/2) > smDivOffsetLeft) ? this.posX - this.mouseDivSizeX/2 : 1;
      var mouseTop =  ((smDivOffsetTop + this.posY - this.mouseDivSizeY/2) > smDivOffsetTop) ? this.posY - this.mouseDivSizeY/2 : 1;

      this.mouseDiv.style.left = mouseLeft+'px';
      this.mouseDiv.style.top = mouseTop+'px';
      this.mouseDiv.style.visibility = "visible";
      
      this.dynamicImg.style.left = (-(mouseLeft * (this.dynamicImgSizeX / this.smImgSizeX)))+'px';
      this.dynamicImg.style.top = (-(mouseTop * (this.dynamicImgSizeY / this.smImgSizeY)))+'px';
      this.dynamicImgDiv.style.left = this.dynamicImgDivStyleLeft;
      this.dynamicImgDiv.style.visibility = 'visible';
    }
  },
  
  hideDynamicDivs : function(e) {
    /* this.dynamicImgDiv.style.left = '-10000px'; */
    this.dynamicImgDiv.style.visibility = 'hidden';
    if (usAgent == 'msie') {
      this.smImgDiv.style.zIndex = 0;
    }
    if (this.mouseDiv) {
      this.mouseDiv.style.visibility = "hidden";
    }
  },
  
  showBigImg : function(e){
    if (usAgent == 'msie') {
      window.event.cancelBubble = true;
    } else {
      e.cancelBubble=true;
      e.preventDefault();
      e.stopPropagation();
    }
    this._showBigImg();
  },
  
  _showBigImg : function(){
    this.isShowBigImg = true;
    this.hideDynamicDivs();
    this.bigImg.src = this.dynamicImgSrc;

    //var winParam = this._getWinParam('size');
    x_coord = windowWidth();
    y_coord = windowHeight();

    this.bigImgDiv.style.left = (x_coord > this.dynamicImgSizeX) ? Math.round((x_coord - this.dynamicImgSizeX) / 2) + 'px' : '20px';
    this.bigImgDiv.style.top = (y_coord > this.dynamicImgSizeY) ? Math.round((y_coord - this.dynamicImgSizeY) / 2) + 'px' : '0px';
    this.bigImgDiv.style.display = 'block';
    this.bigImgDiv.style.zIndex = 200;

    objListener(this.closeImgId, "click", applyFunc(this, "hideBigImg")); 
    objListener(this.bigImg, "click", applyFunc(this, "hideBigImg")); 
  },

  hideBigImg  : function(e){
    this.bigImgDiv.style.display = 'none';
    this.isShowBigImg = false;
  },
  
  checkMousePos : function(e) {
    var docScroll = this._getWinParam("scroll");
    var x = e.clientX + docScroll.x;
    var y = e.clientY + docScroll.y;
    if (usAgent == 'msie' && this.smImg.getBoundingClientRect) {
      var smImgR = this.smImg.getBoundingClientRect();  
    }
    var smallX = ((usAgent == 'msie') ? (smImgR['left'] + docScroll.x) : this.smImgDiv.offsetLeft);
    var smallY = ((usAgent == 'msie') ? (smImgR['top'] + docScroll.y) : this.smImgDiv.offsetTop);
    
    if (x > parseInt(smallX+this.smImgSizeX) || x < parseInt(smallX) 
      || y > parseInt(smallY+this.smImgSizeY) || y<parseInt(smallY)) {
      this.hideDynamicDivs();
      return false;
    }
    return true;  
  },
  
  add_param : function(){
  },
  
  _getWinParam : function(paramType) {
    var coordX = 0;
    var coordY = 0;
    var aParam = {
      'scroll':{'x':'scrollLeft','y':'scrollTop'},
      'size':{'x':'clientWidth','y':'clientHeight'}
    };

    if (document.body && ( document.body[aParam[paramType]['x']] || document.body[aParam[paramType]['y']] )) {
      coordX = document.body[aParam[paramType]['x']];
      coordY = document.body[aParam[paramType]['y']];
    } else if (document.documentElement && (document.documentElement[aParam[paramType]['x']] || document.documentElement[aParam[paramType]['y']])) {
      coordX = document.documentElement[aParam[paramType]['x']];
      coordY = document.documentElement[aParam[paramType]['y']];
    }
    return  {
      'x' : coordX,
      'y' : coordY
    } 
  }
}; 

var zoomObj;
function createZoomObj(){
  zoomObj = new ZoomTool('zoom_div', 'zoom_img', 'close_big_div', 'sm_zoom_link', {'0':'sm','1':'dynamic','2':'big'});
  zoomObj.init();
}

if (typeof(zoomObj) == "undefined") {
 objListener(window, "load", createZoomObj);
 objListener(window, "load", check_related_img);
 objListener(window, "load", change_model);
}

function swap_img(sm_img_src, big_img_src, big_width, big_height) {
  var urlSpl = sm_img_src.split("&");
  for (var i in urlSpl) {
    var val = urlSpl[i];
    var valSpl = val.split("=");
    if (valSpl[0] == "w"){ 
      var smW = valSpl[1];
    }
    if (valSpl[0] == "h") {
      var smH = valSpl[1];
    }
  }
  if (big_width >= big_height){
    smH = Math.round(big_height * smW / big_width);
  }else{
    smW = Math.round(big_width * smH / big_height);
  }
  if (typeof(zoomObj) == "undefined") {
    createZoomObj();
  }
  zoomObj.smImg.src = sm_img_src;  
  zoomObj.dynamicImg.src = big_img_src;
  zoomObj.smImg.style.width = smW+'px';
  zoomObj.smImg.style.height = smH+'px';
  zoomObj.dynamicImg.height = big_height;
  zoomObj.dynamicImg.width = big_width;
  zoomObj.init();
  zoomObj.hideDynamicDivs();
  if (zoomObj.bigImgDiv.style.display == 'block') {
    zoomObj._showBigImg();
  }
}


var iCurrMainPrice = 0;
var iCurrMmiPrice = 0;
var iCurrExpiredPrice = 0;
function check_related_img() {
  //zoom_frame_at_center();

/*   var f = document.cart_quantity;
  if (!f) {
    return;
  } */
  
 // var options_cnt = 0;
 // var sel_attrs = {};

/*   for (var i = 0; i < f.elements.length; i++) {
    if (f.elements[i].name.search(/^model_id\[\d+\]$/) >= 0) {
      options_cnt++;
      var option_id = f.elements[i].name.substr(9, f.elements[i].name.length - 10); // which select 
      sel_attrs[option_id] = f.elements[i].value;
    } else if (f.elements[i].name.search(/^id\[\d+\]$/) >= 0) {
      options_cnt++;
      var option_id = f.elements[i].name.substr(3, f.elements[i].name.length-4); // which select 
      sel_attrs[option_id] = f.elements[i].options[f.elements[i].selectedIndex].value;
    }
  } */
  var bIsImg = false;
  var is_set_selection = false;
  var sel_attrs = get_sel_attrs();
  var matchData = {};
  for (var gallery_id in attr_related_images) {
    var attrs = attr_related_images[gallery_id]['attrs'];
    var attrs_match = 0;
    var attr_count = 0;
    for (var option_id in attrs) {
      if (sel_attrs[option_id] != undefined && attrs[option_id] == sel_attrs[option_id]) {
        attrs_match++;
      }
      attr_count++;
    }
    matchData[gallery_id] = {'attrs_match': attrs_match, 'attr_count': attr_count};
  }
  var maxCount = 0;
  var mostFavourable = 0;
  for (var gallery_id in matchData) {
    for (var val in matchData[gallery_id]) {
      bIsImg = true;
      if (val == "attrs_match" && maxCount < matchData[gallery_id][val]) {
        maxCount = matchData[gallery_id][val];
        mostFavourable = gallery_id;
      }
    }
  }
  if (mostFavourable != 0 && matchData[mostFavourable]['attrs_match'] == matchData[mostFavourable]['attr_count']) {
    set_selection(mostFavourable);
    is_set_selection = true;
  }
  
  if (bIsImg && typeof(zoomObj) == "undefined") {
    createZoomObj();
  }
  if (!is_set_selection) {
    get_new_price(sel_attrs);
  }
}
function get_new_price(sel_attrs) {
  var aOptionsData = option_price['data'];
  var sPriceType, iNewPrice, iOptionVal, iItemPrice, iCurrPrice, iExpiredPrice, iCurrExpPrice;
  for (var sDivName in option_price['prices']) {
    var priceInfo = option_price['prices'][sDivName];
    sPriceType = (priceInfo['percent'] == undefined) ? 'rest_amount' : 'main';
    iCurrPrice = (sPriceType == 'main') ? iCurrMainPrice : iCurrMmiPrice;
    iNewPrice = new Number((sPriceType == 'main' && priceInfo['special_price'] != "") ? priceInfo['special_price']  : priceInfo['price']);
    if (0 == iCurrPrice) {
      iCurrPrice = iNewPrice;
    }
    if (sPriceType == 'main' && option_price['addition']['expired_price'] != '') {
      iCurrExpPrice = iCurrExpiredPrice;
      iExpiredPrice = option_price['addition']['expired_price'];
      if (0 == iCurrExpiredPrice) {
        iCurrExpPrice = option_price['addition']['expired_price'];
      }
    }
    for (var iOptionId in aOptionsData) {
      for (var iValueId in aOptionsData[iOptionId]) {
        for (var iCurrOptionId in sel_attrs) {
          if (iCurrOptionId == iOptionId && sel_attrs[iOptionId] == iValueId) {
            iOptionVal = aOptionsData[iOptionId][iValueId];
            iItemPrice = Math.round((parseFloat(iNewPrice) + parseFloat(iOptionVal)) * 100) / 100;
            iNewPrice = iItemPrice;
            if (iExpiredPrice != 0 && sPriceType == 'main') {
              iExpiredPrice = Math.round((parseFloat(iExpiredPrice) + parseFloat(iOptionVal)) * 100) / 100;
            }
          }
        }
      }
    }
    if (iNewPrice != iCurrPrice) {
      iNewPrice = iNewPrice.toFixed(2);
      //iNewPrice = (sPriceType == 'rest_amount') ? (calculate_rest_amount(iNewPrice, priceInfo['payments_mmi_amount'])).toFixed(2) : iNewPrice.toFixed(2);
      var oDiv = document.getElementById(sDivName);
      if (oDiv) {
        set_content(oDiv, sPriceType, iCurrPrice, iNewPrice, option_price['mls_rate'], (sPriceType == 'main' && priceInfo['special_price'] != ""), iCurrExpPrice,iExpiredPrice);
      }
      if (sPriceType == 'rest_amount') {
        iCurrMmiPrice = iNewPrice;
      } else {
        iCurrMainPrice = iNewPrice;
        if (iExpiredPrice != 0){ iCurrExpiredPrice = iExpiredPrice; }
      }
    }
  }
}

function calculate_rest_amount(iPrice, iPaymentsMmiAmount) {
  //alert(iPrice + ' - ' + iPaymentsMmiAmount);
  var iRestAmount = iPrice - iPaymentsMmiAmount;
  return (iRestAmount > 0) ? iRestAmount : 0;
}

function set_content(obj, sPriceType, iOldContent, iNewContent, iMlsRate, isSpecialPrice, iCurrExpirePrice, iExpirePrice) {
  var oCurrNode, oNewNode, oSubNode;
  
  if (sPriceType == 'rest_amount') {
    var iOldContent = calculate_rest_amount(iOldContent, option_price['prices']['rest_amount']['payments_mmi_amount']).toFixed(2);
    var iNewContent = calculate_rest_amount(iNewContent, option_price['prices']['rest_amount']['payments_mmi_amount']).toFixed(2);
  }

  var iMainOldContent = calculate_price(iOldContent);
  var iMainNewContent = calculate_price(iNewContent);

  //alert(sPriceType + '  old: ' +  iOldContent + ' new: ' + iNewContent + ' rate: ' + iMlsRate);
  //alert(sPriceType + '  old: ' +  iMainOldContent*iMlsRate + ' new: ' + iMainNewContent*iMlsRate + ' rate: ' + iMlsRate);
  //alert(sPriceType + ' : ' + iMainOldContent);

  if (obj.hasChildNodes()) {
    for (var i = 0; obj.childNodes.length >= i; i++) {
      oCurrNode = obj.childNodes[i];
      if ( typeof(oCurrNode) == 'object') { 
        if (oCurrNode.nodeName == "S"  && oCurrNode.firstChild.nodeValue != null && iExpirePrice != 0) {
          ////////////////
          //EXPIRE PRICE//
          ////////////////
          iCurrExpirePrice = calculate_price(iCurrExpirePrice);
          iExpirePrice = calculate_price(iExpirePrice);
          _set_content(oCurrNode, oCurrNode.firstChild, iCurrExpirePrice, iExpirePrice);
        }
        if (oCurrNode.nodeValue != null && match_values(oCurrNode.nodeValue, iMainOldContent)) {
          ////////////////////////
          //REST AMOUNT CURRENCY//
          ////////////////////////
          _set_content(obj, oCurrNode, iMainOldContent, iMainNewContent);
        } else if (oCurrNode.nodeName == "SPAN" ) {
          var iOldMiles = Math.round(iOldContent * iMlsRate);
          var iNewMiles = Math.round(iNewContent * iMlsRate);
          if (!isSpecialPrice && match_values(oCurrNode.firstChild.nodeValue, iOldMiles)) {
            _set_content(oCurrNode, oCurrNode.firstChild, iOldMiles, iNewMiles, true);
          } else if (isSpecialPrice) {
            if (obj.hasChildNodes()) {
              for (var y = 0; oCurrNode.childNodes.length >= y; y++) { 
                oSubNode = oCurrNode.childNodes[y];
                if (typeof(oSubNode) == 'object') {
                  if (oSubNode.nodeValue != null && match_values(oSubNode.nodeValue, iMainOldContent)) {
                    //////////////////////////
                    //SPECIAL PRICE CURRENCY//
                    //////////////////////////
                    _set_content(oCurrNode, oSubNode, iMainOldContent, iMainNewContent);
                  }
                  if (oSubNode.firstChild != null) {
                    if(oSubNode.nodeName == "SPAN" && match_values(oSubNode.firstChild.nodeValue, iOldMiles)) {
                     _set_content(oSubNode, oSubNode.firstChild, iOldMiles, iNewMiles, true);
                    }
                  }
                }
              }  
            }  
          }
        }
      }
    }
  }
}
function calculate_price(iPrice){
  var sFuncName = option_price['rounding_rule'];
  if (typeof(Math[sFuncName]) != "function") {
    sFuncName = 'round';
  }
  var price = Math[sFuncName](iPrice * option_price['curr_currency'] / option_price['precision']) * option_price['precision'];
  return price.toFixed((option_price['curr_currency'] == option_price['mls_rate'] ? 0 : 2));
}

function priceFormat(num, is_miles){
  if (typeof(is_miles) != 'undefined' && is_miles == true) {
    sep_th = option_price['thousands_point']['MLS'];
    sep_de = option_price['decimal_point']['MLS'];
  } else {
    sep_th = option_price['thousands_point']['curr_currency'];
    sep_de = option_price['decimal_point']['curr_currency'];
  }
  var intp0, intp1, l, n, i;
  intp0 = num.toString();
  intp1 = "";
  l = intp0.length;
  for (i = 0; i < l; i += 3) {
    n = l - i;
    intp1 = intp0.substring((n < 3 ? 0 : n - 3), n) + (intp0.substring(n, n+1) != '.' ? sep_th : '') + intp1;
  }
  result = (intp1.substring(intp1.length - 1, intp1.length) == sep_th) ? intp1.substring(0, intp1.length - 1) : intp1;
  if (sep_de != '' && result.substring(result.length - 3, result.length - 2) != sep_de) {
    result = result.substring(0, result.length - 3) + sep_de + result.substring(result.length - 2, result.length);
  }
  return result;
}

function _set_content(obj, oChild, iOldPrice, iNewPrice, is_miles){
  if (typeof(is_miles) == 'undefined') {
    is_miles = false;
  }
  //alert('old :' + priceFormat(iOldPrice, is_miles) + ' new: ' + priceFormat(iNewPrice, is_miles));
  oNewNode = document.createTextNode(oChild.nodeValue.replace(new RegExp(priceFormat(iOldPrice, is_miles), "g"), priceFormat(iNewPrice, is_miles)));
  obj.replaceChild(oNewNode, oChild);
}

/* 
NOT USED NOW
function _set_content_spend_get_miles(iOldContent,iNewContent,iMlsRate,iMainOldContent,iMainNewContent) {
  var oSpendGetMiles = document.getElementById(option_price["addition"][0]);
  if (oSpendGetMiles) {
    var price = Math.round(iOldContent * iMlsRate);
    var oldSpendGetM = ((oSpendGetMiles.firstChild.nodeValue.match(priceFormat(price))) ? priceFormat(price) : price);
    var newSpendGetM = priceFormat(Math.round(iNewContent * iMlsRate));
    var SGChildren = oSpendGetMiles.childNodes;
    for (var sg=0; sg < SGChildren.length; sg ++) {
      var SGChild = SGChildren[sg];
      if (SGChild.nodeValue!= null) {
        _set_content(oSpendGetMiles, SGChild, parseInt(((iMainOldContent) ? iMainOldContent : iOldContent), 10), parseInt(((iMainNewContent) ? iMainNewContent : iNewContent), 10));
        _set_content(oSpendGetMiles, oSpendGetMiles.firstChild, oldSpendGetM, newSpendGetM);
      }
    }
  }
} */

function set_selection(gallery_id) {
  var f = document.cart_quantity;
  var attrs = attr_related_images[gallery_id]['attrs'];
  var is_attr = false;
  for (var attr in attrs) {
    is_attr = true;
  }
  var select_model = document.getElementById('select_model');
  if (select_model != null) {
    for (var i = 0; i < select_model.options.length; i++) {
      if (select_model.options[i].value == gallery_id) {
        select_model.selectedIndex = i;
      }
    }
    change_model();
  }

  if (is_attr) {
    for (var option_id in attrs) {
      if (typeof(f['id[' + option_id + ']']) == "object") {
        var ctl = f['id[' + option_id + ']'];
        for (var i = 0; i < ctl.options.length; i++) {
          if (ctl.options[i].value == attrs[option_id]) {
            ctl.selectedIndex = i;
          }
        }
      } 
    }
  }
  var sel_attrs = get_sel_attrs();
  get_new_price(sel_attrs);
  swap_img(attr_related_images[gallery_id]['image'], attr_related_images[gallery_id]['big_image_src'], attr_related_images[gallery_id]['big_image_width'], attr_related_images[gallery_id]['big_image_height']);
}

function set_selection2(gallery_id) {
  var f = document.cart_quantity;
  var attrs = attr_related_images[gallery_id]['attrs'];
  var is_attr = false;
  for (var n in attrs){
    is_attr = true;
  }
  if (is_attr) {
    var sel_attrs = {};
    for (var option_id in attrs) {
      var ctl = f['id[' + option_id + ']'];
      for (var i = 0; i < ctl.options.length; i++) {
        if (ctl.options[i].value == attrs[option_id]) {
          sel_attrs[option_id] = ctl.options[i].value;
          ctl.selectedIndex = i;
        }
      }
    }

  }
 
}
function change_model() {
  var f = document.cart_quantity;
  oSel = document.getElementById('select_model');
  for (var i = 0; i < f.elements.length; i++) {
    if (f.elements[i].name.search(/^model_id\[\d+\]$/) >= 0) {
      f.elements[i].value = js_model[oSel.value]['attrs'][f.elements[i].name.substr(9, f.elements[i].name.length - 10)];
    }
  }
}
function get_sel_attrs() {
  var f = document.cart_quantity;
  if (!f) {
    alert('Form "cart_quantity" not found');
    return;
  }
  var options_cnt = 0;
  var sel_attrs = {};
  for (var i = 0; i < f.elements.length; i++) {
    if (f.elements[i].name.search(/^model_id\[\d+\]$/) >= 0) {
      options_cnt++;
      var option_id = f.elements[i].name.substr(9, f.elements[i].name.length - 10); // which select 
      sel_attrs[option_id] = f.elements[i].value;
    } else if (f.elements[i].name.search(/^id\[\d+\]$/) >= 0) {
      options_cnt++;
      var option_id = f.elements[i].name.substr(3, f.elements[i].name.length-4); // which select 
      sel_attrs[option_id] = f.elements[i].options[f.elements[i].selectedIndex].value;
    }
  }
  //sel_attrs['op_qnt'] = options_cnt;
  return sel_attrs;
}
function hash_dump(hash, last) {
  var s = '';
  if (last == undefined) {
    last = true;
  }
  for (i in hash) {
      if (last == false) {
        s += '   ';
      }
    s += ' ' + i + ' => ';
    if (hash[i] == "[object Object]") {
      s +=  "{\n";
      s += hash_dump(hash[i], false);
      s += "}\n";
    } else {
      s += '   ' + hash[i] + "\n";
    }
  }
  if (last == false) {
    return s;
  }
  if (last != false) {
    alert(s);
  }
}

function windowHeight() {
  var de = document.documentElement;
  return self.innerHeight || ( de && de.clientHeight ) || document.body.clientHeight;
}

function windowWidth() {
  var de = document.documentElement;
  return self.innerWidth || ( de && de.clientWidth ) || document.body.clientWidth;
}
function match_values(value_1, value_2) {
  pattern = new RegExp('[^0-9]', "g");
  value_1 = value_1.toString().replace(pattern, '');
  value_2 = value_2.toString().replace(pattern, '');
  //alert('match: ' + value_2 + ' = ' + value_1);
  return value_1.match(value_2);
}

function check_for_attrs() {
  aSelects = document.getElementsByTagName('select');
  for (i in aSelects) {
    obj = aSelects[i];
    if (typeof(obj.name) != 'undefined' && obj.name.substr(0, 3) == 'id[' && obj['value'] == '0') {
      alert(sAttrsError);
      return false;
    }
  }
  return true;
}