// Browser detection

	var isDOM = document.getElementById;
	var isOpera = window.opera && isDOM;
	var isOpera5 = isOpera;
	var isOpera6 = isOpera && window.print;
	var isOpera7 = isOpera && document.readyState;
	var isMSIE = document.all && document.all.item && !isOpera;
	var isMSIE5 = isDOM && isMSIE;
	var isNetscape4 = document.layers;
	var isMozilla = isDOM && navigator.appName=='Netscape';

// Alert

	var alertFound = false;

// Validator Object

	var valid = new Object();

// REGEX Elements

	// matches digits only
	valid.Number = /^\d+$/;

	// matches letters only
	valid.Letter = /^[^0-9]+$/;

	// matches zip codes
	valid.zipCode = /^\d{5}$/;

	// matches CA zip codes
	valid.zipCodeCA = /^[A-CEGHJ-NPR-TV-Z]\d[A-CEGHJ-NPR-TV-Z]\s?\d[A-CEGHJ-NPR-TV-Z]\d$/i;

	// matches UK zip codes
	valid.zipCodeUK = /^\s*(GIR(\s?)0AA|BFPO(\s?)(c(\/?)o(\s?)|)[0-9]{1,4}|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])(\s?)[0-9][ABD-HJLNP-UW-Z]{2})\s*$/i;

	// matches year (4 digits)
	valid.Year = /(19|20){1}\d{2}/;

	// Date xxxx/xx/xx  || Date xxxx-xx-xx
	valid.Date = /^\d{4}(\-|\/|\.|\s)\d{2}(\-|\/|\.|\s)\d{2}$/;

	// Social Security Number
	valid.SSN = /^\d{3}(\s|-|\.)?\d{2}(\s|-|\.)?\d{4}$/;

	// matches US phone ###-###-####
	valid.phoneNumber = /^\(?\d{3}\)?(\s|-|\.)?\d{3}(\s|-|\.)?\d{4}$/;

	//matches email
	valid.emailAddress = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/;

	// International Phone Number
	valid.phoneNumberInt = /^\+(\d){1,5}(\s|-|\.)?(\d|\s|-|\.){7,25}/;

	// matches 11.34 or 15,234,566.83 ...
	valid.Currency = /^\d{1,3}(,\d{3})*(\.\d{2}){0,1}$/;

	// profane language filter
	var profaneWords = new Array(/(shit|nerd|stupid|ass|cunt|suck|pussy|cock|cum|penis|nuts|dick|fuck|ass|fag|idiot|asshole|bitch|gimp|freak)+/gi,/([^\s])(\1){3,}/gi,/([^\s]{2,})(\s*)?(\1(\s*)?){2,}/gi);
    
//V2.01.A - http://www.openjs.com/scripts/jx/
    var jx = {
        http:false, //HTTP Object
        format:'text',
        callback:function(data){},
        handler:false,
        error: false,
        opt:new Object(),
        //Create a xmlHttpRequest object - this is the constructor. 
        getHTTPObject : function() {
            var http = false;
            //Use IE's ActiveX items to load the file.
            if(typeof ActiveXObject != 'undefined') {
                try {http = new ActiveXObject("Msxml2.XMLHTTP");}
                catch (e) {
                    try {http = new ActiveXObject("Microsoft.XMLHTTP");}
                    catch (E) {http = false;}
                }
            //If ActiveX is not available, use the XMLHttpRequest of Firefox/Mozilla etc. to load the document.
            } else if (window.XMLHttpRequest) {
                try {http = new XMLHttpRequest();}
                catch (e) {http = false;}
            }
            return http;
        },
        // This function is called from the user's script. 
        //Arguments - 
        //    url    - The url of the serverside script that is to be called. Append all the arguments to 
        //            this url - eg. 'get_data.php?id=5&car=benz'
        //    callback - Function that must be called once the data is ready.
        //    format - The return type for this function. Could be 'xml','json' or 'text'. If it is json, 
        //            the string will be 'eval'ed before returning it. Default:'text'
        //    method - GET or POST. Default 'GET'
        load : function (url,callback,format,method) {
            this.init(); //The XMLHttpRequest object is recreated at every call - to defeat Cache problem in IE
            if(!this.http||!url) return;
            //XML Format need this for some Mozilla Browsers
            if (this.http.overrideMimeType) this.http.overrideMimeType('text/xml');

            this.callback=callback;
            if(!method) var method = "GET";//Default method is GET
            if(!format) var format = "text";//Default return type is 'text'
            this.format = format.toLowerCase();
            method = method.toUpperCase();
            var ths = this;//Closure
            
            //Kill the Cache problem in IE.
            var now = "uid=" + new Date().getTime();
            url += (url.indexOf("?")+1) ? "&" : "?";
            url += now;

            var parameters = null;

            if(method=="POST") {
                var parts = url.split("\?");
                url = parts[0];
                parameters = parts[1];
            }
            this.http.open(method, url, true);

            if(method=="POST") {
                this.http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                this.http.setRequestHeader("Content-length", parameters.length);
                this.http.setRequestHeader("Connection", "close");
            }

            if(this.handler) { //If a custom handler is defined, use it
                this.http.onreadystatechange = this.handler;
            } else {
                this.http.onreadystatechange = function () {//Call a function when the state changes.
                    if(!ths) return;
                    var http = ths.http;
                    if (http.readyState == 4) {//Ready State will be 4 when the document is loaded.
                        if(http.status == 200) {
                            var result = "";
                            if(http.responseText) result = http.responseText;
                            //If the return is in JSON format, eval the result before returning it.
                            if(ths.format.charAt(0) == "j") {
                                //\n's in JSON string, when evaluated will create errors in IE
                                result = result.replace(/[\n\r]/g,"");
                                result = eval('('+result+')');

                            } else if(ths.format.charAt(0) == "x") { //XML Return
                                result = http.responseXML;
                            }

                            //Give the data to the callback function.
                            if(ths.callback) ths.callback(result);
                        } else {
                            if(ths.opt.loadingIndicator) document.getElementsByTagName("body")[0].removeChild(ths.opt.loadingIndicator); //Remove the loading indicator
                            if(ths.opt.loading) document.getElementById(ths.opt.loading).style.display="none"; //Hide the given loading indicator.
                            
                            if(ths.error) ths.error(http.status);
                        }
                    }
                }
            }
            this.http.send(parameters);
        },
        init : function() {this.http = this.getHTTPObject();}
    }

function isValidOffer(form)
{
 ret = true;
 
 country_field = 'country';
 if (typeof(form['dm[!country]'])!='undefined') 
 {
    field_name = 'user[' + form['dm[!country]'].value + ']';
    if (typeof(form[field_name])!='undefined') 
    {
        country_field = field_name;
    }
 }        
 
 if (typeof(form['form_rules'])!='undefined')
 {
        f = form['form_rules'].value.split(';');
        for (i=0, iCnt=f.length; i< iCnt; i++)
        {

		arr = f[i].split(',');
		fId = arr[0];
		fBlType = arr[1];
		fType = arr[2];
		fRequired = arr[3];
		fFunc = arr[4];
		fComplex = arr[5];
		title=dId('descr['+fId+']')
                if (title)
                {
                	title.className = 'Qtitle';
		}

		if (fFunc && typeof(form[country_field])!='undefined')
		{
			caption = error_str[fId].substr(0,error_str[fId].indexOf("Format"));
            country = form[country_field].value; 
            switch(fFunc)
			{
				case 'isZip':
					switch(country)
					{
						case 'US':
							fFunc = 'isZip';
							error_str[fId] = caption + 'Format: valid five-digit ZIP code';
							break;
						case 'CA':
							fFunc = 'isZipCA';
							error_str[fId] = caption + 'Format: valid CA postal code';
							break;
						case 'UK':
							fFunc = 'isZipUK';
							error_str[fId] = caption + 'Format: valid UK postcode';
							break;
						default:
							fFunc = '';
							break;
					}
                			break;
				case 'isPhone':
					switch(country)
					{
						case 'US':
						case 'CA':
							fFunc = 'isPhone';
							error_str[fId] = caption + 'Format: xxx xxx xxxx';
							break;
						case 'UK':
							fFunc = 'isPhoneUK';
							error_str[fId] = caption + 'Format: 0xx xxxx xxxx';
							break;
						default:
							fFunc = 'isIntPhone';
							error_str[fId] = caption + 'Format: +xxx xxx xxx xxxx';
							break;
					}
                			break;
			}
		}

        fieldName = 'user['+fId+']';
        if ((typeof(form[fieldName])=='undefined') && (fType!='COMPLEX')) {
            if (typeof(form[fieldName+'[]'])!='undefined') {
                fieldName += '[]'; // multiselect
            }
        }
        
        fieldOk = true;
		if (((typeof(form[fieldName])!='undefined' && !isHidden(form[fieldName])) || fType=='COMPLEX') && typeof(dont_check[fId])=='undefined')
		{
            // If 'hphone' field is empty, then check whether 'mphone' field is present and filled in
    		if (fBlType == '!hphone' && form[fieldName].value == '') {
    		    if (!form['user[MPHONE]'] || isHidden(form['user[MPHONE]']) || form['user[MPHONE]'].type == 'hidden') {
    		        // the 'mphone' field is hidden, continue the validation
    		    } else if (form['user[MPHONE]'].value == '') {
    		        // the 'mphone' field is shown, but empty, continue the validation
    		    } else {
    		        // the 'mphone' field is shown and not empty, skipping the validation
    		        continue;
    		    }
    		}
			switch(fType)
			{
                		case 'TEXT':
		       			if (form[fieldName].value=='' && fRequired=='yes')
		       			{
						fieldOk = false;
		       			}
					if (fFunc && !(form[fieldName].value=='' && fRequired=='no'))
					{
						try
						{
						        fieldOk = eval(fFunc+'("' + form[fieldName].value + '")');
							if ((fFunc=='isPhone' || fFunc=='isPhoneUK') && fieldOk) form[fieldName].value = fieldOk;
						}
						catch (e)
						{
						}

					}
                			break;
                		case 'SELECT':
		       			if (form[fieldName].selectedIndex==0 && fRequired=='yes')
		       			{
						fieldOk = false;
		       			}
                			break;
		       		case 'TEXTAREA':
		       			if (form[fieldName].value=='' && fRequired=='yes')
		       			{
						fieldOk = false;
		       			}
                			break;
		       		case 'COMPLEX':
		       			if (fRequired=='yes' && fComplex)
		       			{
       			                        arr = fComplex.split(':');
       			                        for (j=0; j< arr.length; j++)
       			                        {
					      		if (typeof(form['user['+fId+']['+arr[j]+']'])!='undefined')
					      		{
								switch(form['user['+fId+']['+arr[j]+']'].tagName)
								{
					                		case 'TEXT':
					                		case 'TEXTAREA':
							       			if (form['user['+fId+']['+arr[j]+']'].value==''  && !isHidden(form['user['+fId+']['+arr[j]+']']))
							       			{
											fieldOk = false;
							       			}
					                			break;
					                		case 'SELECT':
							       			if (form['user['+fId+']['+arr[j]+']'].selectedIndex==0  && !isHidden(form['user['+fId+']['+arr[j]+']']))
							       			{
											fieldOk = false;
							       			}
					                			break;
								}
					      		}
       			                        }
		       			}
                			break;
			}
		}
		
		if (typeof(form['user[zip]']) != 'undefined') {
    		if ((fieldName == 'user[State]' || fieldName == 'user[City]') && form['user[zip]'].value != '') {
    		    fieldOk = true;
    		}		    
		}

		if (!fieldOk)
		{
 		        ret = false;
			title=dId('descr['+fId+']');
			if (title)
			{
		               	title.className = 'Qerror';
			}
			if (typeof(error_str)!='undefined' && typeof(error_str[fId])!='undefined')
			{
			        if (!alertFound)
			        {
					alert(error_str[fId]);
				}
				alertFound = true;
			}
		}
        }
 }
 return ret;

}

function submitOffer(form)
{
	if (typeof(form['clicks'])!='undefined')
	{
		form['clicks'].value++;
	}
	alertFound = false;
	if (isValidOffer(form))
	{
		if (typeof(EVafterSuccessSubmit)=='function')
		{
			if (EVafterSuccessSubmit()==false)
			{
				return false;
			}
		}
		form['resultCode'].value = form['position'].value;
		if (typeof(exitURL)!='undefined' && exitURL)
		{
			exitURL = false;
		}
		form.submit();
	}
	else
	{
		form['resultCode'].value = 0;
		if (!alertFound)
		{
			alert('You need to answer all the required questions.');
		}
	}
	return true;
}

function updateOffer(form)
{
	form['resultCode'].value = form['position'].value;
	if (typeof(exitURL)!='undefined' && exitURL)
	{
		exitURL = false;
	}
	form.submit();
	return true;
}


function passOffer(form, skip_to_offers)
{
    if (skip_to_offers) {
        form['offerID'].value = 0;
    }
    
	form['resultCode'].value = 0;
    if (typeof(exitURL)!='undefined' && exitURL)
	{
		exitURL = false;
	}
	form.submit();
}



function isHidden(elem)
{
	if (typeof(elem)=='undefined' || typeof(elem.style)=='undefined')
	{
		return false;
	}
	else if (elem.style.display == 'none' || elem.style.visibility == 'hidden')
 	{
		return true;
	}
	else
	{
		if (elem.parentNode)
		{
			return isHidden(elem.parentNode,name);
		}
		else
		{
			return false;
		}
	}
}

function getParentElement(elem,name)
{
	if (typeof(elem)=='undefined')
	{
		return false;
	}
	else if (elem.tagName == name)
 	{
		return elem;
	}
	else
	{
	  if (elem.parentNode)
	  {
			return getParentElement(elem.parentNode,name);
		}
		else
		{
			return false;
		}
	}
}

function createHiddenField(form,elemName,value)
{
	var fo;
	if (isMSIE)
	{
		fo = document.createElement('<input type=hidden name='+elemName+'>');
	}
	else if (isDOM)
	{
		fo = document.createElement('input');
		fo.name = elemName;
		fo.type = 'hidden';
	}
	fo.value = value;
	form.appendChild(fo);
	return fo;
}

function dId(id)
{
        if (typeof(document.getElementById(id))!='undefined')
        {
		return document.getElementById(id);
	}
	return false;
}

function isCurrency(value)
{
	return valid.Currency.exec(value);
}

function isNumber(value)
{
	return valid.Number.exec(value);
}

function isLetter(value)
{
	return valid.Letter.exec(value);
}

function isZip(value)
{
	return valid.zipCode.exec(value);
}

function isZipCA(value)
{
	return valid.zipCodeCA.exec(value);
}

function isZipUK(value)
{
	return valid.zipCodeUK.exec(value);
}

function isSSN(value)
{
	return valid.SSN.exec(value);
}

function isEmail(value)
{
	return valid.emailAddress.exec(value);
}


function isPhone(phone)
{
	phone = phone.toLowerCase();
	var pieces=phone.split('x');
	if (typeof(pieces[0])=='undefined') return false;
	phone = extractNumbers(pieces[0]);
	if (phone.length < 10) return false;
	if (typeof(pieces[0])!='undefined' && pieces[1]) ext = extractNumbers(pieces[1]); else ext='';
	return phone.substr(phone.length-10,3) + ' ' + phone.substr(phone.length-7,3) + ' ' + phone.substr(phone.length-4,4) + (ext.length > 0 ? ' x' + ext : '');

}

function isPhoneUK(phone)
{
	phone = extractNumbers(phone.toLowerCase());
	if (phone.length == 10 && phone[0]!=0) phone = '0' + phone;
	if (phone.length < 11) return false;
	return phone.substr(phone.length-11,3) + ' ' + phone.substr(phone.length-8,4) + ' ' + phone.substr(phone.length-4,4);
}

function isIntPhone(value)
{
	return valid.phoneNumberInt.exec(value);
}

function isDate(value)
{
	return valid.Date.exec(value);
}

function isYear(value)
{
	return valid.Date.exec(value);
}

function isProfaneLexicon(value)
{
	value = trim(value);
	if (value!='')
	{
		for (var i = 0, iCnt = profaneWords.length; i < iCnt; i++)
		{
			if (value.search(profaneWords[i])!=-1)
			{
				matches = value.match(profaneWords[i]);
				alert('Please refrain from using the word \"'+matches[0].replace(/[\r\n]/gi,'') +'\"');
				return true;
			}
		}
	}
	return false;
}

function extractNumbers(str)
{
	return str.replace(/[^\d]/g,'');
}

function switchOptIn(id)
{
	id = 'user['+id+']';
	if (dId(id+'_yes').checked)
	{
		dId(id+'_yes').checked = false;
		dId(id+'_no').checked = true;
	}
	else
	{
		dId(id+'_yes').checked = true;
		dId(id+'_no').checked = false;
	}
}

function trim(s) {
    var start_trim = 0;
    var end_trim = s.length;
    while (s.charAt(start_trim) == ' ') {
        start_trim++;
    }
    while (end_trim > start_trim && s.charAt(end_trim-1) == ' ') {
        end_trim--;
    }
    return s.substring(start_trim, end_trim);
} 
