
function getNewHTTPObject()
{
        var xmlhttp;
        
        /** Special IE only code ... */
        /*@cc_on
          @if (@_jscript_version >= 5)
              try
              {
                  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
              }
              catch (e)
              {
                  try
                  {
                      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                  }
                  catch (E)
                  {
                      xmlhttp = false;
                  }
             }
          @else
             xmlhttp = false;
        @end @*/

        /** Every other browser on the planet */
        if (!xmlhttp && typeof XMLHttpRequest != 'undefined')
        {
            try
            {
                xmlhttp = new XMLHttpRequest();
            }
            catch (e)
            {
                xmlhttp = false;
            }
        }

        return xmlhttp;
}


function textCounter(field,cntfield,maxlimit) {
    if (field.value.length > maxlimit) 
        field.value = field.value.substring(0, maxlimit);
    else
    {
        var el = document.getElementById(cntfield);
        el.innerHTML= field.value.length;
    }
}

function addServicesToList(list)
{
    var p = 0;

    list.options[++p] = new Option("Builder", "3");
    list.options[++p] = new Option("Cleaner", "8");
    list.options[++p] = new Option("Concretor", "9");
    list.options[++p] = new Option("Electrician", "2");
    list.options[++p] = new Option("Excavator", "7");
    list.options[++p] = new Option("Gardener", "10");
    list.options[++p] = new Option("Landscaper", "6");
    list.options[++p] = new Option("Locksmith", "5");
    list.options[++p] = new Option("Painter", "11");
    list.options[++p] = new Option("Pest Controler", "12");
    list.options[++p] = new Option("Plumber", "1");
	list.options[++p] = new Option("Plasterer", "13");
	list.options[++p] = new Option("Removalist", "4");
	
	return;
}

function openWindowCenter(url, width, height, name, properties) {
    var left = parseInt((screen.availWidth/2) - (width/2));
    var top = parseInt((screen.availHeight/2) - (height/2));
    var windowFeatures = "width=" + width + ",height=" + height + ",status=0,resizable=1,scrollbars=1,left=" + left + ",top=" + top + "screenX=" + left + ",screenY=" + top;
    window.open(url, name, windowFeatures + ' ' + properties);
}

function validateLogin()
{
    if (isPhoneNumber(document.main.l.value))
		return true;
		
    if (isEmail(document.main.l.value))
		return true;		
		
	alert("Please enter a valid mobile number or email address;\n\n-Your mobile phone number needs to be 10 digits\n-Your email address should be in this format me@mydomain.com");
    return false;
}

function isEmail(str){
	var supported = 0;
	if (window.RegExp) 
	{
		var tempStr = "a";
		var tempReg = new RegExp(tempStr);
		if (tempReg.test(tempStr)) supported = 1;
	}
	if (!supported) 
	{
		return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
	}
	var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
	var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,}|[0-9]{1,3})(\\]?)$");
	return (!r1.test(str) && r2.test(str));
}

function isPhoneNumber(str) {
	var GoodChars = "0123456789()-+ ";
	var i = 0;
	if (str.length < 8) {
		return false;
	}
	
	for (i =0; i <= str.length -1; i++) {
		if (GoodChars.indexOf(str.charAt(i)) == -1) {
			return false;
		} 
	} 
	return true;
}

function IsNumeric(sText)
{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
}

function toDollarsAndCents(n) {
  var s = "" + Math.round(n * 100) / 100
  var i = s.indexOf('.')
  if (i < 0) return s + ".00"
  var t = s.substring(0, i + 1) + s.substring(i + 1, i + 3)
  if (i + 2 == s.length) t += "0"
  return t
}

/**
 * an event cancel handler.
 *
 * @param e the the event.
 */
function cancelEventCompletion(e) {
    if (window.event && !e) {
        window.event.cancelBubble = true;
        window.event.returnValue = false;
    }

    if (e && e.stopPropagation && e.preventDefault) {
        e.stopPropagation();
        e.preventDefault();
    }
}

/**
 * global class.
 *
 */
var ypCore = {

	/**
	 * event listener.
	 *
	 * @param obj name of the object to be listened for.
	 * @param evType the event type.
	 * @param fn the function.
	 * @param useCapture boolean to enable event capture.
	 */
    addEvent: function(obj, evType, fn, useCapture) {
        if (useCapture == null)
            useCapture = true;

        if (obj.addEventListener) {
            obj.addEventListener(evType, fn, useCapture);
            return true;
        } else if (obj.attachEvent) {
            return obj.attachEvent("on" + evType, fn);
        } else {
            obj['on' + evType] = fn;
        }
    },

	/**
	 * check for alpha numeric chars.
	 *
	 * @param string to test.
	 * @return boolean true if special chars exist.
	 */
    checkForSpecialCharacters: function(value) {
        var regex = /[^A-Za-z0-9_ ]/;
        return regex.test(value);
    },

    cloneObject: function(obj) {
        clone = new Object();
        for (property in obj) {
            clone[property] = obj[property];
        }
        return clone;
    },

	/**
	 * trims whitespace.
	 *
	 * @param string to trim.
	 * @return the trimmed string.
	 */
    trim: function(value) {
        value = value.replace(/^\s+/, '');
        value = value.replace(/\s+$/, '');
        return value;
    }
}

/**
 * cookie class
 *
 */
var CookieService = Class.create();
CookieService.prototype = {
    initialize: function (expiryDays) {
        this.expiryDays = 0;

        if (arguments[0]) {
            this.expiryDays = expiryDays;
        }
    },

	/**
	 * delete cookie function.
	 *
	 * @param name the name of the cookie.
	 * @param path the path of the cookie.
	 * @param domain the domain of the cookie.
	 */
    deleteCookie: function (name, path, domain) {
        if (this.getCookie(name)) {
            document.cookie = name + "=" + ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
        }
    },

	/**
	 * returns the value of the specified cookie.
	 *
	 * @param name the name of the cookie.
	 * @return the value of the cookie.
	 */
    getCookie: function (name) {
        var prefix = name + "=";
        var begin = document.cookie.indexOf("; " + prefix);

        if (begin == -1) {
            begin = document.cookie.indexOf(prefix);
            if (begin != 0) {
                return null;
            }
        } else {
            begin += 2;
        }

        var end = document.cookie.indexOf(";", begin);
        if (end == -1) {
            end = document.cookie.length;
        }
        return unescape(document.cookie.substring(begin + prefix.length, end));
    },

	/**
	 * creates a cookie of a specified name.
	 *
	 * @param name the name of the cookie.
	 * @param value the value the cookie contains.
	 * @param path the path of the cookie.
	 * @param domain the domain of the cookie.
	 * @param secure the security attribute value of the cookie.
	 */
    setCookie: function(name, value, path, domain, secure) {
        var curCookie = name + "=" + escape(value) +
        ((this.getExpiryDate()) ? "; expires=" + this.getExpiryDate().toGMTString() : "") +
        "; path=/" +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");

        document.cookie = curCookie;
    },

	/**
	 * gets the expiry date of the cookie.
	 *
	 * @return the expiry date.
	 */
    getExpiryDate: function() {
        if (this.expiryDays > 0) {
            expiryDate = new Date();
            expiryDate.setTime(expiryDate.getTime() + (this.expiryDays*24*60*60*1000))

            return expiryDate;
        }
        return null;
    },

	/**
	 * tests the existence of a cookie.
	 * cookieName the name of the cookie.
	 *
	 * @return boolean.
	 */
    isCookieAvailable: function (cookieName) {
		if (document.cookie.length > 0) {
			if (document.cookie.indexOf(cookieName + "=") != -1) {
				return true;
			}
		}
		return false;
    }
};


/**
 * Search form validation function.
 *
 * @param form the form object.
 * @param defaultBusType.
 * @param defaultBusName.
 * @param defaultSuburb
 * @return boolean.
 */
function validateSearchForm(form, defaultBusType, defaultBusName, defaultSuburb)
{
    var prefixErrorMessage = 'Help us help you\nWe need more information to complete your search.\n';
    var errorMessage = '';

    var keywordSearchForm = "f-searchForm";
    var mapSearchForm = "f-mapSearchForm";
    var mapSearchRefineForm = "f-mapSearchRefineForm";

    if (form.id.indexOf(keywordSearchForm) == 0)
    {
        var str = ypCore.trim(form.locationClue.value);
		if(str.length < 1){
			form.locationClue.value="";
		}

		if (form.clue) {
	        if (form.clueType[0].checked && (ypCore.trim(form.clue.value) == "" || form.clue.value == defaultBusType)) {
	            errorMessage += '\n- Please enter a Business Type';
	            
	        } else if (form.clueType[1].checked && (ypCore.trim(form.clue.value) == "" || form.clue.value == defaultBusName)) {
	            errorMessage += '\n- Please enter a Business Name';
	            
	        }
		}            
    }
    else if (form.id.indexOf(mapSearchForm) == 0 || form.id.indexOf(mapSearchRefineForm) == 0)
    {
        if (form.businessType && (ypCore.trim(form.businessType.value) == "" || form.businessType.value == defaultBusType))
            errorMessage += '\n- Please enter a Business Type';

        if (form.userSuburb && (ypCore.trim(form.userSuburb.value) == "" || form.userSuburb.value == defaultSuburb))
            errorMessage += '\n- Please enter a Suburb, Town or City';

        if (form.userState && form.userState.value.length > 5)
            errorMessage += '\n- Please select a State';
    }

    if (errorMessage != "")
    {
        alert(prefixErrorMessage + errorMessage);
        return false;
    }
    else
    {
        // Form validated successfully, so continue with the submit
        return true;
    }
}

/**
 * Method returns the HTML element that fired the event.  This method is cross browser
 * compliant.
 */
function getElementForEvent(e) 
{
	// MSIE
    if (window.event && window.event.srcElement) 
    {
        return window.event.srcElement;
    }

	// Others
    if (e && e.target) 
    {
        var theEvent;

        if (e.target.nodeType == 3) // defeats Safari bug
        {
            theEvent = e.target;
		}
        else 
        {
            theEvent = e.target;
		}

		return theEvent;
    }

    return null;
}

