/**
 * Returns the cookie domain.  If the domain
 * can not be parsed, then the default domain
 * is returned.
 * @param hostName - the host name to parse.
 */
function parseDomainName(hostName) {
	var domainName = hostName;
	if ( hostName!=null && hostName.indexOf( "." ) != -1 ) {
	  var lastIdx = hostName.lastIndexOf( "." );
	  var firstIdx = hostName.substring( 0, lastIdx ).lastIndexOf( "." );		
	  if ( firstIdx != -1 ) {
	    domainName = hostName.substring( firstIdx + 1 );
	  } else {
	    domainName = hostName;
	  }		  
	  if (domainName.charAt(0)!= ".") {
	  	domainName = "." + domainName;
	  }
	} else {
		domainName = ".ichotelsgroup.com";
	}
	return domainName;
}

/**
 * Sets the cookie.
 * @param name - the cookie name.
 * @param value - the cookie value.
 * @param expires - the expiry date.  The getCookieExpiryDate()
 * method can be used to get the expiry date.
 * @param path - the cookie path. 
 * @param domain - the cookie domain. The parseDomainName()
 * method can be used to get the cookie domain.
 * @param secure - set to true for a secure cookie.
 */
function setCookie(name, value, expires, path, domain, secure) {
  var curCookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires.toGMTString() : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
  document.cookie = curCookie;
}

/**
 * Deletes a cookie.
 * @param name - the cookie name.
 * @param path - the cookie path. 
 * @param domain - the cookie domain. The parseDomainName()
 * method can be used to get the cookie domain.
 */
function deleteCookie(name, path, domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}


/**
 * Returns the cookie in the browser.
 * @param name - the cookie name.
 */
function getCookie(name)
{
	if (document.cookie.length>0) {
	  var start = document.cookie.indexOf(name + "=")
	  if (start!=-1) { 
	    start = start + name.length+1 
	    var end = document.cookie.indexOf(";",start)
	    if (end==-1) {
	    	end = document.cookie.length;
	    }
	    return unescape(document.cookie.substring(start,end));
		} 
	}
	return "";
}

/**
 * Returns the cookie expiry date.
 * @param days - the number of days until the cookie
 * expires.
 */
function getCookieExpiryDate(days) {
	var date = new Date();
	var expireTime = days*24*60*60*1000;
	date.setTime(date.getTime()+(expireTime)); 
	return date;
}
