﻿
function generateDropdowns() {

// FIRST LETS RETRIEVE VALUES OF DROPDOWNS ALLREADY SELECTED
    // get values of selected options - if any
    var ValuesOfListSelections = new Array(NrsOfLists)
    for (i=0; i<NrsOfLists; i++) {                                              // For each list
      try {                                                                     // If html element exists
        ValuesOfListSelections[i] = document.getElementById("List"+i).value;    // Add selected value to array
      }
      catch(e) {                                                                // If element doesnt exist (eg = pageload)
        ValuesOfListSelections[i] = 0                                           // set value = 0
      }
    }


// THEN WE CLEAR THE CURRENT DROPDOWNS
    // Set vars for DOM elements
    var dContainer = document.getElementById("dropdownContainer");
    var oldLists = document.getElementById("dropdownLists");
    // Remove current dropdowns
    try {                                                      // If dropdowns exist
      dContainer.removeChild(oldLists);                        // then delete them
      }
      catch(ex) {                                              // If not
                                                               // Do nothing - error occured because this is first run after pageload, ie: no dropdowns exist yet
      }
    // Make new div
    newLists = document.createElement("div");                  // Make new empty div
    newLists.setAttribute("id", "dropdownLists");              // add id name
	newLists.setAttribute("class", "productDropdownLists");    // add class name (mozilla)
	newLists.setAttribute("className", "productDropdownLists");// add class name (IE)
	dContainer.appendChild(newLists);                          // add to outer div
    // Set var for easy access
    var dLists = document.getElementById("dropdownLists");



	// If layout = 1 then add descriptional header
	if (layout == 1) {
	  addText = document.createTextNode(select_description);          // make textnode
	  addDiv = document.createElement("div")					      // make div
	  addDiv.setAttribute("class", "productDropdownListsHeader");     // add class moz
	  addDiv.setAttribute("className", "productDropdownListsHeader"); // add class IE
	  addDiv.appendChild(addText)									  // add txt to div
	  dLists.appendChild(addDiv)                                      // and add it to page
	}
	// If layout = 2  then alter the top padding
	if (layout == 2) {
	  document.getElementById("dropdownContainer").style.marginTop = '5px';
	}


// NOW LETS FIND OUT WITCH OPTIONS SHOULD BE IN WITCH LISTS	AND PRINT OUT NEW DROPDOWNS
    // Find available options for each element ( = available combinations disregarding selection in the list itself)
    for (i=0; i<NrsOfLists; i++) {                              // For each listelement (to generate each dropdown)
      for (x=0; x<=NrsOfCombinations; x++) {                    // For each combination
        isAvailable = 1;                                        // assume combination is available
        arrCombinations[x][8] = 1;                              // and mark combination as available
        for (y=0; y<NrsOfLists; y++) {                          // now check each list value in the combination
		  
          if (y != i) {                                         // Only check if current element is NOT outer element (eg disregard selection of self)
            if (!(ValuesOfListSelections[y] == arrCombinations[x][NrsOfData+y] || ValuesOfListSelections[y] == 0) && isAvailable == 1) {	// If not (selected listvalue = current combination or list hasnt been selected) AND combinations hasnt been marked unavalable yet
              isAvailable = 0;                                  // then combination is not available
              arrCombinations[x][8] = 0;                        // and array is marked unavailable
            }
          }

        }
      }
      var counter = 0                                           // Set numbers of available elements in list = 0
      tmpElements = arrListElements[i].split("|")               // split listelements into array
      for (x=0; x<tmpElements.length; x++) {                    // for each listelement
        isAvailable = 0                                         // assume element isnt available
        for (y=0; y<=NrsOfCombinations; y++) {                  // run through all combinations
          if (arrCombinations[y][i+NrsOfData] == tmpElements[x] && arrCombinations[y][8] == 1) { 	// if combination = current listelement AND combination is active
            isAvailable = 1                                     // Mark element as available
          }
        }

	// PART	OF GENERATING THE NEW DROPDOWNS

        if (x == 0) {                                                         // If first element on list then

        	var sUa = navigator.userAgent.toLowerCase();                     // Check witch browser is used (IE not able to do document.createElement("select"))
        	if (sUa.indexOf("msie") > -1 && sUa.indexOf("opera") < 0 && false) {          // If browser is IE
        		newElement = document.createElement('<select name="List' + i + '" id="List' + i + '">'); // Create the select element for IE
        	} else {                                                         // And if browser is not IE
        		newElement = document.createElement("select")                  // Make the selectbox for not IE browsere
        		newElement.setAttribute("name", "List" + i);                   // and add the element name
        		newElement.setAttribute("id", "List" + i);                     // and add element ID
        	}
        	newElement.onchange = function() { generateDropdowns(); };            // Set onchange handler

        	newOption = document.createElement("option");                     // Now create an option (default not selected option)
        	newOption.setAttribute('value', '0');                             // Assign a 0 value
        	if (layout == 1) {
        		newOption.appendChild(document.createTextNode(choose + ' ' + arrLists[i])); // and add a text for the user
        	} else {
        		newOption.appendChild(document.createTextNode(default_select_txt)); // and add a text for the user
        	}
        	newElement.appendChild(newOption);                                // then append the option to the select element		  

        	newOption = document.createElement("option");                     // Now create an empty option (for layout purpose)
        	newOption.setAttribute('value', '0');                             // set value = 0
        	newElement.appendChild(newOption);                                // and append the option to the select element		  
        }
        if (isAvailable == 1) {                                             // If element is available then
          newOption = document.createElement("option");                     // Create an option
          newOption.setAttribute('value',tmpElements[x]);                   // Assign a value and
          newOption.appendChild(document.createTextNode(tmpElements[x]));   // a text for the user
          newElement.appendChild(newOption);                                // and append the option to the select element		  

          counter = counter+1                                               // Add 1 to counter (eg option has been added)
          if (tmpElements[x] == ValuesOfListSelections[i]) {                // if curent elements is the selected option
            newElement.selectedIndex = counter+1                            // then set option as selected (add 1 because off the empty option value)
          }
        }
		
        if (x==tmpElements.length-1) {                                      // If last element on list
          var layoutDiv = document.createElement("div")                     // Create div for layout
          if (layout == 2) {                                                // if layout = type 2
			  
			  strikeDiv = document.createElement("div")
              strikeDiv.setAttribute('class','productBGstrike')             // assign classname for css (mozilla)
              strikeDiv.setAttribute('className','productBGstrike')         // assign classname for css (IE)
              layoutDiv.appendChild(strikeDiv)
              
			  labelSpan = document.createElement("span")
			  labelSpan.setAttribute('class','productLabel')                // assign classname for css (mozilla)
              labelSpan.setAttribute('className','productLabel')            // assign classname for css (IE)
              txtLabel = document.createTextNode(arrLists[i])               // Generate dropdownlabel
              labelSpan.appendChild(txtLabel)
			  layoutDiv.appendChild(labelSpan)
          }

          layoutDiv.appendChild(newElement);                                // Assign the dropdown to the div
          dLists.appendChild(layoutDiv);                                    // and then append the layout div to the div area
        }
		
     }

    }

	updateVariantInfo()
  }



function updateVariantInfo() {

			  minSPrice = ''
			  maxSPrice = ''
	
	
// FIRST LETS RETRIEVE VALUES OF DROPDOWNS ALLREADY SELECTED
    // get values of selected options - if any
    var ValuesOfListSelections = new Array(NrsOfLists)
    for (i=0; i<NrsOfLists; i++) {                                              // For each list
      try {                                                                     // If html element exists
        ValuesOfListSelections[i] = document.getElementById("List"+i).value;    // Add selected value to array
      }
      catch(e) {                                                                // If element doesnt exist (eg = pageload)
        ValuesOfListSelections[i] = 0                                           // set value = 0
      }
	}

// NOW LETS FIND OUT WITCH VARIANTS IS STILL AVAILABLE
    for (i=0; i<NrsOfLists; i++) {                              // For each listelement (to generate each dropdown)
	
      for (x=0; x<=NrsOfCombinations; x++) {                    // For each combination
        isAvailable = 1;                                        // assume combination is available
        arrCombinations[x][8] = 1;                              // and mark combination as available
        for (y=0; y<NrsOfLists; y++) {                          // now check each list value in the combination
          if (!(ValuesOfListSelections[y] == arrCombinations[x][NrsOfData+y] || ValuesOfListSelections[y] == 0) && isAvailable == 1) {	// If not (selected listvalue = current combination or list hasnt been selected) AND combinations hasnt been marked unavalable yet
            isAvailable = 0;                                    // then combination is not available
            arrCombinations[x][8] = 0;                          // and array is marked unavailable
          }
        }
      }
	}


// COUNT AVAILABLE VARIANTS
	counter = 0;
	for (x = 0; x < NrsOfCombinations; x++) {                   // For each variant
		if (arrCombinations[x][8] == 1) {                     // if variant is available
			counter = counter + 1;                                  // increase counter
			lastFound = x; 										// Remember for easy access

			if (counter == 1) {									// if first available variant, set price
				minNPrice = arrCombinations[x][2];
				maxNPrice = arrCombinations[x][2];

				if (arrCombinations[x][3] != '') { 				// only set if != 0
					minSPrice = arrCombinations[x][3];
					maxSPrice = arrCombinations[x][3];
				}

			}
			else {

				if (arrCombinations[x][2] < minNPrice) { minNPrice = arrCombinations[x][2] } // find lowest/highest normal/sales-price
				if (arrCombinations[x][2] > maxNPrice) { maxNPrice = arrCombinations[x][2] }
				if (arrCombinations[x][3] != 0) {
					if (minSPrice == '' || arrCombinations[x][3] < minSPrice) { minSPrice = arrCombinations[x][3]; }
					if (maxSPrice == '' || arrCombinations[x][3] > maxSPrice) { maxSPrice = arrCombinations[x][3]; }
				}
			}
		}
	}


	// PRINT TEXT FOR USER


  
      var iContainer = document.getElementById("infoContainer");  // Make reference for outer div
      var iContent = document.getElementById("infoContent");      // Make reference for inner div
      iContainer.removeChild(iContent);                           // Remove inner div - making space for updated content
	  
	  var dInfo = document.createElement("div");                  // Create new inner div
	  dInfo.setAttribute('id','infoContent')                      // and give it ID
	  

      arrLabels = labels.split(",")                               // make array of txt labels
	  
      var oTable = document.createElement("TABLE");               // Create table
      var oTBody = document.createElement("TBODY");               // Create body of table
      oTable.appendChild(oTBody);                                 // append body to the table
      oTable.setAttribute('class','VariantInfo')                  // and set class for styling (moz)
	  oTable.setAttribute('classname','VariantInfo')                  // and set class for styling (ie)

	  for (i=0; i<arrLabels.length; i++) {                        // Loop throug each txt label

         // Alter the order of the options (original in order: Variantnavn,Varenr,Pris,Tilbud,Billede,Lager )
		 if (i==0) { arrItem = 2 }
		 if (i==1) { arrItem = 3 }
		 if (i==2) { arrItem = 0 }
		 if (i==3) { arrItem = 1 }
		 if (i==4) { arrItem = 4 }
		 if (i==5) { arrItem = 5 }

		if (!(															// Do not print if
/*		  (                                                          
		      (counter == 1) &&                                     	// (final variant has been found (if more than one variant -> all labes will be printed) 
		      (															// AND
		        (arrItem ==4 && arrCombinations[lastFound][4] == 'False' //item is image and variant has no image)
				)
		      ) 
		  ) 
		  ||															// OR if (Do not print)
*/		  (arrItem == 5 && show_stock == 0)                            //  item is stock, and stock is set no to be shown (in backend) no matter if final variant has been found or not
		  ||															// OR if 
		  (arrItem == 2 || arrItem == 3)								// Item is price/salesprice
/*		  ||															// OR if 
		  (arrItem == 3 && 																				// item is sales price
		    (																							// AND
			  ((minNPrice != maxNPrice || minSPrice != maxSPrice || maxSPrice == '') && counter != 1) || // (normal and/or salesprices are different
			  (counter == 1 && maxSPrice == '')															// OR finalvariant has been found and item is not on sale)
			 )
		   ) // item is salesprice and (different normal and/or salesprices or not on sale)
*/		)) {
						oRow = document.createElement("TR");                       // Create a new row
            oTBody.appendChild(oRow);	                              // and append it to the table
						oCell = document.createElement("TD");                      // Create a new cell
						oCell.setAttribute('class','productVariantLeft')          // assign classname for css (mozilla)
						oCell.setAttribute('className','productVariantLeft')      // assign classname for css (IE)
            oCell.innerHTML = arrLabels[arrItem]+':';                 // and insert txtlabel text
            oRow.appendChild(oCell);                                  // then append the cell to the table
            oCell = document.createElement("TD");                      // Create 2nd cell 

//            if (arrItem==2 && ((arrCombinations[lastFound][3] != 0 && counter == 1) || (minNPrice == maxNPrice && minSPrice == maxSPrice && minSPrice != ''))) {   // If item is price and sales price <> 0 (eg is on sale)
//               addClass = 'Strike'                                     // then add 'strike' to classname
//            } else {
//               addClass = ''
//            }

            oCell.setAttribute('class','productVariantRight')       // assign classname for css (mozilla)
            oCell.setAttribute('className','productVariantRight')   // assign classname for css (IE)

            if (arrItem == 2 || arrItem == 3 || counter == 1) {                           // If item is price OR final variant has been found

            	if (counter == 1) {                                         // If final variant is found

                aC_value = arrCombinations[lastFound][arrItem]            // Retrieve value of item

                if (arrItem == 0 && (aC_value == '' || aC_value == 'N/A')) {  // If item is variantname and value is emprt or N/A (then show selcted variants as variantname)

				  VOLS = ''
				  for (ii=0; ii<ValuesOfListSelections.length; ii++) {
					if (ValuesOfListSelections[ii] != '' && ValuesOfListSelections[ii] != '0') {
				      VOLS = VOLS + ValuesOfListSelections[ii] + ', '            // Build string of selected variants
					}
				  }
				  aC_value = VOLS.substr(0,VOLS.length-2)                     // Remove trailing ', '
				}

        if (arrItem == 4) {                                       // If current item is image
				  if (aC_value != "") {                               // and variantimage is available, then set link
				  	aC_value = '<a href="/files/products/' + productId + '/v/' + aC_value + '" rel="lightbox[variantimages]" class="productVariantsImageLink productVariantsTableText" title="' + arrCombinations[lastFound][0] + '">' + click_label + '</a>'
				  }
				  else { aC_value =  js_no }
				}
        if (arrItem==5) {                                         // If current item is stock
          if ((arrCombinations[lastFound][5] - arrCombinations[lastFound][6]) > 0) { // and not current out because last items is in shoppingbasket
            aC_value = js_yes
          } else {
            aC_value = js_no
          }
        }

			  }
      }
			else {                                                    // else
			  aC_value = '---';                                         // show empty value
			}

            oCell.innerHTML = aC_value;                               // insert value for user
            oRow.appendChild(oCell);                                  // and append to the table


		}
		dInfo.appendChild(oTable)                                     // append the table to the inner div
	  iContainer.appendChild(dInfo);                                  // and append the innerdiv to the outer
	  
	  }

	  // update price
	  var priceContainer = document.getElementById("priceContainer");   // Make reference for outer div
      var priceContent = document.getElementById("priceContent");       // Make reference for inner div
	  priceContainer.removeChild(priceContent);
      var newDiv = document.createElement("div");                       // Create new inner div
	  newDiv.setAttribute('id','priceContent')                          // and give it ID
	  priceContainer.appendChild(newDiv)

	  var fromPrice
	  var normalPrice
	  var salesPrice
	  if (counter == 1) {												// Find price to show
		  if (minSPrice != '') {
			 salesPrice = minSPrice
		  }
		 normalPrice = minNPrice
	  } else {
		  if (minSPrice == '') {			// if sales price dosnt exist
			if (minNPrice != maxNPrice) {		// if more than one possible price
				fromPrice = minNPrice			// show from price
			} else {							// if onlu same prices
				normalPrice = minNPrice			// show final price
			}
		  } 
		  else {							// if sales prices exists
		  
		    fromPrice = minNPrice
			if (minSPrice < minNPrice) {
				fromPrice = minSPrice
			}
		  }
	  }

	  var priceContent = document.getElementById("priceContent");
	  var newSpan = document.createElement("span")
	  newSpan.setAttribute('id','infoContentHighlight')
	  
	  if (fromPrice) {						// If from price exist
		 txtLabel = document.createTextNode(price_from + ' ' + price_label+' ')
		 txtPrice = document.createTextNode(format_price_delimiters(fromPrice.toFixed(2)))
		 newSpan.appendChild(txtLabel)
		 priceContent.appendChild(newSpan)
		 priceContent.appendChild(txtPrice)

	  } else {								// else show final price
		 txtLabel = document.createTextNode(price_label+' ')
		 newSpan.appendChild(txtLabel)
		 priceContent.appendChild(newSpan)
		 if (salesPrice) {
		 	txtPrice = document.createTextNode(format_price_delimiters(salesPrice.toFixed(2)))
		 	priceContent.appendChild(txtPrice)
		 	newDiv = document.createElement("div")
		 	newDiv.setAttribute('id', 'productPriceNormal')
		 	txtNormal = document.createTextNode(price_before + ' ' + format_price_delimiters(normalPrice.toFixed(2)))
		 	newDiv.appendChild(txtNormal)
		 	priceContent.appendChild(newDiv)
		 }
		 else if (normalPrice) {
		 	txtPrice = document.createTextNode(format_price_delimiters(normalPrice.toFixed(2)))
		 	priceContent.appendChild(txtPrice)
		 } else {
			priceContent.innerHTML = "";
		 }
	  }

      // Update the buy button
	  var bbContainer = document.getElementById("buyButtonContainer");   // Make reference for outer div
      var bbContent = document.getElementById("buyButton");              // Make reference for inner div

      if (bbContent) { bbContainer.removeChild(bbContent); }           // Remove inner div - making space for updated content

      var newDiv = document.createElement("div");                        // Create new inner div
	  newDiv.setAttribute('id','buyButton')                              // and give it ID
	  if (normalPrice || salesPrice) {
	  	bbContainer.appendChild(newDiv);
	  	var dLink = document.getElementById("buyButton");
	  }
	  
	  if (counter == 1 && (order_items_not_in_stock==1 || arrCombinations[lastFound][5] > 0)) { // if final variant has been found

         // Remove two divs (if existing) from DOM due to bug in lightbox, not removing them when lightbox is re-initialized
         try {                                                        // get rid of errors
           var lb_overlay = document.getElementById("overlay")        // reference to existing lightbox overlay div
           var lb_lightbox = document.getElementById("lightbox")      // reference to existing lightbox lightbox div
           var lb_parent = lb_overlay.parentNode;                     // reference to parent node of overlay & lightbox
           lb_parent.removeChild(lb_overlay);                         // remove the overlay div
           lb_parent.removeChild(lb_lightbox);                        // remove the lightboxdiv
           }
           catch(ex) {}                                               // Needed for catch - but do nothing even if error is found (eg lightbox not initialized prior to this)

         setTimeout("initLightbox()", 500);	                          // initialize lightbox with delay (due to IE error) 
		 
		 url = '/default.asp?siteId=' + siteId + '&module=shopping_update_basket&shoppingMode=add&shoppingQuantity=1&shoppingPageId=' + pageId + '&shoppingProductId=' + productId + '&shoppingVariantId=' + arrCombinations[lastFound][7]
		 newOnclick = new Function("return updateBasket("+ siteId +","+ vatFactor +",'add',1,"+ pageId +","+ productId +","+ arrCombinations[lastFound][7] +");");
		 src = '/sys/images/' + site + '/button_buy_off.jpg'
      }
      else {
		 if (counter == 1 && order_items_not_in_stock == 0 && arrCombinations[lastFound][5] <= 0) {
		   url = 'javascript:alert(\'' + not_buyable + '\')'
		 } else {
   		   url = 'javascript:alert(\'' + make_choices + '\')'
		 }
         newOnclick = null;
         src = '/sys/images/' + site + '/button_buy_disabled.jpg'
	  }
      aTag = document.createElement('A');
      aTag.setAttribute('href', url)
      if (newOnclick != null) { aTag.onclick = newOnclick; }
      img = document.createElement('IMG');
      img.setAttribute('src', src)
      img.setAttribute('border', 0)
	  if (src == '/sys/images/' + site + '/button_buy_off.jpg') {
		img.onmouseover = Function("this.src=\'/sys/images/' + site + '/button_buy_on.jpg\'");
		img.onmouseout = Function("this.src=\'/sys/images/' + site + '/button_buy_off.jpg\'");		
	  }
	  img.setAttribute('onFocus', 'this.blur()')
	  aTag.appendChild(img);
	  if (dLink) { dLink.appendChild(aTag); }

}

function format_price_delimiters(nStr) {
  inD = '.'    // input delimiter (199,95)
  outD = ','   // output delimiter (199,95) 
  sep = '.'    // tusindetals seperator (1.000)
	
	nStr += '';
	var dpos = nStr.indexOf(inD);
	var nStrEnd = '';
	if (dpos != -1) {
		nStrEnd = outD + nStr.substring(dpos + 1, nStr.length);
		nStr = nStr.substring(0, dpos);
	}
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(nStr)) {
		nStr = nStr.replace(rgx, '$1' + sep + '$2');
	}
	return nStr + nStrEnd;
}


