/**
 * Copyright 2005-2007 Metaweb Technologies, Inc.  All Rights Reserved.
 *
 * <b>ConciergeApplication</b>
 *
 * @author alee@metaweb.com
 */
function ConciergeApplication(){
  // member vars:
  this.conceptId;
  this.urler;
  this.utils;
  this.template;
  this.transformer;
  
  setupInheritance(ConciergeApplication);
  superConstructor(Application, this);
}
ConciergeApplication.superClass = [Application];
registerClass(ConciergeApplication, "ConciergeApplication");
ConciergeApplication.prototype._init = function(){
  this.conceptId = arg("id");
  this.urler = new MetawebUrls();
  this.user = new MetawebConciergeUser();
  this.transformer = new DataTransform();
  var url = window.location.pathname;
  var idx= url.lastIndexOf("/");
  if (idx  > -1)
    this.template = url.substr(idx+1);
  if ((this.template == null || this.template != "signin.html") &&
      (typeof this.user == "undefined" || this.user == null || this.user.name == null || this.user.name == ""))
    // check if signed in and redirect to signin if not.
//    window.location = this.urler.signinUrl();
  superMethod(Application, this, "_init");
}
ConciergeApplication.prototype._build = function(){
  superMethod(Application, this, "_build");
  
  this._buildHeader();
  this._buildFooter();
  this._buildDevtools();
}
ConciergeApplication.prototype._buildHeader = function(){
  var signupMarkup = "";
  if (this.user.name == undefined) 
    signupMarkup = sprintf("Please <a href='%s?returnUrl='%s'>sign in</a> to browse or contribute.", this.urler.signinUrl(), window.location);
  else {
    var signoutUrl = this.urler.signoutUrl();
    signupMarkup = sprintf('&nbsp;&nbsp;Welcome back,  <a href="%s">%s</a>. <a href="%s">Sign out</a>.', 
                            this.user.url(), this.user.name, signoutUrl);
  }  
  
  var headerElement = document.getElementById("header");
  if (!headerElement) {
//    var signedin = document.getElementById("signedin");
//    signedin.innerHTML = signupMarkup;
    return;
  }
  
  var headerMarkup = '' +
      '  <table border="0" padding="0" margin="0" width="100%">' +
      '    <tr><td width="147"><a href="index.html"><img id="logo" width="147" border="0" height="54" src="resources/images/concierge_sm.gif"></a></td>' +
      '    <td align="right" valign="middle">' +
      '      <div id="signup">'+signupMarkup+'</div></td>' +
      '   <td width="350" align="right" valign="middle">' +
      '   </td></tr></table>';
  headerElement.innerHTML = sprintf(headerMarkup, this.urler.searchUrl());    
}
ConciergeApplication.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;
}
ConciergeApplication.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 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);
}
ConciergeApplication.prototype.getUser = function(){
  if (!this.user)
    this.user = new MetawebConciergeUser()
  return this.user.getUser();
}
/**
 * Copyright 2005-2007 Metaweb Technologies, Inc.  All Rights Reserved.
 *
 * <b>IndexApplication</b>
 *
 * @author alee@metaweb.com
 */
function IndexApplication(){
  setupInheritance(IndexApplication);
  superConstructor(ConciergeApplication, this);
  
  this.transformer = new DataTransform();
  this.htmler = new HTMLMarkup();
}
IndexApplication.superClass = [ConciergeApplication];
registerClass(IndexApplication, "IndexApplication");
IndexApplication.prototype._postBuild = function(){
//  var component = document.getElementById("locationInput")._component;
//  component.setAutocompleteURL(Globals.autocompleteUrl("/location/us_citytown", true, null, 'instance', false));
//  component.addEventListener("onAutocompleteSelect", this);
//  component.setCreateNewText(null);
//  component.addEventListener("onEscapeKey", this);
  
  if (tester) {
    this.pseudoAutocompleteSelect();
  }
}
IndexApplication.prototype.makeQuery = function(cuisine, location){
  return {
    "q":{
      "query": [{
        "id": null,
        "name" : null,
        "type": "/dining/restaurant",
        "limit": 600,
        "cuisine":[{
          "id":null,
          "name":(cuisine?cuisine:null),
          "optional":true,  // should not be optional - it should return []
          "sort":["name"]
        }],
        "related_webpages":[{
          "/common/webpage/description":{},
          "/common/webpage/uri":{},
          "id":null,
          "name":null,
          "optional":true
        }],
        "/business/retail_location/address": {
          "/location/mailing_address/citytown" : {
            "id" : location,
            "name" : null
          },
          "/location/mailing_address/postal_code":{},
          "/location/mailing_address/street_address":{},
          "/location/mailing_address/street_address_2":{},
          "id":null,
          "name":null,
          "limit":1
        }
      }]
    }
  };
}
IndexApplication.prototype.findRestaurants = function(name, typeId){
  var hjq = this.makeQuery(null, typeId);
  console.log("IndexApplication.findRestaurants: ", hjq);
  var hjDP = mql(hjq, false);
  hjDP.requestData(Delegate.create(this, this.cuisineList)); 
}
IndexApplication.prototype.cuisineList = function( queryResult) {
  var foodImg = document.getElementById("food");
  var cuisineDiv = document.getElementById("cuisines");
  if (this.cuisineChoices) {
    cuisineDiv.style.display = "none";
    this.cuisineChoices.clearData();
    foodImg.style.display = "block";
  }
  
  console.log("IndexApplication.cuisineList: ", showMembers(queryResult.q));
  if (queryResult.q.code == "/api/status/error") {
    alert("Sorry, there was a problem retrieving cuisines for " + this.locationInfo.getText() + "\nError: " + queryResult.q.messages[0].message);
    return;
  }
  
  var restaurants = queryResult.q["result"];
  if (restaurants.length == 0 || restaurants[0] == null) {
    alert("Sorry, we have no restaurant listings for " + this.locationInfo.getText());
    return;
  }
  if (!this.map && !tester) {
    alert("Wrong Location specified and map won't load");
    return;
  }
  this.transformer.mapCuisines(restaurants);
  
  var radioButtonListData = { listItems:[] };
  for (var i = 0, len=this.transformer.cuisines.length; i < len; i++) {
    var cuisineName = this.transformer.cuisines[i];
    var cuisine = this.transformer.cuisineMap[cuisineName];
    var numRestaurantsByCuisine = this.transformer.cuisineRestaurantMap[cuisineName].length;
    radioButtonListData.listItems.push({
      name: "cuisineChoices",
      label: sprintf("%s (%s)", cuisineName, numRestaurantsByCuisine) ,
      url: this.htmler.cuisineLink(cuisine.id, this.locationInfo.getValue(), cuisineName),
      cuisine: cuisineName,
      value: i,
      checked: false
    });
  }
  
  var randomCuisine = this.transformer.getRandomCuisineIndex();
  radioButtonListData.selected = randomCuisine;
  this.htmler.mapRestaurants(10, this.transformer.cuisineRestaurantMap[this.transformer.cuisines[randomCuisine]], this.map);
  
  foodImg.style.display = "none";
  cuisineDiv.style.display = "block";
//  if (!this.cuisineChoices){
    var div = document.getElementById('cuisineTitle');
    div.innerHTML = sprintf("Cuisines (%s)", this.htmler.allCuisinesLink(this.locationInfo.getValue(), this.transformer.cuisines.length));
    div = document.getElementById('cuisineList');
    this.cuisineChoices = new RadioButtonList(div);
    this.cuisineChoices.addEventListener("onSelectionChange", this);
//  }
  this.cuisineChoices.setData(radioButtonListData);
  
  div = document.getElementById("viewAll");
  div.innerHTML = this.htmler.allRestaurantsLink(this.locationInfo.getValue(), "View " + restaurants.length + " restaurants");
}
IndexApplication.prototype.mapLocation = function(locationName){
  if (tester) return;
  
  this.map = new GoogleMap("map");
  this.map.showAddress(locationName, locationName, true);
}
IndexApplication.prototype.onAutocompleteSelect = function(eventObject) {


console.log("Hai", eventObject);
  this.locationInfo = eventObject.autocompleteInfo;
  var locationId = this.locationInfo.getValue();
  var locationName = this.locationInfo.getText();
  // Do MQLQuery to find all restaurants in given location.
  // TODO
  this.mapLocation(locationName);
  this.findRestaurants(locationName, locationId);
};
IndexApplication.prototype.pseudoAutocompleteSelect = function() {
  var queryResults = cachedQResults();
  var results = queryResults["result"];
  this.locationInfo = new AutocompleteInfo();
  this.locationInfo._text = results[0]['/business/retail_location/address']['/location/mailing_address/citytown'].name;
  this.locationInfo._value = results[0]['/business/retail_location/address']['/location/mailing_address/citytown'].id;
  var locationId = this.locationInfo.getValue();
  var locationName = this.locationInfo.getText();
  // Do MQLQuery to find all restaurants in given location.
  // TODO
  this.mapLocation(locationName);
  this.cuisineList(queryResults);
};
IndexApplication.prototype.onEscapeKey = function(eventObject) {
  // Do nothing.
}
IndexApplication.prototype.onSelectionChange = function(eventObject) {
  if (!eventObject.targetItem || !this.locationInfo)
    return;
  var data = eventObject.targetItem.getData();
  var cuisine = data.cuisine;
  var cuisineIndex = data.value;
  
  if (tester) {
    return;
  }
  this.mapLocation(this.locationInfo.getText());
  this.htmler.mapRestaurants(10, this.transformer.cuisineRestaurantMap[this.transformer.cuisines[cuisineIndex]], this.map);
}
