// JavaScript Document
/**** browser version filters ****/

var isIE = (navigator.appName == "Microsoft Internet Explorer");
var isIEWin = (isIE && navigator.userAgent.indexOf("Win") != -1);
var isIEMac = (isIE && navigator.userAgent.indexOf("Mac") != -1);

var itemWantInfo = "";
var itemOfferInfo = "";
var aliasInfo = "";

var numberOfWantItems = 0;
var numberOfOfferItems = 0;
var numberOfCashItems = 0;
var numberOfIPItems = 0;

function popUp(URL, width, height) {
	if (document.all) {
		var x = window.screeLeft;
		var y = window.screenTop;
		var w = window.document.body.offsetWidth;
		var h = window.document.body.offsetHeight;
 
	}else {
		var x = window.screenX;
		var y = window.screenY;
		var w = window.outerWidth;
		var h = window.outerHeight;
	}
	var cx = Math.round((screen.availWidth - width) / 2);
	var cy = Math.round((screen.availHeight - height) / 2);
 
	var win = window.open(URL,"Create","\"toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width="+ width + ",height="+ height + ",left=" + cx + ",top=" + cy + "\"");
	
}

function isaPosNum(s) {
	return (parseFloat(s) > 0)
}

function realNum(val)
{
 var ok = '0123456789';
 if (val.length == 0) { return false; }
 if(val.charAt(0) == '0') {return false; }
 for (var i = 0; i < val.length; i++)
 {
   var c = val.charAt(i);
   if (ok.indexOf(c) == -1)
    {
     return false;
    }
 }
 return true;
}

function addLink(form, href, itemName) {
if (document.getElementById) {
  	var input = document.createElement('A');

    if (document.all) { // what follows should work
                          // with NN6 but doesnt in M14
    	var inputString = "<a href='" + href + "'>";
    	
    	input = document.createElement(inputString);
		
		input.innerHTML = itemName;
		//fixed to avoid displaying <br/> tags    	
    	/*var inputText = document.createTextNode(itemName);
    	input.appendChild(inputText);*/

      }
      else if (document.getElementById) { // so here is the
                                          // NN6 workaround
        input.setAttribute('href', href);
		input.innerHTML = itemName;
		//fixed to avoid displaying <br/> tags
        /*var txtNode = document.createTextNode(itemName);
        input.appendChild(txtNode);*/

      }
    form.appendChild(input);
  }	
}

function addInputField (wantOffer, form, fieldType, fieldId, fieldName, fieldValue, itemId) {
  if (document.getElementById) {
  	var input = document.createElement('INPUT');

    if (document.all) { // what follows should work
                          // with NN6 but doesnt in M14
    	var inputString = "<INPUT id=\"" + fieldId + "\" type=\"" + fieldType + "\" name=\"" + fieldName + "\" value=\"" + fieldValue + "\"";
        if(fieldType ==  'checkbox') {
        	inputString += " checked=\"checked\" onclick=\"removeItemFromList('" + wantOffer + "'," + itemId + ");\"";
        }else if(fieldType ==  'text') {
        	inputString += " size=\"3\" onblur=\"validateQty('" + wantOffer + "'," + itemId + ");\"";
        }

        inputString += " />";
        input = document.createElement(inputString);

      }
      else if (document.getElementById) { // so here is the
                                          // NN6 workaround
        input.setAttribute('type', fieldType);
        input.setAttribute('name', fieldName);
        input.setAttribute('value', fieldValue);
        input.setAttribute('id', fieldId);
		if(fieldType == "checkbox") {
			var remove = "removeItemFromList('" + wantOffer + "'," + itemId + ");";
			input.setAttribute('checked', "checked");
			input.setAttribute('onclick', remove);
		}else if(fieldType == "text") {
        	var validateQty = "validateQty('" + wantOffer + "'," + itemId + ");";
        	input.setAttribute('onblur', validateQty);
        	input.setAttribute('size', "3");
        }

      }
    form.appendChild(input);
  }
}

function removeItemFromList(wantOffer, fieldId) {
  var field = document.getElementById("item" + wantOffer + fieldId + "Row");
  if (field) {
    field.parentNode.removeChild(field);
  }
  
  var listItem = document.getElementById("itemList" + fieldId);
  if(listItem) {
  	listItem.checked = false;
  }
  
  var tableBody = document.getElementById("item" + wantOffer + "TableBody");
  if(tableBody.rows.length > 1) {
  	reStyleTable(wantOffer);
  }
  
  if ('function' == typeof window.recalculateCash){
    recalculateCash(fieldId, wantOffer);
  } 
    
}

function reStyleTable(tableName) {
	var tableBody = document.getElementById("item" + tableName + "TableBody");
	var trColor = "0";
	for(var i = 1; i < tableBody.rows.length; i++) {
		tableBody.rows[i].className = "tr" + trColor;
	  	if(trColor == "0") {
	    	trColor = "1";
	    }else {
	    	trColor = "0";
	    }
			
	}
}

function reStyleFormTable(tableName, from) {
	var tableBody = document.getElementById(tableName);
	var trColor = "0";
	
	if (document.all && from > 0) { // what follows should work
                          // with NN6 and IE but doesnt in M14
        //this is because IE counts thead as a table row
        //and mozilla doesn't
    	from++;
    }
	
	for(var i = from; i < tableBody.rows.length; i++) {
		var rowId = tableBody.rows[i].id;
		var rowStyle = tableBody.rows[i].style.display;
		if(rowId != "text1" && rowId != "text2" && rowStyle != "none") {
			tableBody.rows[i].className = "tr" + trColor;
			if(trColor == "0") {
				trColor = "1";
			}else {
				trColor = "0";
			}
		}			
	}
}

function validateQty(wantOffer, itemId) {
	var qty = document.getElementById("item" + itemId + "Qty");
	if(qty) {
		var userQty = document.getElementById("item" + wantOffer + itemId + "Qty");

		if(userQty && !realNum(userQty.value)) {
        	alert("Please enter a valid quantity number.\nReseting to default value.");
        	userQty.value = 1;
        	}else if(userQty && parseInt(userQty.value) > parseInt(qty.value)) {
			alert("You can't select more than " + qty.value + " units of this item!");
			userQty.value = 1;
			
		}
	}
}

function addItem(wantOffer, itemId, itemName, quantity, quantityWanted, exchangeType, instantPurchase, parentCategory) {

    if (document.createElement && !isIEMac) {
    	var exists = document.getElementById("item" + wantOffer + itemId + "Row");
    	if(exists) {
    		removeItemFromList(wantOffer, itemId);
    		
    	}else {
	        // prepare references to document tree objects for later
	        var mytable = document.getElementById("item" + wantOffer + "Table");
	        var mytbody = document.getElementById("item" + wantOffer + "TableBody");
	        // generate fragment container for tbody assembly
	
	        var trElem, tdElem, txtNode;
	        trElem = document.createElement("tr");
	        trElem.id = "item" + wantOffer + itemId + "Row";
	
	        tdElem = document.createElement("td");
	        tdElem.className = "col0";
	        addInputField(wantOffer, tdElem, 'checkbox', itemId, itemId, itemId, itemId);
	
	        //tdElem.appendChild(txtNode);
	        trElem.appendChild(tdElem);
	
	        tdElem = document.createElement("td");
	        tdElem.className = "col1";
	        var itemLink = "/product/itemView/" + itemId + "&#63;close=true";
			var popUp = "javascript:popUp(\"" + itemLink + "\", 800, 600);"
	        
	        addLink(tdElem, popUp, itemName);
	        trElem.appendChild(tdElem);
	
	        tdElem = document.createElement("td");
	        tdElem.className = "col2";
	        txtNode = document.createTextNode(quantity);
	        tdElem.appendChild(txtNode);
	        trElem.appendChild(tdElem);
	
	        tdElem = document.createElement("td");
	        tdElem.className = "col3";
	        var itemQtyid = "item" + itemId + "Qty";
	        addInputField(wantOffer, tdElem, 'hidden', itemQtyid, itemQtyid, quantity, itemId);
			
	        var itemWantQtyId = "item" + wantOffer + itemId + "Qty";
	        addInputField(wantOffer, tdElem, 'text', itemWantQtyId, itemWantQtyId, quantityWanted, itemId);
			
			var itemExTypeId = "item" + itemId + "ExType";
	        addInputField(wantOffer, tdElem, 'hidden', itemExTypeId, itemExTypeId, exchangeType, itemId);
	        
	        var itemIPId = "item" + itemId + "IP";
	        addInputField(wantOffer, tdElem, 'hidden', itemIPId, itemIPId, instantPurchase, itemId);
			
			var itemParentId = "item" + itemId + "Parent";
	        addInputField(wantOffer, tdElem, 'hidden', itemParentId, itemParentId, parentCategory, itemId);
	
	        trElem.appendChild(tdElem);
	
	        mytbody.appendChild(trElem);
	        
	        reStyleTable(wantOffer);
			
	   		
    	}
    	//checkAllowQuestion(); 

    } else {
        alert("This test not supported in the current browser.");
    }
}

function addSummaryItem(wantOffer, itemId, itemName, quantityWanted) {

    if (document.createElement && !isIEMac) {
        // prepare references to document tree objects for later
        var mytable = document.getElementById("item" + wantOffer + "Table");
        var mytbody = document.getElementById("item" + wantOffer + "TableBody");
        // generate fragment container for tbody assembly
	
        var trElem, tdElem;
        trElem = document.createElement("tr");
        	
        tdElem = document.createElement("td");
        tdElem.className = "col0";
        
        var itemLink = "/product/itemView/" + itemId + "&#63;close=true";
		var popUp = "javascript:popUp(\"" + itemLink + "\", 800, 600);"
	     
		var fullName = "(" + quantityWanted + ") " + itemName;
        addLink(tdElem, popUp, fullName);
        trElem.appendChild(tdElem);
	
        mytbody.appendChild(trElem);
	        
        reStyleTable(wantOffer);

	} else {
        alert("This test not supported in the current browser.");
    }
}

function getItemWantInfo() {
	var itemWantTableBody = document.getElementById("itemWantTableBody");
	
	if(itemWantTableBody != null) {
		var rows = itemWantTableBody.rows;
			
		numberOfWantItems = rows.length - 1;
		
		for (var i = 1; i < rows.length; i++) {
			var row = rows[i];
			var cells = row.cells;
	
			var itemId = cells[0].childNodes[0].id;
			itemWantInfo += itemId + itemDataSeparator;		
			
			var itemName = cells[1].childNodes[0].innerHTML;
			itemWantInfo += itemName + itemDataSeparator;
			
			var itemQty = cells[3].childNodes[0].value;
			itemWantInfo += itemQty + itemDataSeparator;
			
			var itemQtyWant = cells[3].childNodes[1].value;
					
			if(itemQtyWant > itemQty) {
				//resetting wanted quantity if it is wrong
				itemWantInfo += 1 + itemDataSeparator;		
			}else {
				itemWantInfo += itemQtyWant + itemDataSeparator;
			}
			
			var itemExType = cells[3].childNodes[2].value;
			itemWantInfo += itemExType + itemDataSeparator;
			
			var itemIP = cells[3].childNodes[3].value;
			itemWantInfo += itemIP + itemDataSeparator;
			
			var itemParent = cells[3].childNodes[4].value;
			itemWantInfo += itemParent + itemSeparator;
			
			if(itemExType == "2") {
				numberOfCashItems++;
			}
			
			if(itemIP == "1") {
				numberOfIPItems++;
			}			
			
		}
		
		itemWantInfo = escapeQuotation(itemWantInfo);		
	}

}

function getItemOfferInfo() {
	var itemOfferTableBody = document.getElementById("itemOfferTableBody");
	
	if(itemOfferTableBody != null) {
		var rows = itemOfferTableBody.rows;
		
		numberOfOfferItems = rows.length - 1;
		
		for (var i = 1; i < rows.length; i++) {
			var row = rows[i];
			var cells = row.cells;
	
			var itemId = cells[0].childNodes[0].id;
			itemOfferInfo += itemId + itemDataSeparator;		
			
			var itemName = cells[1].childNodes[0].innerHTML;
			itemOfferInfo += itemName + itemDataSeparator;
			
			var itemQty = cells[3].childNodes[0].value;
			itemOfferInfo += itemQty + itemDataSeparator;
			
			var itemQtyOffer = cells[3].childNodes[1].value;
			
			if(itemQtyOffer > itemQty) {
				//resetting wanted quantity if it is wrong
				itemOfferInfo += 1 + itemDataSeparator;		
			}else {
				itemOfferInfo += itemQtyOffer + itemDataSeparator;
			}
	
			
			var itemExType = cells[3].childNodes[2].value;
			itemOfferInfo += itemExType + itemDataSeparator;
			
			var itemIP = cells[3].childNodes[3].value;
			itemOfferInfo += itemIP + itemDataSeparator;
			
			var itemParent = cells[3].childNodes[4].value;
			itemOfferInfo += itemParent + itemSeparator;
			
			if(itemExType == "2") {
				numberOfCashItems++;
			}
			
			if(itemIP == "1") {
				numberOfIPItems++;
			}
			
		}
	
		itemOfferInfo = escapeQuotation(itemOfferInfo);
		
	}
}

function escapeQuotation(theString) {
	while(theString.indexOf("\"") != -1) {
		theString = theString.replace("\"", "&quot;");
	}
	return theString;
}

function viewSwaps() {
	var frm = document.swapsForm;
	frm.submit();
}

function getAliasInfo() {
	
	var frm = document.SuperCatCreateForm;
	
	var aliased = frm.aliasedCats;
	
	for(var i=0; i < aliased.options.length; i++) {
			var currentAlias = aliased.options[i];
			aliasInfo += currentAlias.value + itemDataSeparator;
			aliasInfo += currentAlias.text + itemSeparator;
	}
	
	aliasInfo = escapeQuotation(aliasInfo);
}

function checkAllowQuestion() {
	var questionLink = document.getElementById("questionLink");
	
	if(questionLink != null) {
		var oldItemWantInfo = itemWantInfo;
		getItemWantInfo();
		
		if(itemWantInfo != null && itemWantInfo.length > 0) {
			var arrayOfItems = itemWantInfo.split(itemSeparator);
			if(arrayOfItems.length == 2) {	//there is only one "wanted" item selected
				var itemInfo = arrayOfItems[0].split(itemDataSeparator);
				var itemId = itemInfo[0];
				var itemLink = "/swap/questionAsk.do?itemId=" + itemId + "&amp;close=true";
				var popUpLink = "javascript:popUp(\"" + itemLink + "\", 800, 600);"
				questionLink.href = popUpLink;
				
				if (document.all) { // what follows should work
								  // with NN6 but doesnt in M14
					if(document.getElementById("questionButtonRow").style.display !=null){
							document.getElementById("questionButtonRow").style.display="inline"
					}
				
				} else if (document.getElementById) { // so here is the
														  // NN6 workaround
					if(document.getElementById("questionButtonRow").style.display !=null){
						document.getElementById("questionButtonRow").style.display="table-row"
					}
					
				}
				
			}else {
				questionLink.href = "#";
				
				if(document.getElementById("questionButtonRow").style.display !=null){
					document.getElementById("questionButtonRow").style.display="none"
				}
							
			}
		}else {
			questionLink.href = "#";
			
			if(document.getElementById("questionButtonRow").style.display !=null){
				document.getElementById("questionButtonRow").style.display="none"
			}

		}
		itemWantInfo = oldItemWantInfo;
		
	}	
}

function getExampleImages(tags,destination, width, height) {
    var destContent = document.getElementById(destination).innerHTML;
    if (destContent.indexOf('Loading') > 0) {	//the loading image is being shown
    	
    	//workaround to create a XMLHTTPRequest in both IE or FF
    	var exampleImagesRequest=false;
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	// JScript gives us Conditional compilation, we can cope with old IE versions.
	// and security blocked creation of the objects.
	 try {
	  exampleImagesRequest = new ActiveXObject("Msxml2.XMLHTTP");
	 } catch (e) {
	  try {
	   exampleImagesRequest = new ActiveXObject("Microsoft.XMLHTTP");
	  } catch (E) {
	   exampleImagesRequest = false;
	  }
	 }
	@end @*/
	if (!exampleImagesRequest && typeof XMLHttpRequest!='undefined') {
		try {
			exampleImagesRequest = new XMLHttpRequest();
		} catch (e) {
			exampleImagesRequest=false;
		}
	}
        if(exampleImagesRequest)  {
        	exampleImagesRequest.open("GET", "/search/exampleImagesGet.do?tags=" + tags,true);
        	exampleImagesRequest.onreadystatechange=function() {
            	if (exampleImagesRequest.readyState==4) {	//the transfer is complete
                	var exampleImagesResults = exampleImagesRequest.responseText;
                    if (exampleImagesResults == "null" || exampleImagesRequest.status != 200) {
                    	exampleImagesResults = "";
                    	document.getElementById(destination).innerHTML = "<h2 align='center'>No Photos Available</h2>";                            
                    } else {
                    	document.getElementById(destination).innerHTML = exampleImagesResults;
                    	var images = document.getElementById(destination).getElementsByTagName("img");
                        for (var i = 0; i < images.length; i++){
                        	var image = images.item(i);
                            if (image.height > height) image.height = height;
                            if (image.width > width) image.width = width;
                        }
                    }
                }
            }
            exampleImagesRequest.send(null);
       	}
    }
    
	function getParameter ( queryString, parameterName ) {
   		// Add "=" to the parameter name (i.e. parameterName=value)
   		var parameterName = parameterName + "=";
   		if ( queryString.length > 0 ) {
    	// Find the beginning of the string
		begin = queryString.indexOf ( parameterName );
      	// If the parameter name is not found, skip it, otherwise return the value
      	if ( begin != -1 ) {
        	// Add the length (integer) to the beginning
         	begin += parameterName.length;
         	// Multiple parameters are separated by the "&" sign
         	end = queryString.indexOf ( "&" , begin );
      		if ( end == -1 ) {
    			end = queryString.length
      		}
      		// Return the string
      		return unescape ( queryString.substring ( begin, end ) );
   		}
   		// Return "null" if no parameter has been found
   		return "null";
   }
}
    
}
