// This javascript file was made to handle the ajax requests of creating a new classifieds entry.


/**
* Creates and executes an Ajax GET request
* <p>
* @param url 		The filename of the php file to request from (do not have to change the scope of the file system).
* @param parameters The URL arguments. Can sometimes be pre-compiled.
* @param step 		The step that the user is up to in adding a new listing.
*/
function makeRequest(url, parameters, requestMethod, step) {
	http_request = false;
	if (window.XMLHttpRequest) { // Mozilla, Safari, etc
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
		// set type accordingly to anticipated content type
		//http_request.overrideMimeType('text/xml');
		http_request.overrideMimeType('text/html');
	}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (error) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (error) {}
		}
	}
	if (!http_request) {
		alert('Cannot create XMLHTTP instance');
		return false;
	}

	paramStep = "step" + step;
	//document.getElementById(step).innerHTML = "Please wait, loading the next step...";
	
	// whent he request is sent via GET
	if(requestMethod == "GET"){
		http_request.open('GET', url + parameters, true);
		http_request.onreadystatechange = function() { 
			if (http_request.readyState == 4) {
				if (http_request.status == 200) {
					alert("step = " + paramStep);
					alert(http_request.responseText);
					result = http_request.responseText;
					document.getElementById(paramStep).innerHTML = result;            
				} else {
					alert('There was a problem with the get request. Please report this in the Bugs thread in the top left.');
				}
			}
		}
		http_request.send();
	} else if (requestMethod == "POST"){
		http_request.open('POST', url, true);
		http_request.onreadystatechange = function() {//Call a function when the state changes.
			if(http_request.readyState == 4){ 
				alert("readystate == 4");
				if(http_request.status == 200 || http_request.status == 302) {
					alert("http_request status = " + http_request.status);
					alert("step = " + paramStep);
					alert(http_request.responseText);
					result = http_request.responseText;
					if(http_request.status == 302){
						// this means that there has been a redirect because the data inputted in step 4 has failed php validation.
						// reload the appropriate span.
						step--;
						paramStep = "step" + step;
						document.getElementById(paramStep).innerHTML = result;
					} else {
						document.getElementById(paramStep).innerHTML = result;
					}
				} else {
					alert('There was a problem with the post request. Please report this in the Bugs thread in the top left.');
				}
			}
		}
		//Send the proper header information along with the request
		http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		http_request.setRequestHeader("Content-length", parameters.length);
		http_request.setRequestHeader("Connection", "close");
		http_request.send(parameters);
	}	
}

//if (result.indexOf("location.replace('") != -1){
//						// get the position of the url for location.replace.
//						var stringToTest = "location.replace('";
//						startIndexPosition = result.indexOf("location.replace('") + stringToTest.length;
//						endIndexPosition = result.indexOf("')");
//						
//						// this is the redirect location. it should be in the format of "usercheckout.php?step=5&listingid=3403&productid=6" without the quotes
//						redirectLocation = result.substring(startIndexPosition, endIndexPosition);
//						
//						// redirectURL is the filename for the makerequest function
//						startIndexPosition = 0;
//						endIndexPosition = redirectLocation.indexof("?");
//						redirectURL = redirectLocation.substring(startIndexPosition, endIndexPosition);
//						
//						// redirectStep is the next step to take
//						// if there is a step in the url arguments and it is not empty:
//						stringToTest="step=";
//						redirectLocation.indexOf("step=") + stringToTest.length;
//						if(redirectLocation.indexOf("step=") != -1 && !isNaN(redirectLocation.charat(redirectLocation.indexOf("step=") + stringToTest.length))){
//							// redirectStep = the step number
//							redirectStep = redirectLocation.charat(redirectLocation.indexOf("step=") + stringToTest.length);
//							// redirectParameters = all other parameters without step
//							redirectParameters = redirectLocation.substring((redirectLocation.indexOf("step=") + stringToTest.length)+1, redirectLocation.length-1);
//							makeRequest(redirectURL, redirectParameters, "GET", redirectStep);
//						} else {
//							alert("There has been a problem with your request. Please report this to the bugs thread: The server returned the wrong redirection details.");
//						}
//					} else if (result.indexOf("location.replace('") = -1){
//						document.getElementById(step).innerHTML = result; 
//					}


/**
* Automatically grabs form details, such as input field contents etc.
* Think of this as a URL argument creator, based on form input.
* <p>
* @param obj 			Form input.
* @param filename 		The filename of the PHP file to request from.
* @param requestMethod 	GET or POST.
*/
function getFormContents(obj, filename, requestMethod) {
	var getstr = "";
	var sendStr;
	if(requestMethod == "GET"){
		sendStr = "?";
	} else if (requestMethod == "POST"){
		sendStr = "";
	}

	for (i=0; i<obj.elements.length; i++) {

			alert("getsrt @ " + i + " = " + getstr);

		if (obj.elements[i].tagName == "INPUT") {
			if (obj.elements[i].type == "text") {
				getstr += obj.elements[i].name + "=" + obj.elements[i].value + "&";
			}
			if (obj.elements[i].type == "checkbox") {
				if (obj.elements[i].checked) {
				getstr += obj.elements[i].name + "=" + obj.elements[i].value + "&";
				} else {
					getstr += obj.elements[i].name + "=&";
				}
			}
			if (obj.elements[i].type == "radio") {
				if (obj.elements[i].checked) {
				getstr += obj.elements[i].name + "=" + obj.elements[i].value + "&";
				}
			}
			if (obj.elements[i].type == "hidden") {
				if(obj.elements[i].name == "step") {
					nextStep = obj.elements[i].value;
				}
				getstr += obj.elements[i].name += "=" + obj.elements[i].value + "&";
			}	
		}
		if (obj.elements[i].tagName == "SELECT") {
			var sel = obj.elements[i];
			getstr += sel.name + "=" + sel.options[sel.selectedIndex].value + "&";
		}
		if (obj.elements[i].tagName == "TEXTAREA") {
			getstr+= obj.elements[i].name += "=" + obj.elements[i].value + "&";
		}
		
	}
	filename += '.php';
	sendStr += getstr;
	makeRequest(filename, sendStr, requestMethod, nextStep);

}

/**
* Checks the first step of adding an item (ie, category selection).
* Includes appropriate test to check for correct category selection.
* <p>
* @param objectToPass	Form input. This is grabbed to pass to the "get" function.
*/
function checkFirstStep (objectToPass){
	// Variables used to check the drop down selected from step 1
	var dropdownIndex = document.getElementById('category').selectedIndex;
	var dropdownValue = document.getElementById('category')[dropdownIndex].value;
	
	// If the parent is selected, don't display the second section, display an alert saying so.
	if(dropdownValue < 22 || dropdownValue > 25) {
		// load the second section.
		getFormContents(objectToPass, "usercheckout1", "GET");
	} else {
		alert("Please select a sub-category in order to continue.");
	}
}


/**
* Checks the second step of adding an item (ie, clicking the submit button on the relevant listing type).
* <p>
* @param input	Form input. (this will be handled by the "get" function at a later date).
*/
function checkSecondStep (objectToPass){
	
	// Grab details from the form to create the url
	var productId = document.getElementById('productid').value;
	var category = document.getElementById('category').value;
	var listingId = document.getElementById('listingid').value;
	
	// Make the ajax request
	var step = 3;
	var filename = "usercheckout1.php";
	var parameters = "?category=";
	parameters += category;
	parameters += "&productid=";
	parameters += productId;
	parameters += "&step=";
	parameters += step;
	
	makeRequest(filename, parameters, "GET", step);
}

// This function is included for continuity.
function checkThirdStep (objectToPass){
	// validate the form
	if(checkform(objectToPass)){
		// send the input data from the form to the "get" function to be assembled into url parameters.
		getFormContents(objectToPass, "usercheckout1", "POST");
	}
}

/**
* This is a rewrite of the checkforn functions that comes with 68 classifieds. Validation for the per-case input fields has been
* 	moved from being generated by smarty, to pure javascript. Majority of the smarty tags have been left in, incase of re-porting
*	and such. The original template is still intact (step3.tpl).
*
* @param frm	Form input.
*/
function checkform(frm) {
	if (frm.title.value == '') {
		alert("{/literal}{$smarty.const.LANG_JAVASCRIPT_PLEASE_ENTER} '{$smarty.const.LANG_TITLE}{literal}'.");
		frm.title.focus();
		return (false);
	}
	
// all checkouts require a price
// {/literal}
// {if $checkoutRequirePrice=="Y" && $checkoutDisPrice=="Y"}
// {literal}
	if (frm.price.value == '' || frm.price.value <= 0) {
		alert("{/literal}{$smarty.const.LANG_JAVASCRIPT_PLEASE_ENTER} '{$smarty.const.LANG_PRICE}{literal}'.");
		frm.price.focus();
		return (false);
	}
	
// all checkouts require a description
// {/literal}
// {/if}
// {if $checkoutDisShortDesc=="Y" && $checkoutRequireShortDesc=="Y"}
// {literal}
	if (frm.shortDescription.value == '') {
		alert("{/literal}{$smarty.const.LANG_JAVASCRIPT_PLEASE_ENTER} '{$smarty.const.LANG_SHORT_DESCRIPTION}{literal}'.");
		frm.shortDescription.focus();
		return (false);
	}
	
// {/literal}
// {/if}
// {if $checkoutRequireDesc=="Y" && $checkoutDisDesc=="Y"}
// {literal}
	if (frm.description.value == '') {
		alert("{/literal}{$smarty.const.LANG_JAVASCRIPT_PLEASE_ENTER} '{$smarty.const.LANG_DESCRIPTION}{literal}'.");
		frm.description.focus();
		return (false);
	}	
	
//{/literal}
//{literal}
	//extra field validation
	// year field
	if(frm.opt15){
		if (frm.opt15.value == "") {
			alert("Please enter a value in the field 'Year'.");
			frm.opt15.focus(); return (false);
		}
	}
	//milage field
	if(frm.opt17){
		if (frm.opt17.value == "") {
			alert("Please enter a value in the field 'Milage'.");
			frm.opt17.focus(); return (false);
		}
	}
	// transmission field
	if(frm.opt16){
		if (frm.opt16.value == "") {
			alert("Please enter a value in the field 'Transmission'.");
			frm.opt16.focus();
			return (false);
		} 
	}
		
	// rims
	// pcd field
	if(frm.opt13){
		if (frm.opt13.value == "") {
			alert("Please enter a value in the field 'Wheel PCD'.");
			frm.opt13.focus(); return (false);
		}
	}
		
	// rim colour field
	if(frm.opt18){
		if (frm.opt18.value == "") {
			alert("Please enter a value in the field 'Wheel Colour'.");
			frm.opt18.focus();
			return (false);
		}
	}
		
	// rim condition field
	if(frm.opt19){
		if (frm.opt19.value == "") {
			alert("Please enter a value in the field 'Condition'.");
			frm.opt19.focus();
			return (false);
		}
	}
	return true;
}

// Functions pre-existing in 68 classifieds.
function textTitleCounter(field, countfield, maxlimit) {
	if (field.value.length > maxlimit)
		{field.value = field.value.substring(0, maxlimit);}
	else
	{
		document.getElementById('cCharTitleLeft').innerHTML = field.value.length;
	}
}
// Functions pre-existing in 68 classifieds.
function textShortDescCounter(field, countfield, maxlimit) {
	if (field.value.length > maxlimit)
		{field.value = field.value.substring(0, maxlimit);}
	else
	{
		document.getElementById('cCharShortDescLeft').innerHTML = field.value.length;
	}
}
// Functions pre-existing in 68 classifieds.
function textCounter(field, countfield, maxlimit) {
  if (field.value.length > maxlimit)
	  {field.value = field.value.substring(0, maxlimit);}
	  else
	  {//countfield.value = maxlimit - field.value.length;
	   document.getElementById('cCharLeft').innerHTML = field.value.length;
	   }
}

// Functions pre-existing in 68 classifieds.
function MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}
function confirmDelete(goto)
{
var agree=confirm("Are you sure you wish to delete this?\nIt cannot be undone");
	if (agree)
	{
		location.href=goto;
		return true ;
	}
	else
	{
		return false ;
	}
}