

/**
 * Copyright 2005-2007 Metaweb Technologies, Inc.  All Rights Reserved.
 *
 * <b>DataTransform</b>
 *
 * @author alee@metaweb.com
 */
function DataTransform(){
  // member vars
  this.cuisineRestaurantMap;
  this.cuisines;
  this.cuisineMap;
}
DataTransform.prototype.mapCuisines = function(restaurants){
  // creates cuisineMap, cuisineRestaurantMap; both indexed by cuisine name
  // each item in cuisineMap points to cuisine object - name, id, description
  // each item in cuisineRestaurantMap points to array of restaurants with that cuisine.
  this.cuisineMap = new Array ();
  this.cuisineRestaurantMap = new Array ();
  this.cuisine_count = 0;
  for (var i = 0, len=restaurants.length; i < len; i++) {
    this.cuisine_count += restaurants[i].cuisine.length;
    for (var j = 0, len2=restaurants[i].cuisine.length; j < len2; j++) {
      var cuisine = restaurants[i].cuisine[j];
      var cuisineName = cuisine.name;
      this.cuisineMap[cuisineName] = cuisine;
      var cuisineRestaurants = this.cuisineRestaurantMap[cuisineName];
      if (cuisineRestaurants == undefined) {
        cuisineRestaurants = new Array();
        this.cuisineRestaurantMap[cuisineName] = cuisineRestaurants;
      }
      cuisineRestaurants.push(restaurants[i]);
    }
  }
  this.cuisines = new Array ();
  for (var key in this.cuisineRestaurantMap)
    this.cuisines.push (key);
  this.cuisines.sort();
}
DataTransform.prototype.restaurantsWithAnyOneOfCuisines = function(cuisineIndicesSelected) {
  // cuisineRestaurantMap[app.transformer.cuisines[cuisineIndex]]
  var inRestaurants = {};
  var restaurants = new Array();
  var isInRestaurants;
  var restaurant;
  for (var c in cuisineIndicesSelected) {
    if (!cuisineIndicesSelected[c])
      continue;
    for (var r=0, cuisineName=this.cuisines[c], len=this.cuisineRestaurantMap[cuisineName].length; r<len; r++){
      restaurant = this.cuisineRestaurantMap[cuisineName][r];
      isInRestaurants = inRestaurants[restaurant.id];
      if (typeof isInRestaurants == "undefined" || isInRestaurants == null){
        restaurants.push(restaurant);
        inRestaurants[restaurant.id] = true;
      }
    }
  }
  return restaurants;
}
DataTransform.prototype.tableRestaurant = function(restaurants){
  var restaurantRows = new Array();
  for (var row=0, rowlen=Math.round(restaurants.length/3); row<rowlen; row++) {
    var restaurantCols = new Array();
    for (var col=0; col<3; col++) {
      var index = row*3 + col;
      if (index < restaurants.length)
        restaurantCols.push(restaurants[index]);
      else
        break;
    }
    restaurantRows.push(restaurantCols);
  }
  return restaurantRows;
}                  
DataTransform.prototype.getRandomCuisineIndex = function(){
  var rand_count = Math.floor (this.cuisine_count * Math.random ());
  var rand_cuisine = -1;
  for (var i = 0, len=this.cuisines.length; i < len; i++) {
    rand_count -= this.cuisineRestaurantMap[this.cuisines[i]].length;
    if (rand_count < 0) {
      rand_cuisine = i;
      break;
    }
  }
  return rand_cuisine;
}
DataTransform.prototype.compareText = function (a,b) {
    aa = a.label.toLowerCase();
    bb = b.label.toLowerCase();
    if (aa==bb) return 0;
    if (aa<bb) return -1;
    return 1;
}
/**
 * Copyright 2005-2007 Metaweb Technologies, Inc.  All Rights Reserved.
 *
 * <b>GoogleMap</b>
 *
 * @author alee@metaweb.com
 */
function GoogleMap(mapIdString) {
  this._body = document.getElementById(mapIdString);
  this.mapIdString = (mapIdString)?mapIdString:"map";
  this.centerMarker;
  this.map;
  this.geocoder = new GClientGeocoder();
}
GoogleMap.MarkerDefaults = [
	{img:'resources/images/mw_logo2.png', width:20, height:30, shadow:'resources/images/mw_logo2_shadow.png', swidth:47, sheight:30, xAnchor:11, yAnchor:30},
	{img:'resources/images/marker.png', width:11, height:23, shadow:'resources/images/marker_shadow.png', swidth:25, sheight:23, xAnchor:6, yAnchor:23}
];
GoogleMap.prototype.showAddress = function(address, description, center) {
  if (typeof center == "undefined" || center == null)
    center = false;
  if (GBrowserIsCompatible()) {
    this.map = new GMap2(document.getElementById(this.mapIdString));
    this.map.addControl(new GSmallMapControl());
    this.map.addControl(new GMapTypeControl());
    var owner = this;
    this.geocoder.getLatLng( address,
      function(point) {
        if (!point) {
          console.log(address + " not found");
        } else {
          owner.map.setCenter(point, 13);
          var marker;
          if (center) {
            if (typeof owner.centerMarker == "undefined" || owner.centerMarker == null)
              owner.centerMarker = owner.createMarker(0);
            marker = new GMarker(point, owner.centerMarker);
          }
          else
            marker = new GMarker(point);
          owner.map.addOverlay(marker);
          GEvent.addListener(marker, 'click', function() {
                               marker.openInfoWindowHtml(description);
                             });
        }
      }
    );
  }
}
GoogleMap.prototype.createMarker = function(type) {
	var icon = new GIcon();
	icon.image = 'resources/images/mw_logo2.png';
	icon.shadow = 'resources/images/mw_logo2_shadow.png';
	icon.iconSize = new GSize(20, 30);
	icon.shadowSize = new GSize(47, 30);
	icon.iconAnchor = new GPoint(11, 30);
	icon.infoWindowAnchor = new GPoint(12, 1);
	return icon;
};
/*
 * Vanilla markers: no Image, just text with <a> if .url is set.
 */
GoogleMap.prototype.addMarker = function(markerData) { 
  var owner = this;
  try {
    this.geocoder.getLatLng( markerData.address, function(point) {
      if (!point) {
        console.log("GoogleMap.addMarker", markerData.address, " not found");
      } else {
        owner.map.setCenter(point, 13);
        var marker = new GMarker(point);
        owner.map.addOverlay(marker);
        GEvent.addListener(marker, 'click', function() {
          marker.openInfoWindowHtml(markerData.description);
        });
      }
    });
  } catch(ex) {
    console.log("GoogleMap.addMarker", ex, showMembers(markerData));
  }
}
/**
 * Copyright 2005-2007 Metaweb Technologies, Inc.  All Rights Reserved.
 *
 * <b>HTMLMarkup</b>
 *
 * @author alee@metaweb.com
 */
function HTMLMarkup(){
}
HTMLMarkup.prototype.trimUrl = function(urlStr, maxLength)
{
  var trimmed = urlStr;
  if (/^(\w+:\/{2,3}[^\/]+)(.*)/.test(urlStr)) {
    trimmed = RegExp.$1;
    
    var path = RegExp.$2;
    if (path && path.length > maxLength) {
      path = path.substr(1,maxLength-1);
      path += '\u2026';
    }
  }
  return trimmed+"/"+path;
}
HTMLMarkup.prototype.mapRestaurants = function(maxNumber, restaurants, map){
  var randomIndices = new Array();
  if (maxNumber >= restaurants.length) {
    for (var r = 0, len=restaurants.length; r < len; r++)
      randomIndices.push(r);
  }
  else
    while(randomIndices.length< maxNumber) {
      var r = Math.floor(Math.random() * restaurants.length);
      var found = false;
      for (var i = 0; i < randomIndices.length; i++)
        if (r == randomIndices[i]) {
          found = true;
          break;
        }
      if (found)
        continue;
      randomIndices.push(r);
    }
  var randomRestaurants = new Array();
  for (var i = 0, len=randomIndices.length; i < len; i++) {
    var restaurant = restaurants[randomIndices[i]];
    randomRestaurants.push(restaurant);
    console.log("HTMLMarkup.mapRestaurants: ", restaurant);
    var markerData = this.addressMarkerData(restaurant.name, restaurant.id, restaurant["/business/business_location/address"], restaurant.cuisine);
    if (tester)
      console.log("HTMLMarkup.mapRestaurants", i, restaurant.name, restaurant.id, restaurant["/business/business_location/address"]);
    else
      map.addMarker(markerData);
  }  
}
HTMLMarkup.prototype.addressMarkup = function(id, name, location, noCityTown){
  // Replaced by mjt.htmler.addressMarkup
  if (typeof noCityTown == "undefined" || noCityTown == null)
    noCityTown = false;
  var html = "";
  var street = "";
  if (name) 
    html += sprintf("    <div class='title'>%s</div>", this.restaurantLink(id, name,  location["/location/mailing_address/citytown"].id));
  if (location['/location/mailing_address/street_address'])
    street = html += sprintf("    <div class='Street'>%s</div>", location['/location/mailing_address/street_address'].value);
  if (!noCityTown && 
    (location['/location/mailing_address/citytown'] || location['/location/mailing_address/postal_code'])){
    var html2 = ""
    if (location['/location/mailing_address/citytown'])
      html2 += sprintf("<span class='CityTown'>%s</span>&nbsp;", location['/location/mailing_address/citytown'].name);
    if (location['/location/mailing_address/postal_code'])
      html2 += sprintf("<span class='PostalCode'>%s</span>", location['/location/mailing_address/postal_code'].name);
    html += sprintf("    <div>%s</div>", html2);
  }
  return html;
}

HTMLMarkup.prototype.addressMarkerData = function(name, id, location, cuisines){
  var address = '';
  var cuisineList = '';

  if (!location['/location/mailing_address/citytown']) {
    alert(sprintf("Aborting HTMLMarkup.addresssMarkerData: please provide city_town (%s)", location['/location/mailing_address/citytown']));
    return {};
  }
  for (var c=0, len=cuisines.length; c<len; c++) {
    cuisineList += sprintf('%s<span>%s</span>',
      ((c>0)?", ":""), this.cuisineLink(cuisines[c]["id"], location['/location/mailing_address/citytown'].id, cuisines[c]["name"]));
  }
  if (!location['/location/mailing_address/citytown']) {
    alert(sprintf("Aborting HTMLMarkup.addresssMarkerData: please provide city_town (%s)", location['/location/mailing_address/citytown']));
    return {};
  }
  if (location['/location/mailing_address/street_address']){
    address += location['/location/mailing_address/street_address'].value;
    street = sprintf("    <div class='Street'>%s</div>", location['/location/mailing_address/street_address'].value);
  }
  if (location['/location/mailing_address/street_address2'])
    address += ", " + location['/location/mailing_address/street_address2'].value;
  if (location['/location/mailing_address/citytown'] || location['/location/mailing_address/postal_code']){
    if (location['/location/mailing_address/citytown'])
      address += ", " + location['/location/mailing_address/citytown'].name;
    if (location['/location/mailing_address/postal_code'])
      address += ", " + location['/location/mailing_address/postal_code'].name;
  }
  var markerData = {
    name: name,
    address: address,
    description: sprintf("<div id='gmarkerAddress'>%s<br/>%s%s</div>", this.restaurantLink(id, name, location['/location/mailing_address/citytown'].id), street, cuisineList)
  };
  return markerData;
}
HTMLMarkup.prototype.allCuisinesLink = function(location, label){
  return sprintf('<a href="allCuisines.html?location=%s">%s</a>', encodeURIComponent(location), label);
}
HTMLMarkup.prototype.allRestaurantsLink = function(location, label){
  return sprintf('<a href="allRestaurants.html?location=%s">%s</a>', 
                   encodeURIComponent(location), label);
}
HTMLMarkup.prototype.cuisineLink = function(cuisineId, locationId, cuisineName, i, len){
  return sprintf('<a href="cuisine.html?id=%s&location=%s">%s</a>%s', 
                 encodeURIComponent(cuisineId), encodeURIComponent(locationId), cuisineName, (i<len)?", ":"");
}
HTMLMarkup.prototype.cuisineLinkWithHandler = function(cuisineId, locationId, cuisineName){
  return sprintf('<a href="cuisine.html?id=%s&location=%s" onclick=consumeClickHandler(event)>%s</a>', 
                 encodeURIComponent(cuisineId), encodeURIComponent(locationId), cuisineName);
}
HTMLMarkup.prototype.restaurantLink = function(id, label, location) {
  return sprintf("<a href='restaurant.html?id=%s&location=%s'>%s</a>", 
                 encodeURIComponent(id), encodeURIComponent(location), label);  
};
HTMLMarkup.prototype.restaurantLinkWithHandler = function(id, label, location) {
  return sprintf("<a href='restaurant.html?id=%s&location=%s' onclick=consumeClickHandler(event)>%s</a>", 
                 encodeURIComponent(id), encodeURIComponent(location), label);  
};
HTMLMarkup.prototype.webpageLink = function(description, uri, trim){
  if (typeof trim == "undefined" || trim == null)
    trim = false;
  var fullText = uri.value;
  var linkText = (trim)?this.trimUrl(uri.value, 5):uri.value;
  if (description) 
    fullText = linkText = description.name; 
  console.log("HTMLMarkup.webpageLink", sprintf('<a href="%s" alt="%s">%s</a>', uri.value, fullText, linkText));
  return sprintf('<a href="%s" alt="%s">%s</a>', uri.value, fullText, linkText);
}
/**
 * Copyright 2005-2007 Metaweb Technologies, Inc.  All Rights Reserved.
 *
 * <b>MetawebConciergeUser</b>
 *
 * @author tim@metaweb.com
 * @author alee@metaweb.com
 * 
 * Adapted to provide only functionality associated with reading cookie 
 * info - ignoring loginEvent functionality.
 */
function MetawebConciergeUser() {
  this.guid = undefined;
  this.name = undefined;
  this.path = undefined;
  this._update();
  
  // Update our contents whenever we see a "login" event.
  if (g_application) {
    var owner = this;
    g_application.addEventListener("login", function(ev){owner.onLoginEvent();});
  }
};
MetawebConciergeUser.prototype._update = function(){
  // get user info from cookie:
  var cookieInfo = readCookie("metaweb-user-info");
  var oldGuid = this.guid;
  var oldName = this.name;
  if (cookieInfo.indexOf('A|') == 0) {
    // Using new cookie format (which is extensible and Unicode-safe)
    // 'g' = User GUID, 'u' = user account name, 'p' = path name of user obj
    this.guid = this._cookieItem(cookieInfo, 'g');
    this.name = this._cookieItem(cookieInfo, 'u');
    this.path = this._cookieItem(cookieInfo, 'p');
    if (!this.path)
      this.path = '/user/' + this.name;
  } else {
    // Using old cookie format
    cookieInfo = unescape(cookieInfo).split("|");
    if (cookieInfo && cookieInfo.length >= 2) {
      this.guid = cookieInfo[0];
      this.name = cookieInfo[1];
      this.path = '/user/' + this.name;
    } else {
      this.guid = undefined;
      this.name = undefined;
      this.path = undefined;
    }
  }  
  this.displayName = this.name;
  // Return "true" if anything really changed.
  return (oldGuid != this.guid || oldName != this.name);
};
MetawebConciergeUser.prototype.onLoginEvent = function(){
  // Since we send a login event recursively, we will get
  // entered recursively; prevent that from going too far.
  if (this._handlingLoginEvent > 0)
    return;
  
  // If nothing changed, we're done.
  if (!this._update())
    return;
  
  // Dispatch a login event, but ignore the event we receive from this.
  this._handlingLoginEvent = 1;
  if (g_application && g_application.dispatchEvent)
    g_application.dispatchEvent("login");
  this._handlingLoginEvent = 0;
};
MetawebConciergeUser.prototype._cookieItem = function(c, i){
  var s = c.indexOf('|'+i+'_');
  if (s != -1){
    s = s + 2 + i.length;
    var e = c.indexOf('|',s);
    if (e != -1) return decodeURIComponent(c.substr(s,e-s));
  }
  return null;
};
MetawebConciergeUser.prototype.getUser = function() {
  if (this.guid)
    return(this);
  return undefined;
};
MetawebConciergeUser.prototype.url = function() {
  try {
    var url = "http://www.freebase.com/api/metaweb/view?id=" + encodeURIComponent(this.guid);  
    url += "&typeId=" + encodeURIComponent("/type/user");
    return url
  } catch(e) {
    console.error("login.url() failed:", e);
  }
  return null;
};
/**
 * Copyright 2005-2007 Metaweb Technologies, Inc.  All Rights Reserved.
 *
 * <b>MetawebUrls</b>
 *
 * @author alee@metaweb.com
 */
function MetawebUrls(){}
MetawebUrls.prototype.allDomainsUrl = function() {
  return "http://www.freebase.com/view/allDomains";
};
MetawebUrls.prototype.topicViewUrl = function(id) {
  var url = "http://www.freebase.com/view?id=" + encodeURIComponent(id);  
  return (url);
};
MetawebUrls.prototype.freebaseUrl = function(){
  return "http://www.freebase.com/view/";
}
MetawebUrls.prototype.freebaseLoginUrl = function(){
  return "http://www.freebase.com/view/signin/";
}
MetawebUrls.prototype.helpUrl = function(){
  return "http://www.freebase.com/view/helpindex?id=%239202a8c04000641f80000000012090ef";
};
MetawebUrls.prototype.searchUrl = function(){
  return "http://www.freebase.com/view/search";
};
MetawebUrls.prototype.signinUrl = function(){
  return "signin.html?returnUrl=" + encodeURIComponent(window.location);
};
MetawebUrls.prototype.signoutUrl = function(){
  return "/api/account/logout?onsucceed=" + encodeURIComponent("/");
};
MetawebUrls.prototype.viewUrl = function(id, typeId) {
  var url = "/api/metaweb/view?id=" + encodeURIComponent(id);  
  if (typeId) {
    url += "&typeId=" + encodeURIComponent(typeId);
  }  
  return (url);
};
/**
 * Copyright 2005-2007 Metaweb Technologies, Inc.  All Rights Reserved.
 *
 * <b>MJTConciergeApplication</b>
 *
 * @author alee@metaweb.com
 */
var g_application;
function MJTConciergeApplication(locationId, user, htmler, transformer, urler){
  g_application = this;
  // member vars:
  this.locationId = locationId;
  this.user = user;
  this.urler = urler;
  this.htmler = htmler;
  this.transformer = transformer;
  
  this._emptyMessage;
  this._input;
  this._searchBox;
  this._searchUrl;
  this._searchButton;
  this._focusHandler;
  this._blurHandler;
  this._enterKeyHandler;
    
  this._buildHeader();
  this._buildFooter();
  this._buildDevtools();
  this.attachSearchHandlers();
}
MJTConciergeApplication.DEFAULT = "Keyword search Freebase";
MJTConciergeApplication.prototype.searchMarkup = function(){
  return sprintf('<div id="searchBox" class="SearchBox" searchurl="%s"><div class="TextInput"><input id="searchInput" autocomplete="off" type="text"></div><button id="searchButton" class="Button"><span class="ButtonLabel">Search Freebase</span></button></div>', this.urler.searchUrl());
};
MJTConciergeApplication.prototype._buildHeader = function(){
  var headerElement = document.getElementById("header");
  if (!headerElement) return;
  
  var signupMarkup = "";
/*  if (this.user.name == undefined) 
    signupMarkup = sprintf("Please <a href='%s?returnUrl='%s'>sign in</a> or <a href='%s?returnUrl='%s'>register</a> to contribute.", this.urler.signinUrl(), window.location, this.urler.signinUrl(), window.location);
  else {
    var signoutUrl = this.urler.signoutUrl();
    signupMarkup = sprintf('Welcome back,  <a href="%s">%s</a>. <a href="%s">Sign out</a>.', 
                            this.user.url(), this.user.name, signoutUrl);
  }  
*/  

  var headerMarkup = '' +
      '  <table border="0" padding="0" margin="0" width="100%">' +
      '    <tr><td width="247" align="left"><a href="index.html"><img id="logo" width="147" border="0" height="54" src="resources/images/concierge_sm.gif"></a></td>' +
      '    <td align="left" valign="middle">' +
      '      <div id="signup">'+signupMarkup+'</div></td>' +
      '   <td width="350" align="right" valign="middle">' +
      '     <div id="searchWidget">' + 
      this.searchMarkup() +
      '       <div id="searchwidgetbottom"><img width="5" height="3" src="resources/images/search_bkd_bottom_left.gif"></div></div></td></tr></table>';
  headerElement.innerHTML = headerMarkup;    
}
MJTConciergeApplication.prototype._buildFooter = function(){
  var footerElement = document.getElementById("footer");
  if (!footerElement) return;
  var footerMarkup = '' +
      '<div id="contentbottom"><img src="resources/images/bottom_left_content_corner.gif"></div>' +
      '<div id="pagebottom"><img width="7" height="35" src="resources/images/bottom_left_corner.gif"></div>';
  footerElement.innerHTML = footerMarkup;
}
MJTConciergeApplication.prototype._buildDevtools = function() {
  // DOM calls are faster than setting innerHTML with all the tag elements and their innerHTML
  var element = document.getElementById("devtools");
  if (!element) return;  
  var exploreId = this.locationId;
  if (!exploreId)
    exploreId = "/";
    
  // markup that goes inside the <div> element:
  var fragment = document.createDocumentFragment();
  var div = document.createElement("div");
  div.setAttribute("title", "Dev Tools");
  div.setAttribute("id", "pagetools");
  fragment.appendChild(div);
  
  var span = document.createElement("span");
  span.innerHTML = "Tools";
  div.appendChild(span);
  
  // first ul with all MetawebLinks
  var ul = document.createElement("ul");
  ul.setAttribute("id", "footernav");
  var ulListItems = [{
    href : this.urler.freebaseUrl(),
    text : "Freebase"
  },{
    href : this.urler.allDomainsUrl(),
    text : "Types"
  }];
  var conceptId = arg("id");
  if (typeof conceptId != "undefined" && conceptId != null && conceptId != ""){
    ulListItems.splice(2,0, {
      href : this.urler.topicViewUrl(conceptId),
      text : "Contribute to this Topic"
    });
  }
  var li;
  var ahref;
  for (var i=0, len=ulListItems.length; i<len; i++) {
    li = document.createElement("li");
    ahref = document.createElement("a");
    ahref.setAttribute("href", ulListItems[i].href);
    ahref.innerHTML = ulListItems[i].text;
    li.appendChild(ahref);
    ul.appendChild(li);
  }
  fragment.appendChild(ul);
  
  // Second ul for cc
  ul = document.createElement("ul");
  ul.setAttribute("id", "cc");
  ulListItems = [{
    href : "http://www.freebase.com/signin/tos",
    text : "Terms of Service"
  },{
    href :  "http://www.metaweb.com",
    text : "&copy;2007 Metaweb Technologies, Inc."
  }];
  for (var i=0, len=ulListItems.length; i<len; i++) {
    li = document.createElement("li");
    ahref = document.createElement("a");
    ahref.setAttribute("href", ulListItems[i].href);
    ahref.setAttribute("target", "_blank");
    ahref.innerHTML = ulListItems[i].text;
    li.appendChild(ahref);
    ul.appendChild(li);
  }
  fragment.appendChild(ul);
  
  div = document.createElement("div");
  div.className = "shim";
  div.style.clear = "both";
  fragment.appendChild(div);
  
  element.appendChild(fragment);
}
MJTConciergeApplication.prototype.attachSearchHandlers = function()
{
  this._searchBox = document.getElementById("searchBox");
  this._input = document.getElementById("searchInput");
  this._emptyMessage = this._searchBox.getAttribute("prompt");
  if (!this._emptyMessage) this._emptyMessage = MJTConciergeApplication.DEFAULT;
  
  this._searchUrl = this._searchBox.getAttribute("searchUrl");
  var prompt = arg("query");
  if (!prompt)
    prompt = this._emptyMessage;
  this._input.value = prompt;
  this._input.setAttribute("autocomplete", "off");
  try {
    this._focusHandler = Delegate.create(this, this.onFocus);
    this._blurHandler = Delegate.create(this, this.onBlur);
    this._enterKeyHandler = Delegate.create(this, this.onEnterKey);
    this.addEventHandler(this._input, "focus", this._focusHandler);
    this.addEventHandler(this._input, "blur", this._blurHandler);
    this.addEventHandler(this._input, "keypress", this._enterKeyHandler);
  } catch(ex){
    console.log("MJTConciergeApplication.attachSearchHandlers on this._input: ", ex);
    console.trace();
  }
  this._searchButton = document.getElementById("searchButton");;
  try {
    this._searchHandler = Delegate.create(this, this._onSearch);
    this.addEventHandler(this._searchButton, "click", this._searchHandler);
  } catch(ex){
    console.log("MJTConciergeApplication.attachSearchHandlers on this._searchButton: ", ex);
    console.trace();
  }
}
MJTConciergeApplication.prototype.onFocus = function(eventObject){
  if (this._input && this._input.value == this._emptyMessage)
    this._input.value = "";
}
MJTConciergeApplication.prototype.onBlur = function(eventObject){
  var value = this._input.value;
  if (typeof value == "undefined" || value == null || value == "")
    this._input.value = this._emptyMessage;
}
MJTConciergeApplication.prototype.onEnterKey = function(eventObject){
  eventObject = eventObject || window.event;
  if (eventObject.keyCode == 13) {
    this.preventDefault(eventObject);
      this._onSearch();
  }
}
MJTConciergeApplication.prototype._onSearch = function() {
  var searchStr = this._input.value;
  var request;
  if (typeof searchStr != "undefined" && searchStr != null && searchStr != "")
  {
    // query is search string
    // limit is search page size
    // start is next start index
    params = sprintf("query=%s&limit=30&start=0", encodeURIComponent(searchStr))
  }
  document.location.href = this._searchUrl + "?" + params;
}
MJTConciergeApplication.prototype.addEventHandler = function(target, eventType, handler) {
  if(target.addEventListener){
    target.addEventListener(eventType, handler, false);
  }
  else if(target.attachEvent){
    target.attachEvent("on" + eventType, handler);
  }
  else{
    target["on" + eventType] = handler;
  }
}
MJTConciergeApplication.prototype.removeEventHandler = function(target, eventType, handler) {
  if(target.removeEventListener){
    target.removeEventListener(eventType, handler, false);
  }
  else if(target.detachEvent){
    target.detachEvent("on" + eventType, handler);
  }
  else{ 
    target["on" + eventType] = null;
  }
}
MJTConciergeApplication.prototype.preventDefault = function(domEvent) {
  isIE ? domEvent.returnValue = false : domEvent.preventDefault();
};
MJTConciergeApplication.prototype.stopPropagation = function(domEvent) {
  isIE ? domEvent.cancelBubble = true : domEvent.stopPropagation();
};
/**
 * Copyright 2005-2007 Metaweb Technologies, Inc.  All Rights Reserved.
 *
 * rights reserved under the copyright laws of the United States.
 *
 * <b>Delegate</b>
 *
 * @author daepark@apmindsf.com
 */
/******************************************************** Delegate
 * @constructor
 */
function Delegate() {}
/******************************************************** create
 * Creates a functions wrapper for the original function so that it runs 
 * in the provided context.
 *
 * @param obj:Object - Context in which to run the function
 * @param func:Function - Function to run.
 */
Delegate.create = function(obj, func, args) {
  if (typeof args == "undefined") {
    args = [];
  }
  
  var f = function(){
    var myArgs = [];
    for(var i=0, len=arguments.length; i<len; i++) {
      myArgs.push(arguments[i]);
    }
    return (arguments.callee.func.apply(arguments.callee.target, arguments.callee.args.concat(myArgs)));
  };
  f.target = obj;
  f.func = func;
  f.args = args;
  return (f);
};
/******************************************************** destroy
 * Properly cleanup a delegate created from Delegate.create
 *
 * @param f:Function - Function created from Delegate.create
 */
Delegate.destroy = function(f) {
  if (f) {
    f.target = null;
    f.func = null;
    f.args = null;
  }
};
