//generic validation system
//below is an example of the validation array that gets passed
/*

validationRules = Array(
	Array('companyName','Company Name','required',''),
	Array('ABN','ABN','required',''),
	Array('businessOwnersText','Business Owner','required',''),
	Array('phoneNumber','Phone Number','required',''),
	Array('tradeAddress1','Trading Address','required',''),
	Array('tradeCity','Trading Suburb','required',''),
	Array('tradeState','Trading State','required',''),
	Array('tradePostCode','Trading Post Code','required',''),
	Array('tradeCountry','Trading Country','required',''),
	Array('accountingBasis','Accounting Basis','required',''),
	Array('emailAddress','Email Address','compareRequired',Array('emailAddressConfirm'))
	)

*/

function validateForm(validationArray,additionalMessagesArray)
{
	var alerts = new Array();
	var tmpCount = 0;
	var submitOK = true;
	
	if(additionalMessagesArray)
	{
		for(kk=0;kk<additionalMessagesArray.length;kk++)
		{
			alerts[tmpCount]=additionalMessagesArray[kk];
			tmpCount++;
			submitOK=false;
		}
	}

	
	for (i=0; i<validationArray.length; i++)
	{
		tmpFieldName=validationArray[i][0];
		tmpFieldDisplayName=validationArray[i][1];
		tmpValidationType=validationArray[i][2];
		tmpValidationArgs=validationArray[i][3];
		tmpFieldValue = document.getElementsByName(tmpFieldName)[0].value;
		if((tmpValidationType=="" || tmpValidationType=="required") && trim(tmpFieldValue)=="")
		{
			alerts[tmpCount] = tmpFieldDisplayName + " is a required field";
			tmpCount++;
			submitOK = false;
		}
		else if(tmpValidationType=="emailAddressRequired")
		{
			if(trim(tmpFieldValue)=="")
			{
				alerts[tmpCount] = tmpFieldDisplayName + " is a required field";
				tmpCount++;
				submitOK = false;
			}
			else
			{
				var emailRegExp  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
				
				if(!emailRegExp.test(tmpFieldValue))
				{
					alerts[tmpCount] = tmpFieldDisplayName + " is not a valid email address";
					tmpCount++;
					submitOK = false;
				}
			}
		}
		else if(tmpValidationType=="emailAddressNotRequired")
		{
			if(trim(tmpFieldValue)!="")
			{
				var emailRegExp  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
				
				if(!emailRegExp.test(tmpFieldValue))
				{
					alerts[tmpCount] = tmpFieldDisplayName + " is not a valid email address";
					tmpCount++;
					submitOK = false;
				}
			}
		}
		else if(tmpValidationType=="numberNotRequired")
		{
			if(tmpFieldValue!="")
			{
				
				if(tmpValidationArgs[0]=='')
				{
					strValidChars="";
				}
				else
				{
					strValidChars=tmpValidationArgs[0];
				}
				if(isNumeric(tmpFieldValue,strValidChars)==false)
				{
					alerts[tmpCount] = tmpFieldDisplayName + " must be numeric";
					tmpCount++;
					submitOK = false;
				}
			}
		}
		else if(tmpValidationType=="compareRequired")
		{
			tmpCompareFieldValue = document.getElementsByName(tmpValidationArgs[0])[0].value;
			if(trim(tmpFieldValue)=="" && trim(tmpCompareFieldValue)=="")
			{
				alerts[tmpCount] = tmpFieldDisplayName + " is a required field";
				tmpCount++;
				submitOK = false;
			}
			else if(tmpFieldValue != tmpCompareFieldValue)
			{
				alerts[tmpCount] = tmpFieldDisplayName + " field does not match the Confirm " + tmpFieldDisplayName + " field";
				tmpCount++;
				submitOK = false;
			}
			
		}
		else if(tmpValidationType=="compareNotRequired")
		{
			tmpCompareFieldValue = document.getElementsByName(tmpValidationArgs[0])[0].value;
			if(tmpFieldValue != tmpCompareFieldValue)
			{
				alerts[tmpCount] = tmpFieldDisplayName + " field does not match the Confirm " + tmpFieldDisplayName + " field";
				tmpCount++;
				submitOK = false;
			}
		}
		else if(tmpValidationType=="radioRequired")
		{

			var radio_selected = false;

			// Loop from zero to the one minus the number of radio button selections
			for (radiocounter = 0; radiocounter < document.getElementsByName(tmpFieldName).length; radiocounter++)
			{
			
				if (document.getElementsByName(tmpFieldName)[radiocounter].checked)
				{
					radio_selected = true;
				}
			}

			if(radio_selected==false)
			{
				alerts[tmpCount] = tmpFieldDisplayName + " is a required field.";
				tmpCount++;
				submitOK = false;
			}
		}
	}
	validationMessage(alerts);
	return submitOK;
}

function isArray(obj)
{
	return (obj.constructor.toString().indexOf('Array') != -1);
}

//Outputs validation popup message in one sentence
function validationMessage(alerts)
{

	if(alerts.length==0)
	{
		return;
	}
	var alertstring = "Please correct the following errors:\n\n";
	
	for (i=0; i<alerts.length; i++)
	{
		alertstring += "- " + alerts[i] + "\n"
	}
	
	alert(alertstring);

}

function trim(strText) { 
    // this will get rid of leading spaces 
    while (strText.substring(0,1) == ' ') 
        strText = strText.substring(1, strText.length);

    // this will get rid of trailing spaces 
    while (strText.substring(strText.length-1,strText.length) == ' ')
        strText = strText.substring(0, strText.length-1);

   return strText;
}

//  check for valid numeric strings	
function isNumeric(strString,strValidChars)
{
	//default to decimal (positive or negative) if strValidChars is empty
	if(strValidChars=="")
	{
		strValidChars = "0123456789.-";
	}
	
	var strChar;
	var blnResult = true;

	if (strString.length == 0) return false;

	//  test strString consists of valid characters listed above
	for (j = 0; j < strString.length && blnResult == true; j++)
	{
		strChar = strString.charAt(j);
		if (strValidChars.indexOf(strChar) == -1)
		{
			blnResult = false;
		}
	}
	return blnResult;
}

function removeSpaces(string)
{
	var tstring = "";
	string = '' + string;
	splitstring = string.split(" ");
	for(k=0; k < splitstring.length; k++)
	{
		tstring += splitstring[k];
	}
	return tstring;
}

function toggleElement(elementID)
{
	if(document.getElementById(elementID).style.display=='none')
	{
		document.getElementById(elementID).style.display='inline';
	}
	else
	{
		document.getElementById(elementID).style.display='none';
	}
}

function hideElement(elementID)
{
	document.getElementById(elementID).style.display='none';
}

function showElement(elementID)
{
	document.getElementById(elementID).style.display='';
}

function pageTypeChanged()
{
	if(document.getElementsByName('page_type')[0].checked==true)
	{
		showElement('content_element');
		hideElement('redirect_to_element');
		hideElement('external_redirect_to');
		showElement('page_advanced_options_container');
	}
	else if(document.getElementsByName('page_type')[1].checked==true)
	{
		hideElement('content_element');
		hideElement('redirect_to_element');
		hideElement('external_redirect_to');
		hideElement('page_advanced_options_container');
	}
	else if(document.getElementsByName('page_type')[2].checked==true)
	{
		hideElement('content_element');
		showElement('redirect_to_element');
		hideElement('page_advanced_options_container');
		redirectTypeChanged();
	}
}

function redirectTypeChanged()
{
	if(document.getElementById('redirect_to').value=="external_link")
	{
		showElement('external_redirect_to');
	}
	else
	{
		hideElement('external_redirect_to');
	}
}

function menuChoiceChanged()
{
	if(document.getElementsByName('menu_display_choice')[0].checked==true)
	{
		showElement('main_menu_extra');
		hideElement('sub_menu_extra');
		hideElement('not_in_menu_extra');
	}
	else if(document.getElementsByName('menu_display_choice')[1].checked==true)
	{
		hideElement('main_menu_extra');
		showElement('sub_menu_extra');
		hideElement('not_in_menu_extra');
	}
	else if(document.getElementsByName('menu_display_choice')[2].checked==true)
	{
		hideElement('main_menu_extra');
		hideElement('sub_menu_extra');
		showElement('not_in_menu_extra');
	}
}

function memberAccessTypeChanged()
{
	if(document.getElementById('member_access_type').value=="member_groups")
	{
		showElement('member_groups_div');
		hideElement('members_div');
	}
	else if(document.getElementById('member_access_type').value=="specific_members")
	{
		showElement('members_div');
		hideElement('member_groups_div');
	}
	else
	{
		hideElement('member_groups_div');
		hideElement('members_div');
	}
}

function allowPageCommentsChanged()
{
	if(document.getElementById('allow_comments').checked==false)
	{
		hideElement('page_comments_div');
	}
	else
	{
		showElement('page_comments_div');
	}
}

function togglePageAdvancedOptions()
{
	if(document.getElementById('page_advanced_options').style.display=='none')
	{
		document.getElementById('page_advanced_options').style.display='inline';
		document.getElementById('page_advanced_options_link').innerHTML='Hide &laquo;&laquo;';
	}
	else
	{
		document.getElementById('page_advanced_options').style.display='none';
		document.getElementById('page_advanced_options_link').innerHTML='Show &raquo;&raquo;';
	}
}

function cartProductPricingTypeChanged()
{
	if(document.getElementsByName('pricing_type')[0].checked==true)
	{
		showElement('single_pricing_element');
		hideElement('multiple_pricing_element');
	}
	else
	{
		showElement('multiple_pricing_element');
		hideElement('single_pricing_element');
	}
}

function cartProductPostagePricingTypeChanged()
{
	if(document.getElementsByName('postage_pricing_type')[0].checked==true)
	{
		hideElement('custom_postage_pricing_element');
	}
	else
	{
		showElement('custom_postage_pricing_element');
	}
}

function cartProductCustomFieldsChanged()
{
	if(document.getElementsByName('product_has_custom_fields')[0].checked==true)
	{
		hideElement('cart_product_custom_fields_element');
	}
	else
	{
		showElement('cart_product_custom_fields_element');
	}
}

function cartProductCustomFieldsInit(total_custom_field_count)
{
	//first work out the last custom field that is in use

	tmp_last_custom_field_in_use=0;

	for(ii=1;ii<=total_custom_field_count;ii++)
	{
		if(document.getElementById('product_custom_field_name_'+ii).value!='')
		{
			tmp_last_custom_field_in_use=ii;
		}
	}

	//set last custom field to show to current number plus 3
	tmp_last_custom_field_to_show=tmp_last_custom_field_in_use+3;

	//check we haven't maxed out above total_custom_field_count
	if(tmp_last_custom_field_to_show>total_custom_field_count)
	{
		tmp_last_custom_field_to_show=total_custom_field_count;
	}

	//now cycle through custom fields and hide ones above tmp_last_custom_field_to_show
	for(ii=1;ii<=total_custom_field_count;ii++)
	{
		if(ii>tmp_last_custom_field_to_show)
		{
			document.getElementById('cart_product_custom_field_element_'+ii).style.display='none';
		}
	}

	//if we are showing all fields, then we need to hide the more button
	if(tmp_last_custom_field_to_show==total_custom_field_count)
	{
		document.getElementById('cart_product_custom_fields_show_all').style.display='none';
	}
}
function cartProductCustomFieldsShowAll(total_custom_field_count)
{
	//cycle through custom fields and show them all
	for(ii=1;ii<=total_custom_field_count;ii++)
	{
		document.getElementById('cart_product_custom_field_element_'+ii).style.display='';
	}

	//hide show more button
	document.getElementById('cart_product_custom_fields_show_all').style.display='none';
}

function blogCategoryEnableArchivingChanges()
{
	if(document.getElementById('enable_archiving').checked==true)
	{
		showTableRows('table_section_archive_settings');
	}
	else
	{
		hideTableRows('table_section_archive_settings');
	}
}

function validatePageAddEditForm(standardValidationRules)
{
	var page_add_edit_form_ok=true;

	customAlerts=Array();
	//if redirect option is selected AND dropdown is set to external redirect AND external redirect textbox is empty, then don't allow submit
	if(document.getElementsByName('page_type')[2].checked==true && document.getElementById('redirect_to').value=="external_link" && document.getElementById('external_redirect_to').value=="")
	{
		customAlerts[0]='You have selected the option to redirect this page to an external website. Please enter the URL of the website you wish to redirect to.';
	}

	if(validateForm(standardValidationRules,customAlerts)==false)
	{
		page_add_edit_form_ok=false;
	}

	return page_add_edit_form_ok;

}

function validateCartProductAddEditForm(standardValidationRules)
{
	var cart_product_add_edit_form_ok=true;
	var cart_product_category_selected=false;
	cart_product_add_edit_form=document.getElementById('cart_product_form');

	for(tmp_form_elements=0;tmp_form_elements<cart_product_add_edit_form.length;tmp_form_elements++)
	{
		tmp_form_element_name=cart_product_add_edit_form[tmp_form_elements].name;
		tmp_form_element_type=cart_product_add_edit_form[tmp_form_elements].type;

		if(tmp_form_element_name.indexOf('category_')==0 && tmp_form_element_type=='checkbox')
		{
			if(cart_product_add_edit_form[tmp_form_elements].checked==true)
			{
				cart_product_category_selected=true;
			}
		}
	}

	customAlerts=Array();
	if(cart_product_category_selected==false)
	{
		customAlerts[0]='Please select at least one category for this product.';
	}

	if(validateForm(standardValidationRules,customAlerts)==false)
	{
		cart_product_add_edit_form_ok=false;
	}

	return cart_product_add_edit_form_ok;

}

function cartDiscountTypeChanged()
{
	if(document.getElementById('discount_type').value=="percentage")
	{
		showElement('discount_percentage_tbody');
		hideElement('discount_dollar_amount_tbody');
	}
	else if(document.getElementById('discount_type').value=="dollar_amount")
	{
		showElement('discount_dollar_amount_tbody');
		hideElement('discount_percentage_tbody');
	}
	else
	{
		hideElement('discount_dollar_amount_tbody');
		hideElement('discount_percentage_tbody');
	}
}

function cartDiscountCriteriaTypeChanged()
{
	if(document.getElementById('criteria_type').value=="dollar_amount")
	{
		showElement('criteria_dollar_amount_tbody');
		hideElement('criteria_product_count_tbody');
	}
	else if(document.getElementById('criteria_type').value=="product_count")
	{
		showElement('criteria_product_count_tbody');
		hideElement('criteria_dollar_amount_tbody');
	}
	else
	{
		hideElement('criteria_product_count_tbody');
		hideElement('criteria_dollar_amount_tbody');
	}
}

function cartDiscountCodeRequiredChanged()
{
	if(document.getElementById('discount_code_required').value=="Y")
	{
		showElement('discount_code_div');
	}
	else
	{
		hideElement('discount_code_div');
	}
}

function cartDiscountValidFromDateTypeChanged()
{
	if(document.getElementById('valid_from_date_type').value=="use_date")
	{
		showElement('valid_from_date_span');
	}
	else
	{
		hideElement('valid_from_date_span');
	}
}

function cartDiscountValidToDateTypeChanged()
{
	if(document.getElementById('valid_to_date_type').value=="use_date")
	{
		showElement('valid_to_date_span');
	}
	else
	{
		hideElement('valid_to_date_span');
	}
}

function cartCheckoutSettingsCustomFieldTypeChanged(field_number)
{
	if(document.getElementById('cart_checkout_custom_field_'+field_number+'_type').value=='dropdown')
	{
		document.getElementById('cart_checkout_custom_field_'+field_number+'_options_container').style.display='';
	}
	else
	{
		document.getElementById('cart_checkout_custom_field_'+field_number+'_options_container').style.display='none';
	}

}

function isInternetExplorer()
{
	var detect = navigator.userAgent.toLowerCase();
	pos = detect.indexOf('msie') + 1;
	return pos;
}

function watermarkCheckboxChanged()
{
	if(document.getElementById('use_watermark').checked)
	{
		showTableRows('watermark_options');
	}
	else
	{
		hideTableRows('watermark_options');
	}
}

function hideTableRows(elementID)
{
	document.getElementById(elementID).style.display='none';
}

function showTableRows(elementID)
{
	if(isInternetExplorer())
	{
		document.getElementById(elementID).style.display='inline';
	}
	else
	{
		document.getElementById(elementID).style.display='table-row-group';
	}
}
