var orderWindowReference = null;

function myFormSubmit(text) { 
  document.write("<div class=\"link-button-clear\"><a href=\"#\" onclick=\"this.blur(); var form = this; while(null != (form = form.parentNode)) if( form.nodeName == \'FORM\') if( (form.onsubmit &amp;&amp; form.onsubmit()) || (!(form.onsubmit)) ) form.submit();; return false;\" class=\"link-button\"><span>"+text+"</span></a></div>");
}
function myFormSubmitText(text) { 
  document.write("<div class=\"submit_text\"><a href=\"#\" onclick=\"this.blur(); var form = this; while(null != (form = form.parentNode)) if( form.nodeName == \'FORM\') if( (form.onsubmit &amp;&amp; form.onsubmit()) || (!(form.onsubmit)) ) form.submit();; return false;\"><span>"+text+"</span></a></div>");
}

function orderPopup(url) {

	if(orderWindowReference != null && !orderWindowReference.closed) {
		orderWindowReference.close();
	}
	orderWindowReference = window.open(url, 'tilaus', 'resizable=1, menubar=0, scrollbars=1, height=700, width=850, top=10, left=60');
}

function generalPopup(url) {

	var popup = window.open(url, url, 'resizable=1, menubar=1, toolbar=1, scrollbars=1, height=600, width=750, top=20, left=60');
	popup.focus();
}


function uncheckRadios(formId) {
	var myForm = document.getElementById(formId);	
	for(var i=0; i < myForm.elements.length; i++) {
		if(myForm.elements[i].type == 'radio' && myForm.elements[i].name == 'optionIds[]') {
			myForm.elements[i].checked = false;
		}
	}
}


function focus(elementId) {
	var input = document.getElementById(elementId);
	if(input) {
		input.focus();
	}
}

function submitForm(obj) {
	
	obj.blur();
	var form = obj; 
	
	while(null != (form = form.parentNode))  {
		if( form.nodeName == 'FORM') {
			if((form.onsubmit && form.onsubmit()) || (!(form.onsubmit))) {
				form.submit();
			}
		}
	}
				 
	return false;

}

function removeElement(element) {
	if(element != null) {
		element.parentNode.removeChild(element);
	}
}

function checkOptionCardinality(id, name, maxOccurs) {
	
	if(maxOccurs >= 0) {
	
		// First count selections for current option
		var optionInputs = document.getElementsByName('optionIds[]');
		var optionCounter = 0;
		for(var i = 0; i< optionInputs.length; i++) {
			if(optionInputs[i].value == id) {
				optionCounter++;
			}
		}
	
		// Then compare the optionCount to maxOccurs restriction
		if(optionCounter >= maxOccurs) {
			if(maxOccurs == 0) {
				alert("Täytteen "+name+" valitseminen ei ole sallittua.");
			}
			else if(maxOccurs == 1) {
				alert("Täytteen "+name+" voi valita ainoastaan kerran.");
			}
			else {
				alert("Täytteen "+name+" voi valita ainoastaan "+maxOccurs+" kertaa.");
			}
			// Return false if maxOccurs has been reached
			return false;
		}
	}
	return true;
}

function inArray(needle, haystack) {
	
	if(haystack != null && haystack.length > 0) {
		for(var i=0; i < haystack.length; i++) {
			if(haystack[i] == needle) {
				return true;
			}
		}	
	}
	return false;
}

/**
 * Returns false if any of the selected options is in the unallowedOptions array;
 */
function checkUnallowedOptions(unallowedOptions) {

	if(unallowedOptions != null && unallowedOptions.length > 0) {
		
		var optionInputs = document.getElementsByName('optionIds[]');
		for(var i = 0; i< optionInputs.length; i++) {
			if(inArray(optionInputs[i].value, unallowedOptions)) {
				alert("Tälle täytteelle vaihtoehtoinen täyte "+optionInputs[i].alt+" on jo valittu. Poista valinta, mikäli haluat vaihtaa täytteen.");
				return false;
			}
		}	
	}
	return true;
}

function addOption(id, name, maxOccurs, unallowedOptions, imgSrc, calcPriceUrl) {
	
	// Check cardinality before adding
	if(!checkOptionCardinality(id, name, maxOccurs)) {
		return false;
	}

	// Check unallowed options before adding
	if(!checkUnallowedOptions(unallowedOptions)) {
		return false;
	}

	var optionList = document.getElementById('selectedOptions');
	
	// Create list item
	var li = document.createElement('li');
	
	// Create span for to remove option
	var span = document.createElement('span');
	setClass(span, 'remove');
	setRemoveOptionOnClick(span, calcPriceUrl);

	// Create icon image	
	var img = document.createElement('img');
	img.setAttribute('alt', 'Poista');
	img.setAttribute('title', 'Poista '+name);
	img.setAttribute('src', imgSrc);
	
	// Add icon to span
	span.appendChild(img);
	
	// Create input-element to hold option id
	var input = createNamedElement('input','optionIds[]');
	input.setAttribute('type','hidden');
	input.setAttribute('value', id);
	input.setAttribute('alt', name);
	
	// Add created elements to list item
	li.appendChild(span);
	li.appendChild(document.createTextNode(' '+name));
	li.appendChild(input);
	
	// Add list item to list
	optionList.appendChild(li);
	
	if(calcPriceUrl != null && calcPriceUrl.length > 0) {
	  calculateProductPrice(calcPriceUrl);
	}
	
	return true;
}

// Helper, to allow IE add named elements
// http://www.thunderguy.com/semicolon/2005/05/23/setting-the-name-attribute-in-internet-explorer/	
function createNamedElement(type, name) {
   var element = null;
   // Try the IE way; this fails on standards-compliant browsers
   try {
      element = document.createElement('<'+type+' name="'+name+'">');
   } catch (e) {
   }
   if (!element || element.nodeName != type.toUpperCase()) {
      // Non-IE browser; use canonical method to create named element
      element = document.createElement(type);
      element.name = name;
   }
   return element;
}


// IE fix to set class-attribute
// http://alistapart.com/articles/jslogging
function setClass(element, className) {
	if (element.getAttributeNode("class")) {
		for (var i = 0; i < element.attributes.length; i++) {
    			var attrName = element.attributes[i].name.toUpperCase();
    			if (attrName == 'CLASS') {
      				element.attributes[i].value = className;
    		}
  	}
	// otherwise create a new attribute
	} 
	else {
  		element.setAttribute("class", className);
	}
}

// IE fix to set onclick-eventhandler
function setRemoveOptionOnClick(element, calcPriceUrl) {
	if(element.attachEvent) {
		element.onclick = function() {
			removeElement(this.parentNode);
			if(calcPriceUrl != null && calcPriceUrl.length > 0) {
		    calculateProductPrice(calcPriceUrl);
		  }			
			
		};
	} 
	else {
    if(calcPriceUrl != null && calcPriceUrl.length > 0) {
      element.setAttribute('onclick', 'removeElement(this.parentNode); calculateProductPrice("'+calcPriceUrl+'")'); 
    }
    else {
      element.setAttribute('onclick', 'removeElement(this.parentNode)'); 
    }
	}
}

/**
 * Makes Ajax-request to search CustomerInfo by given phone number
 */
var OLD_Q = '';
function search(q, url) {

  // Clear message
  messageBox = document.getElementById("searchMsg");
  messageBox.innerHTML = '';
    
  if(q != null && q.length > 3 && q != OLD_Q) {
      OLD_Q = q;
      	url = url+'/'+q;  
        new Ajax.Request(url, {asynchronous:true, evalScripts:false, onSuccess:function(request, json){update(request)}});        
  }
}
  
/**
 * Helper to get values from Ajax-search result XML
 */
function getTextValue(doc, name) {
  try {
    element = doc.getElementsByTagName(name)[0];
    value = element.firstChild.data;
    if(value != null && value.length > 0) {
      return value;
    }
    else {
      return null;
    }
  } catch(err) {
    return null;
  }  
}

/**
 * Helper to get values from Ajax-search result XML
 */
function getElementValuesToArray(doc, name) {
  try {
    var values = new Array();
    elements = doc.getElementsByTagName(name);
    var arrayIndex = 0;
    for(var i = 0; i < elements.length; i++) {
      value = elements[i].firstChild.data;
      if(value != null && value.length > 0) {
        values[arrayIndex] = value;
        arrayIndex++;
      }
    }
    return values;
  } catch(err) {
    
    return new Array();
  }  
}

/**
 * Updates form fields according to Ajax-search results
 */
function update(request) {

  doc = request.responseXML.documentElement;
  var message = getTextValue(doc, "message");
  var messageBox = document.getElementById("searchMsg");
  
  if(message != null) {      
    messageBox.innerHTML = message;      
    setOrderFormValues("", "", "", "", "", "", "", "");
  }
  else {
    firstname = getTextValue(doc, "firstname");
    lastname = getTextValue(doc, "lastname");
    company = getTextValue(doc, "company");
    phone = getTextValue(doc, "phone");
    address = getTextValue(doc, "address");
    orderPostalCode = getTextValue(doc, "orderPostalCode");
    city = getTextValue(doc, "city");
    email = getTextValue(doc, "email");
    
    setOrderFormValues(firstname, lastname, company, phone, address, orderPostalCode, city, email);
    
    messageBox.innerHTML = "Löytyi "+firstname+" "+lastname;
    
  }
}


/**
 * Makes Ajax-request to calculate customized product price
 */
function calculateProductPrice(url) {

	var productPriceId = null;
	var hiddenPriceInput = document.getElementById("productPriceIdHidden");
	if(hiddenPriceInput != null) {
		productPriceId = hiddenPriceInput.value;
	}
	else {
		var priceSelect = document.getElementById("productPriceId");
		var priceOption = priceSelect.options[priceSelect.selectedIndex];
		productPriceId = priceOption.value;		
	}

	var amountSelect = document.getElementById("productAmount");
	var amountOption = amountSelect.options[amountSelect.selectedIndex];
	var productAmount = amountOption.value;
	
	var params = "productPriceId="+productPriceId+"&amount="+productAmount;
	
	// First count selections for current option
	var optionInputs = document.getElementsByName('optionIds[]');
	var optionCounter = 0;
	for(var i = 0; i< optionInputs.length; i++) {
		params += "&optionIds[]="+optionInputs[i].value;
	}
	
	new Ajax.Request(
		  url, 
		  { 
			  method: 'post',
			  parameters: params,
			  asynchronous: true,
			  onSuccess: calculateProductPriceCallback
		  });        
}

function calculateProductPriceCallback(request) {
  
  doc = request.responseXML.documentElement;
  var status = getTextValue(doc, "status");
  status = status.toLowerCase();
  var priceField = document.getElementById("priceField");
  if(status == "true") {    
    var price = getTextValue(doc, "price");
    priceField.innerHTML = price;
  }
  else {
    var message = getTextValue(doc, "message");
    if(message != "") {
      priceField.innerHTML = "?";
      alert(message);
    }
  }
  
}

/**
 * Set given values to orderForm text fields 
 */
function setOrderFormValues(firstname, lastname, company, phone, address, orderPostalCode, city, email) {
    
   try {
     document.getElementById("firstname").value = firstname;
   } catch(err) {}

   try {      
     document.getElementById("lastname").value = lastname;
   } catch(err) {}

   try {      
     document.getElementById("company").value = company;
   } catch(err) {}

   try {      
     document.getElementById("phone").value = phone;
   } catch(err) {}

   try {      
     document.getElementById("address").value = address;
   } catch(err) {}

   try {      
     document.getElementById("orderPostalCode").value = orderPostalCode;
   } catch(err) {}

   try {      
     document.getElementById("city").value = city;
   } catch(err) {}

   try {      
     document.getElementById("email").value = email;
   } catch(err) {}
}

function getOptionValues(selecetElementId, onlySelected) {
  var selectElement = document.getElementById(selecetElementId);
  var optionElements = selectElement.getElementsByTagName("option");
  var values = new Array();
  var arrayIndex = 0;
  for(var i = 0; i< optionElements.length; i++) {
    if(onlySelected == false || optionElements[i].selected == true) {
      values[arrayIndex] = optionElements[i].value;
      arrayIndex++;
    }
  }
  return values;
}



