// AJAX
var bSubmit = true;
var oReq = false;
var gFormSaveButton = false;

function ajaxHideWarnings(oForm)
{
	aElements = document.getElementsByTagName("div");
	
	for (j = 0; j < aElements.length; j++) {
		if (aElements[j].className == "warnings") {
			aElements[j].style.display = 'none';
		}
	}
}


/*	This function gets called as the onsubmit event of a form.
	It will create the XMLHttpRequest object that we use for AJAX.
	It will call the /functions/ajax_validation.php page and will post all the form elements to it.
	It waits for xml reply of that page and if there are errors it will show them.
	If there are no errors this functions returns true, the form will be submitted.
	If there are errors it will return false preventing the form from submitting.
*/

function ajaxValidateForm(oForm) {
	
	if (gFormSaveButton) {
		// only do the form validation when the user has clicked on the save button of the form
		if (window.XMLHttpRequest) {
			// FF
			oReq = new XMLHttpRequest();
		} else if (window.ActiveXObject) {
			// IE
			oReq = new ActiveXObject("Microsoft.XMLHTTP");
		}
		
	    if (oReq) {
			bSubmit = false;
	
			// collect all the form elements and prepare them as post data
			cData = "";
			for (i = 0; i < oForm.elements.length; i++) {

				if (i > 0) {
					cData += "&";
				}
				
				if (oForm.elements[i].type == "checkbox") {
					if (oForm.elements[i].checked == true) {
						cData += oForm.elements[i].name + "=" + oForm.elements[i].value;
					}
				} else if (oForm.elements[i].type == "radio") {
					if (oForm.elements[i].checked == true) {
						cData += oForm.elements[i].name + "=" + oForm.elements[i].value;
					}
				} else if (oForm.elements[i].type == "hidden") {
					var aParentNodeClassName = oForm.elements[i].parentNode.className.split(" ");					
					var bFckEditor = false;
					for (j=0;j<aParentNodeClassName.length;j++) {
						if (aParentNodeClassName[j]  == "fckeditor") {
							bFckEditor = true;
						}
					}
					var itemId = oForm.elements[i].id;
					var itemName = oForm.elements[i].name;
					if (bFckEditor && (itemId == itemName)) {
						var oEditor = FCKeditorAPI.GetInstance(itemId);
						var cValue = oEditor.GetXHTML();
						cData += oForm.elements[i].name + "=" + encodeURIComponent(cValue);
					} else {
						cData += oForm.elements[i].name + "=" + encodeURIComponent(oForm.elements[i].value);
					}					
				} else {
					
					if($(oForm.elements[i]).is(':visible') && !$(oForm.elements[i]).is(':disabled')){
						cData += oForm.elements[i].name + "=" + encodeURIComponent(oForm.elements[i].value);
					}
				}
						
			}

			// send the validation request to the php page that does the validation synchronously
			oReq.open("POST", "/functions/ajax_validation.php", false);
			oReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			oReq.send(cData);

			// after the send() is called the execution of this script will be blocked untill the ajax_validation.php page 
			// has finished executing then this script continues below where we are going to parse the xml that is returned
			// to see if there where any errors that we must display
			
			if (oReq.readyState == 4) {
				if (oReq.status == 200) {
					
					ajaxHideWarnings(oForm);
					
					if (window.ActiveXObject) {
						//IE
						oDOM = new ActiveXObject("Microsoft.XMLDOM");
						oDOM.loadXML(oReq.responseText);
					} else {
						//FF
						oParser = new DOMParser();
						oDOM = oParser.parseFromString(oReq.responseText, "text/xml");
					}
					
					//Shows the responce for debugging
					//alert(oReq.responseText);
					
					oValidationResult = oDOM.getElementsByTagName("ValidationResult").item(0);
					oFields = oDOM.getElementsByTagName("Field");
					
					// Loop through the fields
					for (i = 0; i < oFields.length; i++) {
						oField = oFields[i];
						cFieldName = oField.getAttribute("Name");
						oWarnings = oField.getElementsByTagName("Warning");
						
						// Loop through the warnings
						for (j = 0; j < oWarnings.length; j++) {

							oWarning = oWarnings[j];
							cWarningType = oWarning.getAttribute("Type");

							// now search for the hidden warning in the HTML and make it visible
							oDocWarning = document.getElementById(oForm.name + "_" + cFieldName + "_" + cWarningType);
							//alert(oForm.name + "_" + cFieldName + "_" + cWarningType);
							if (oDocWarning) {
								oDocWarning.style.display = 'block';
							}
						}
											
					}
					
					if (oValidationResult.getAttribute("AllowSubmit") == "true") {
						bSubmit = true;
					} else {
						bSubmit = false;
						checkReloadCaptcha();
						hideBusy();
					}
											

				}
			}
			return bSubmit;
		}
	} else {
		return true;
	}
}

/*
	Gets called during the onload event of the page. (functions.js addDefaultFunctions())
	This functions makes sure that gFormSaveButton is only set to true when the user clicks the save button of the form
	not when he clickes the cancel button.
*/	
function ajaxFixFormButtons()
{
	for (i = 0; i < document.forms.length; i++) {
		oForm = document.forms[i];
		for (j = 0; j < oForm.elements.length; j++) {
			oElement = oForm.elements[j];
			if (oElement.type == "submit") {
				if (oElement.id == "saveButton" || oElement.id == "previewButton" || oElement.id == "testButton") {
					oElement.setAttribute("onclick", "ajaxSetSaveButtonGlobal();"); //FireFox
					oElement.onclick = ajaxSetSaveButtonGlobal; //Internet Explorer
				} else if (oElement.id == "cancelButton" || oElement.id == "backButton" || oElement.id == "keepButton") {
					oElement.setAttribute("onclick", "ajaxUnSetSaveButtonGlobal();"); //FireFox
					oElement.onclick = ajaxUnSetSaveButtonGlobal; //Internet Explorer
				}
			}
		}
	}
}

/*
	See ajaxFixFormButtons();
*/
function ajaxSetSaveButtonGlobal()
{
	gFormSaveButton = true;
}

function ajaxUnSetSaveButtonGlobal()
{
	gFormSaveButton = false;	
}




function calculatePrice(oForm, cValidationPage) {

	
	// only do the form validation when the user has clicked on the save button of the form
	if (window.XMLHttpRequest) {
		// FF
		oReq = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		// IE
		oReq = new ActiveXObject("Microsoft.XMLHTTP");
	}
	
    if (oReq) {
    
    	
    	// collect all the form elements and prepare them as post data
		cData = "";
		for (i = 0; i < oForm.elements.length; i++) {
			if (i > 0) {
				cData += "&";
			}
			
			if (oForm.elements[i].type == "checkbox") {
				if (oForm.elements[i].checked == true) {
					cData += oForm.elements[i].name + "=" + oForm.elements[i].value;
				}
			} else if (oForm.elements[i].type == "radio") {
				if (oForm.elements[i].checked == true) {
					cData += oForm.elements[i].name + "=" + oForm.elements[i].value;
				}
			} else {
				cData += oForm.elements[i].name + "=" + encodeURIComponent(oForm.elements[i].value);
			}
		}

		// send the validation request to the php page that does the validation synchronously
		oReq.open("POST", cValidationPage, false);
		oReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		oReq.send(cData);

		// after the send() is called the execution of this script will be blocked untill the ajax_validation.php page 
		// has finished executing then this script continues below where we are going to parse the xml that is returned
		// to see if there where any errors that we must display
		
		if (oReq.readyState == 4) {
		
			if (oReq.status == 200) {
				
				ajaxHideWarnings(oForm);
				
				if (window.ActiveXObject) {
					//IE
					oDOM = new ActiveXObject("Microsoft.XMLDOM");
					oDOM.loadXML(oReq.responseText);
				} else {
					//FF
					oParser = new DOMParser();
					oDOM = oParser.parseFromString(oReq.responseText, "text/xml");
				}
				
//				alert(oReq.responseText);
				oValidationResult = oDOM.getElementsByTagName("ValidationResult").item(0);
				oFields = oDOM.getElementsByTagName("Field");
				oFieldWarnings = oDOM.getElementsByTagName("WarningAll");
				
				// Loop through the fields
				
				//warning div
				var nWarnings = oFieldWarnings.length;
				var bDisplayMessage = 0;
				var oRemoveWarningDiv = document.getElementById("divMessageBlock");
				var oMessageDiv = document.getElementById("messages");
				
				if (oRemoveWarningDiv){
					oMessageDiv.removeChild(oRemoveWarningDiv); 
				}
				
				for (i = 0; i < oFields.length; i++) {
					oField = oFields[i];
					cFieldName = oField.getAttribute("Name");
							
					oUpdateWarningAll = oField.getElementsByTagName("WarningAll");
					if (oUpdateWarningAll) {

						for (j = 0; j < oUpdateWarningAll.length; j++) {
							var bDisplayMessage = 1;
						}
						
					}
					
					oUpdates = oField.getElementsByTagName("ModifyHTML");
					// Loop through the modify
					for (j = 0; j < oUpdates.length; j++) {
						oUpdate = oUpdates[j];
						cItemValue = oUpdate.getAttribute("Value");
						document.getElementById(cFieldName).innerHTML = cItemValue;
						
					}
					
					oChangeItems = oField.getElementsByTagName("ReplaceHTML");
					// Loop through the modify
					for (j = 0; j < oChangeItems.length; j++) {

						oChangeItem = oChangeItems[j];
						cHTMLValue = oChangeItem.getAttribute("Value");
						document.getElementById(cFieldName).innerHTML = cHTMLValue;
						
					}
					
					//enable/disable proceed button
					
									
				} //for (i = 0; i < oFields.length; i++)
				
				if (nWarnings > 0) {
					document.getElementById("saveButton").disabled = true;
				} else {
					document.getElementById("saveButton").disabled = false;
				}
								
			} //if (oReq.status == 200)
			
		} //if (oReq.readyState == 4)
		
		
	} //if (oReq)

	if (bDisplayMessage == 1) {
		ajaxHTMLAppendChild(oForm, 'checkout_message', 'messages', 'divMessageBlock');
	}
}

function quantityChanged()
{
	 var url = '/functions/ajax/checkout_quantity.php';
	 var rand = Math.random(9999);
	 var queryString = $('#checkoutOverview').formSerialize() + '&rand=' + rand;
	 $.post(url, queryString, function(data) {
		 for (i in data.job) {
			 jobId = data.job[i].jobId;
			 cost = data.job[i].cost;
			 $('#fnPrice_' + jobId).html(cost);
		 }
		 $('#nSubTotalPrice_checkout').html(data.subtotal);
		 $('#messageblock_order').remove();
		 if (data.errorHtml) {
			 $('#messages').append(data.errorHtml);
			 $('#saveButton').attr('disabled', 'disabled');
		 } else {
			 if (!data.visitor) {
				 $('#saveButton').removeAttr('disabled');
			 }
		 }
	 }, 'json');
}

function validateQuantities()
{
	var result = $.ajax({async: false, 
						 url: "/functions/ajax/checkout_quantity.php",
						 type: "POST",
						 data: $('#checkoutOverview').formSerialize()}).responseText;
	var json = eval('(' + result + ')');
	if (json.errorHtml) {
		return false;
	} else {
		return true;
	}
}

/**
 * 
 *
 * @param object oForm
 * @param string cFunctionsPageId
 * @param string cTargetId
 * @param string cPostProcess
 */
	function ajaxHTMLAppendChild(oForm, cFunctionsPageId, cTargetId, cDivID) {

	// only do the form validation when the user has clicked on the save button of the form
	if (window.XMLHttpRequest) {
		// FF
		oReq = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		// IE
		oReq = new ActiveXObject("Microsoft.XMLHTTP");
	}

    if (oReq) {

    	// collect all the form elements and prepare them as post data
		cData = "";
		if(oForm.elements.length > 0){

			for (i = 0; i < oForm.elements.length; i++) {
				if (i > 0) {
					cData += "&";
				}
				if (oForm.elements[i].type == "checkbox") {
					if (oForm.elements[i].checked == true) {
						cData += oForm.elements[i].name + "=" + oForm.elements[i].value;
					}
				} else if (oForm.elements[i].type == "radio") {
					if (oForm.elements[i].checked == true) {
						cData += oForm.elements[i].name + "=" + oForm.elements[i].value;
					}
				} else {
					cData += oForm.elements[i].name + "=" + encodeURIComponent(oForm.elements[i].value);
				}
			}
    	}    	
    
		// send the validation request to the php page that does the validation synchronously
		oReq.open("POST", "/functions/" + cFunctionsPageId + ".php", false);
		oReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		oReq.send(cData);

		// after the send() is called the execution of this script will be blocked untill the ajax_validation.php page 
		// has finished executing then this script continues below where we are going to parse the xml that is returned
		// to see if there where any errors that we must display
			
		if (oReq.readyState == 4) {

			if (oReq.status == 200) {
				
				ajaxHideWarnings(oForm);
					
				if (window.ActiveXObject) {
					//IE
					oDOM = new ActiveXObject("Microsoft.XMLDOM");
					oDOM.loadXML(oReq.responseText);
				} else {
					//FF
					oParser = new DOMParser();
					oDOM = oParser.parseFromString(oReq.responseText, "text/xml");
				}
				
				var oMessageDiv = document.getElementById(cTargetId);				
				var oWarningDiv=document.createElement("div");
				oWarningDiv.setAttribute('id',cDivID);
				oMessageDiv.appendChild(oWarningDiv);
				oWarningDiv.innerHTML = oReq.responseText;
							
			} //if (oReq.status == 200)
			
		} //if (oReq.readyState == 4)

	} //if (oReq)
	
}



/**
 * 
 *
 * @param object oForm
 * @param string cFunctionsPageId
 * @param string cTargetId
 * @param string cPostProcess
 * @param string cParams
 */
	function ajaxReplaceHTML(oForm, cFunctionsPageId, cTargetId, cPostProcess, cParams) {

	// only do the form validation when the user has clicked on the save button of the form
	if (window.XMLHttpRequest) {
		// FF
		oReq = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		// IE
		oReq = new ActiveXObject("Microsoft.XMLHTTP");
	}

    if (oReq) {
		
    	if (!cParams) {
	    	// collect all the form elements and prepare them as post data
			cData = "";
			if(oForm.elements.length > 0){
	
				for (i = 0; i < oForm.elements.length; i++) {
					if (i > 0) {
						cData += "&";
					}
					if (oForm.elements[i].type == "checkbox") {
						if (oForm.elements[i].checked == true) {
							cData += oForm.elements[i].name + "=" + oForm.elements[i].value;
						}
					} else if (oForm.elements[i].type == "radio") {
						if (oForm.elements[i].checked == true) {
							cData += oForm.elements[i].name + "=" + oForm.elements[i].value;
						}
					} else {
						cData += oForm.elements[i].name + "=" + encodeURIComponent(oForm.elements[i].value);
					}
				}
	    	}
    	} else {
    		
    		cData = cParams;
    	}
    
		// send the validation request to the php page that does the validation synchronously
		oReq.open("POST", "/functions/" + cFunctionsPageId + ".php", false);
		oReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		oReq.send(cData);

		// after the send() is called the execution of this script will be blocked untill the ajax_validation.php page 
		// has finished executing then this script continues below where we are going to parse the xml that is returned
		// to see if there where any errors that we must display
			
		if (oReq.readyState == 4) {

			if (oReq.status == 200) {
				
				if (oForm) {
					ajaxHideWarnings(oForm);
				}
					
				if (window.ActiveXObject) {
					//IE
					oDOM = new ActiveXObject("Microsoft.XMLDOM");
					oDOM.loadXML(oReq.responseText);
				} else {
					//FF
					oParser = new DOMParser();
					oDOM = oParser.parseFromString(oReq.responseText, "text/xml");
				}
				
				document.getElementById(cTargetId).innerHTML = oReq.responseText;
				if (cPostProcess) {
					window.eval(cPostProcess);
				}
				
				//update summary
				if (cFunctionsPageId =="ordermanager_completed_list") {
					if($("#cNumOfOrdersField")){
						$("#cNumOfOrdersField").html($('#summaryOrderCountField').val());
					}
					if($("#cTotalPriceField")){
						$("#cTotalPriceField").html($('#summaryTotalPriceField').val());
					}
				}

															
									
			} //if (oReq.status == 200)
			
		} //if (oReq.readyState == 4)

	} //if (oReq)
	
}



/**
 * 
 *
 * @param object oForm
 * @param string cFunctionsPageId
 * @param string cTargetId
 */
	function ajaxValidateElement(oForm, cFunctionsPageId, cTargetId) {

	// only do the form validation when the user has clicked on the save button of the form
	if (window.XMLHttpRequest) {
		// FF
		oReq = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		// IE
		oReq = new ActiveXObject("Microsoft.XMLHTTP");
	}
	
    if (oReq) {
    
    	
    	// collect all the form elements and prepare them as post data
		cData = "";
		for (i = 0; i < oForm.elements.length; i++) {
			if (i > 0) {
				cData += "&";
			}
			cData += oForm.elements[i].name + "=" + encodeURIComponent(oForm.elements[i].value);
		}

		// send the validation request to the php page that does the validation synchronously
		oReq.open("POST", "/functions/" + cFunctionsPageId + ".php", false);
		oReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		oReq.send(cData);

		// after the send() is called the execution of this script will be blocked untill the ajax_validation.php page 
		// has finished executing then this script continues below where we are going to parse the xml that is returned
		// to see if there where any errors that we must display
		
		if (oReq.readyState == 4) {
		
			if (oReq.status == 200) {
				
				ajaxHideWarnings(oForm);
				
				if (window.ActiveXObject) {
					//IE
					oDOM = new ActiveXObject("Microsoft.XMLDOM");
					oDOM.loadXML(oReq.responseText);
				} else {
					//FF
					oParser = new DOMParser();
					oDOM = oParser.parseFromString(oReq.responseText, "text/xml");
				}
				
				//alert(oReq.responseText);
				
				document.getElementById(cTargetId + oReq.responseText).style.display = 'block';				
													
			} //if (oReq.status == 200)
			
		} //if (oReq.readyState == 4)

	} //if (oReq)
	
}



/**
 * 
 *
 * @param object oForm
 * @param string cFunctionsPageId
 * @param string cTargetId
 * @param string cPostProcess
 */
	function ajaxChangeStatus(oForm, cField, nID, cFunctionsPageId, bToggleOldItem, bSetCheckbox) {

	// only do the form validation when the user has clicked on the save button of the form
	if (window.XMLHttpRequest) {
		// FF
		oReq = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		// IE
		oReq = new ActiveXObject("Microsoft.XMLHTTP");
	}
	
    if (oReq) {
    	
		cData = "id="+nID;
		cData += "&bToggleOldItem="+String(bToggleOldItem);
    	
		// send the validation request to the php page that does the validation synchronously
		oReq.open("POST", "/functions/" + cFunctionsPageId + ".php", false);
		oReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		oReq.send(cData);

		// after the send() is called the execution of this script will be blocked untill the ajax_validation.php page 
		// has finished executing then this script continues below where we are going to parse the xml that is returned
		// to see if there where any errors that we must display
		
		if (oReq.readyState == 4) {
		
			if (oReq.status == 200) {
				
				ajaxHideWarnings(oForm);
				
				if (window.ActiveXObject) {
					//IE
					oDOM = new ActiveXObject("Microsoft.XMLDOM");
					oDOM.loadXML(oReq.responseText);
				} else {
					//FF
					oParser = new DOMParser();
					oDOM = oParser.parseFromString(oReq.responseText, "text/xml");
				}

				if(oReq.responseText){
					
					var cResponse = oReq.responseText;					
					var cOrg = cField+"_"+nID;
					
					if(bToggleOldItem == true) {
						//If bToggleOldItem is set to true there can only be a single selected item
						var cOld = cField+"_"+cResponse;

						document.getElementById(cOld).firstChild.firstChild.className = "icon_check_dis pointer";
						document.getElementById(cOrg).firstChild.firstChild.className = "icon_check pointer";
						
						if (bSetCheckbox == true) {
							var cOldCheckBox = cResponse+"Field";
							var cNewCheckBox = nID+"Field";
							document.getElementById(cOldCheckBox).disabled = false;
							document.getElementById(cNewCheckBox).disabled = true;
						}
						
					} else {
						//If bToggleOldItem is set to false we only toggle the status of the current item (clicked by the user)
						if(cResponse == 1){
							document.getElementById(cOrg).firstChild.firstChild.className = "icon_check pointer";
						} else {
							document.getElementById(cOrg).firstChild.firstChild.className = "icon_check_dis pointer";
						}
					}

				} 
					
			} //if (oReq.status == 200)
			
		} //if (oReq.readyState == 4)

	} //if (oReq)
	
}




function ajaxPreviewImageHandling(cFunctionsPageId, nId, cAction) {

	
	// only do the form validation when the user has clicked on the save button of the form
	if (window.XMLHttpRequest) {
		// FF
		oReq = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		// IE
		oReq = new ActiveXObject("Microsoft.XMLHTTP");
	}
	
    if (oReq) {
    
    	
    	// prepare the post data
		cData = "id="+nId+"&action="+cAction;
		
		// send the validation request to the php page that does the validation synchronously
		oReq.open("POST", cFunctionsPageId, false);
		oReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		oReq.send(cData);

		// after the send() is called the execution of this script will be blocked untill the ajax_validation.php page 
		// has finished executing then this script continues below where we are going to parse the xml that is returned
		// to see if there where any errors that we must display
		
		if (oReq.readyState == 4) {
		
			if (oReq.status == 200) {
				
				ajaxHideWarnings(oForm);
				
				if (window.ActiveXObject) {
					//IE
					oDOM = new ActiveXObject("Microsoft.XMLDOM");
					oDOM.loadXML(oReq.responseText);
				} else {
					//FF
					oParser = new DOMParser();
					oDOM = oParser.parseFromString(oReq.responseText, "text/xml");
				}
				
				//alert(oReq.responseText);
				oValidationResult = oDOM.getElementsByTagName("ValidationResult").item(0);
				oFields = oDOM.getElementsByTagName("Field");
				
				var nItemId = nId.split(",")[0];
				
				var oThumbCell = document.getElementById("nItemID[" + nItemId + "]ImageThumbnail");
				var oImageNameCell = document.getElementById("nItemID[" + nItemId + "]ImageInfo");
				var oImageFileSizeCell = document.getElementById("nItemID[" + nItemId + "]ImageAddionalInfo");
				var oImageResetButton = document.getElementById("nItemID[" + nItemId + "]ResetButton");
				var oImageHiddenField = document.getElementById("nItemID[" + nItemId + "]Field");
								
				
				for (i = 0; i < oFields.length; i++) {
					oField = oFields[i];
					cFieldName = oField.getAttribute("Name");
					
					oUpdates = oField.getElementsByTagName("ModifyHTML");
					
					if (cFieldName == "thumbnail") {				
						oThumbCell.innerHTML = oUpdates[0].getAttribute("Value");
					} else if (cFieldName == "name") {
						oImageNameCell.innerHTML = oUpdates[0].getAttribute("Value");
					} else if (cFieldName == "size") {
						oImageFileSizeCell.innerHTML = oUpdates[0].getAttribute("Value");
					} else if (cFieldName == "resetbutton") {
						if (oUpdates[0].getAttribute("Value") == "false") {
							oImageResetButton.disabled = false;
						} else if (oUpdates[0].getAttribute("Value") == "true") {
							oImageResetButton.disabled = true;
						}
					} else if (cFieldName == "path") {
						oImageHiddenField.value = oUpdates[0].getAttribute("Value");
					} 
				}
								
			} //if (oReq.status == 200)
			
		} //if (oReq.readyState == 4)
		
		
	} //if (oReq)

}

function checkReloadCaptcha()
{
	if ($('#cAccountCreationVerificationFieldset').length) {
		$.get('/functions/ajax/get_captcha.php', {}, function(imageUrl){
			$('#captchaImageField').attr('src' , imageUrl);
			$('#fcCaptchaField').val('');
		});
	}
}
