/*
	Common JS functions
*/


//Adv Search scripts
function advsearch_subs(obj) {
	if (obj.value != "") {
		document.getElementById("adv_search_options_subs").className="";
		document.getElementById("adv_subcat").disabled = false;
		document.getElementById("adv_man").disabled = false;

		makeRequest(obj.value);


	} else {
		document.getElementById("adv_search_options_subs").className="hide";
		document.getElementById("adv_subcat").disabled = true;
		document.getElementById("adv_man").disabled = true;
	}

}




var div = document.getElementById('container');

var handleSuccess = function(o){
	if(o.responseXML !== undefined){

		//Select tag (subcats) to be created
		if (document.getElementById("adv_subcat")) {
			var el_select = document.getElementById("adv_subcat");
			el_select.parentNode.removeChild(el_select);
		}
	    var el_select = document.createElement("select");
		el_select.setAttribute('name', 's');
		el_select.setAttribute('id', 'adv_subcat');


		//Setup default <option>
		option = document.createElement('option');
    	option.setAttribute('value', "");
    	option_value = document.createTextNode('- All Subcategories -');
    	option.appendChild(option_value);
    	el_select.appendChild(option);

    	//Select tag (mans) to be created
		if (document.getElementById("adv_man")) {
			var el_select_mans = document.getElementById("adv_man");
			el_select_mans.parentNode.removeChild(el_select_mans);
		}
	    var el_select_mans = document.createElement("select");
		el_select_mans.setAttribute('name', 'm');
		el_select_mans.setAttribute('id', 'adv_man');

		//Setup default <option>
		option = document.createElement('option');
    	option.setAttribute('value', "");
    	option_value = document.createTextNode('- All Manufacturers -');
    	option.appendChild(option_value);
    	el_select_mans.appendChild(option);





		//Load XML Document
	    var root = o.responseXML.documentElement;

		//Loop through XML to generate new <select> dropdowns for (subs)
		var children = root.getElementsByTagName("subcat");
	    for (j=0; j<children.length; j++) {
	    	option = document.createElement('option');
	    	option.setAttribute('value', children[j].getElementsByTagName('subid')[0].firstChild.nodeValue);
	    	option_value = document.createTextNode(children[j].getElementsByTagName('subname')[0].firstChild.nodeValue);
	    	option.appendChild(option_value);
	    	el_select.appendChild(option);
	    }

	    //Loop through XML to generate new <select> dropdowns for (mans)
		var children = root.getElementsByTagName("man");
	    for (j=0; j<children.length; j++) {
	    	option = document.createElement('option');
	    	option.setAttribute('value', children[j].getElementsByTagName('manid')[0].firstChild.nodeValue);
	    	option_value = document.createTextNode(children[j].getElementsByTagName('manname')[0].firstChild.nodeValue);
	    	option.appendChild(option_value);
	    	el_select_mans.appendChild(option);
	    }

	    //Add new <select> dropdowns to page
	    document.getElementById("subcatsgohere").appendChild(el_select);
	    document.getElementById("mansgohere").appendChild(el_select_mans);
	}
}

var handleFailure = function(o){
	if(o.responseText !== undefined){
	}
}

var callback = {
  success:handleSuccess,
  failure:handleFailure
}

function makeRequest(catid){
	var sUrl = "/ajax/get?action=advsearch&catid=" + catid;
	var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);
}





/* ------- General scripts --------------------------------------------------------------------------------------------------- */

//Confirm user action
function confirm_action(msg) {
	if (confirm(msg)) {
		return true;
	} else {
		return false;
	}
}

//Confirm user action then redirect to new url
function confirm_location(msg,url) {
	if (confirm(msg)) {
		window.location = url;
	} else {
		return false;
	}
}

//Add Firefox search engine
/*function addEngine(name,ext,cat,type)
{
    if ((typeof window.sidebar == "object") && (typeof window.sidebar.addSearchEngine == "function")) {
        window.sidebar.addSearchEngine(
            "http://localhost/download/search/"+name+".src",
            "http://localhost/download/search/"+name+"."+ext, name, cat
        );
    } else {
        alert("Sorry, you need a Mozilla-based browser to install a search plugin.");
    }
}*/

//Open popup window
function popup_win (url) {
	newwindow=window.open(url,'name','width=600,height=400,resizable=yes');
	if (window.focus) {newwindow.focus()}
//	return false;
}

/* ------- Validation ------------------------------------------------------------------------------------------------------------- */

//Check search term entered is valid length
function validate_search(objform) {
	var searchterm = objform.q;
	var success = _strlen(searchterm.value,0,30);

	if (success == false) {
		alert("Search term must be between 1 and 30 characters long");
		searchterm.focus();
		return false;
	}
}


//Validate details of advanced search
function validate_search_adv(objform) {
	return true;
}


//Validate login details are complete before submitting
function validate_login(login_form) {
	if (!_email(login_form.log_email.value)) {
		alert("Email address is invalid, please try again.");
		login_form.log_email.focus();
		login_form.log_email.select();
		return false;
	} else if (login_form.log_password.value == "") {
		alert("Password cannot be left blank, please enter a password.");
		login_form.log_password.focus();
		return false;
	}
	return true;
}




//Validate Forgot Password email address
function validate_forgot(login_form) {
	if (!_email(login_form.log_email.value)) {
		alert("Email address is invalid, please try again.");
		login_form.log_email.focus();
		login_form.log_email.select();
		return false;
	}
	return true;
}




//Validate product Enquiry (from main product pages)
function validate_prod_enq() {
	var cname = document.getElementById("cust_name");
	var email = document.getElementById("cust_eml");
	var cenq  = document.getElementById("cust_enquiry");
	var scode = document.getElementById("captcha_code");
	var msg   = "";
  var err = false;

	if (!_strlen(cname.value,1,40)) {
		msg = "You must provide your name.";
		cname.focus();
		err = true;
	}
	if (!err && !_email(email.value)) {
		msg += "\nYou must provide a valid email address for us to respond to your enquriy.";
		email.focus();
		err = true;
	}
	if (!err && !_strlen(cenq.value,1,2000)) {
		if (cenq.value.length > 2000) {
			msg = "The comments or questions you have written appear to be too long to be sent by email. You will need to call us to discuss your product enquiries.";
		} else {
			msg += "\nPlease enter your questions or comments.";
		}
		cenq.focus();
	}
	if (!err && !_strlen(scode.value,1,8)) {
		msg = "Security code is invalid.";
		scode.focus();
		err = true;

	}
	if (msg) {
		alert(msg);
		return false;
	} else {
		return true;
	}
}








//Return an array of elements with a specific class
//Dustin Diaz - http://www.dustindiaz.com/getelementsbyclass/
function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}


//Show/hide 'customer correspondence' on quote/warranty pages
function show_hide_div(action,divid) {
	var new_class = (action == 1) ? "hide" : "";

	document.getElementById(divid).className = "customer_correspondence " + new_class;

	if (new_class == "hide") {
		document.getElementById(divid+"_show").className = "";
		document.getElementById(divid+"_hide").className = "hide";
	} else {
		document.getElementById(divid+"_show").className = "hide";
		document.getElementById(divid+"_hide").className = "";
	}
}



//Show/hide 'customer correspondence' on quote/warranty pages
function show_hide_this_div(cur,elid,extra) {
	var eltohide = document.getElementById(elid);
	var new_class = (eltohide.className == "hide") ? "" : "hide";

	eltohide.className = new_class;

	if (new_class == "hide") {
		cur.innerHTML = "Show "+extra;
	} else {
		cur.innerHTML = "Hide "+extra;
	}
}






//Show full description for payment/delivery checkout pages
function delivery_method(divid) {
	var cur_class = document.getElementById(divid).className;
	var new_class = (cur_class == "delivery_method_hide") ? "delivery_method_show" : "delivery_method_hide";
	var new_link  = (cur_class == "delivery_method_hide") ? "Hide" : "Show";

	document.getElementById(divid).className = new_class;
	document.getElementById(divid+"_link").innerHTML = new_link +" Full Description";

}

//Switch description layers for payment/delivery checkout pages
function switch_layers( displayLayerName) {
	if ( document.getElementById ) {
		for (i = 0; i<layers.length; i++) {
			var obj_layer = document.getElementById( layers[i] );
			if (layers[i] == displayLayerName) {
				obj_layer.className = "checkout_delivery_options";
			} else {
				obj_layer.className = "checkout_delivery_options hide";
			}
		}
	}
}



/*
// ------- Checkout functions ---------------------------------------------------------------------------------------------------
<script type="text/javascript">
	<!--//
	//Validates the quote only fields to ensure the customer has submitted proper requirements for their quote
	function validateQuoteForm(frm){
		var error = false;
		var msg = "";

		//Have they selected at least one action request?
		var chkName = "fld_questions[]";
		len = frm.elements.length;
		var i=0;
		var countdropdowns = 0;
		for( i=0 ; i<len ; i++) {
			if ((frm.elements[i].name==chkName) && (frm.elements[i].checked==1))
				countdropdowns++;
		}
		if (countdropdowns == 0) {
			msg += "Please select at least one Action Request for this quote.\n\n";
			error = true;
		}

		//Have they entered a timeframe estimate for this quote?
		if (document.checkout_form.fld_order_eta.value == "") {
			msg += "Please enter an approximate timeframe for when you would purchase this quote.\n\n";
			error = true;
		}

		//Does the custom need to enter 'other comments' if they ticked the 'Other Requests' checkbox?
		if (document.getElementById('id_other').checked == true) {
			if (document.checkout_form.fld_comments.value.length < 5) {
				msg += "Please elaborate on what other requests you may have for this quote.\n\n";
				error = true;
			}
		}

		if (error == true) {
			alert(msg)
			return false;
		} else
			return true;
	}

	-->
</script>



*/



// ------- Standard Validation Subfunctions -------------------------------------------------------------------------------------
//currency
function _cash(Curr) {
    return /^\d{1,3}(,\d{3})*\.\d\d$|^\d+\.\d\d$/.test(Curr);
}
//within min/max string length
function _strlen(Curr,minvalue,maxvalue) {
    return (Curr.length > minvalue && Curr.length < maxvalue);
}
//number
function _isnum(St) {
    return !/\D/.test(St);
}

//Email validation
function _email(email) {
	invalid_chars = " /:,;"
	if (email == "") {
		return false;
	}
	// Check for invalid characters
	for (i=0; i<invalid_chars.length; i++) {
		badChar = invalid_chars.charAt(i)
		if (email.indexOf(badChar, 0) > -1) {
			return false;
		}
	}
	// Validate @ sign
	at_pos = email.indexOf("@", 1)
	if (at_pos == -1) {
		return false;
	}
	if (email.indexOf("@", at_pos+1) > -1) {
		return false;
	}
	// Validate dots
	period_pos = email.indexOf(".", at_pos)
	if (period_pos == -1) {
		return false;
	}
	if (period_pos+3 > email.length) {
		return false;
	}
	return true;
}

// Determine Bill State according to postcode when customer registering an account.
function check_state(){
	postcode = document.getElementsByName('fld_bill_postcode')[0].value;
	if (postcode <= 3200 && postcode >= 3000){
		document.getElementsByName('fld_bill_state')[0].value = "VIC-METROPOLITAN";
	}
	else if (postcode >3200 && postcode <= 3999) {
		document.getElementsByName('fld_bill_state')[0].value = "VIC-COUNTRY";
	}

}

// ------------------------------------------------------------------------------------------------------------------------------

/*
//Get value of radio buttons
function _getCheckedValue(radioObj) {
	if(!radioObj)
		return false;
	user_input = false;

	for (i=0; i<radioObj.length; i++) {
		if (radioObj[i].checked) {
			user_input = radioObj[i].value;
		}
	}
	return user_input;
}
*/
//JS equivelant of PHP's in_array() function
Array.prototype.find = function (s) {
	for(var i=0;i<this.length;i++)
		if(this[i] == s) return true;
		return false;
};



// ------- Account functions -----------------------------------------------------------------------------------------------------
function account_ccv_submit_check(form) {
	if (form.fld_verify_amount.value==0 || form.fld_verify_amount.value=='') {
		alert("Amount is not entered, please try again!!");
		form.fld_verify_amount.focus();
		form.fld_verify_amount.select();
		return false;
	}
	else {
		return confirm('Are you sure the amount you have entered is correct? Once submitted, there is NO retry.');
	}

}

/*
 * $Log: common.js,v $
 * Revision 1.4  2006/09/14 00:35:51  edward
 * Add function state_check to check bill state in customer registration.
 *
 * Revision 1.3  2006/08/15 04:15:19  edward
 * Mod popup_win function so the window is resizable and remove "return false"
 *
 *
 *
 *
 * Logic Flow (c) 2004 - www.logicflow.com.au
 *
 */
 
