/*
 * Copyright 2009 Palm, Inc. All rights reserved.
 */
/*global Mojo, Class, $L, $A */
/*jslint rhino:true, undef:true */

var UrlManager = {

  username: "",
  password: "",
  locale: null,
  carrier: null,
  device: null,
  deviceModel: null,
  baseUrlWithInfo: "#{baseUrl}/#{locale}/#{carrier}/#{device}",
  baseUrlWithLocale: "#{baseUrl}/#{locale}",
  baseUrlNoInfo: "http://help.palm.com",

  tipsUrl: "#{baseUrl}/index.json",
  clipsUrl: "#{baseUrl}/clips/index.json",

  tipsMenuUrl: "#{baseUrl}/index.json?from=menu",
  clipsMenuUrl: "#{baseUrl}/clips/index.json?from=menu",

  searchUrl: "http://help.palm.com/search/results.cgi",
  featuredUrl: "#{baseUrl}/index_features.json",

  searchParamter: "q",

  setLocale: function(value) {
    UrlManager.locale = value.toLocaleLowerCase();
    Mojo.Log.info("UrlManager#setLocale: " + UrlManager.locale);
  },

  setCarrier: function(value) {
    Mojo.Log.info("UrlManager#setCarrier: " + value);
    UrlManager.carrier = value;
  },

  setDevice: function(devModel) {
    Mojo.Log.info("UrlManager#setDevice: " + devModel);

    UrlManager.deviceModel = devModel;

    var device = null;
    if (devModel.match(/^P100/)) 
    {
        device = 'd100-00';
    }
	else if (devModel.match(/^P101/)) {
		device = 'd100-03';
	}
    else if (devModel.match(/^P120/))
    {
        device = 'd200-01';
    }
	else if (devModel.match(/^P121/)) {
		device = 'd200-03';
	}
    else 
    {
        Mojo.Log.warn("Unknown device %s", devModel);
    }

    if (device) {
        UrlManager.device = encodeURIComponent(device);
	}
  },

  getBaseUrl: function() {
    if (UrlManager.locale && UrlManager.carrier && UrlManager.device) 
    {
        return UrlManager.baseUrlWithInfo.interpolate(
            {locale: UrlManager.locale, carrier: UrlManager.carrier, device: UrlManager.device, baseUrl: UrlManager.baseUrlNoInfo});
    } 
    else if (UrlManager.locale ) 
    {
        return UrlManager.baseUrlWithLocale.interpolate( {locale: UrlManager.locale, baseUrl: UrlManager.baseUrlNoInfo});
    }
    else 
    {
      return UrlManager.baseUrlNoInfo;
    }
  },

  getTipsUrl: function() {
    return UrlManager.tipsUrl.interpolate({baseUrl: UrlManager.getBaseUrl()});
  },
  
  getTipsMenuUrl: function() {
    return UrlManager.tipsMenuUrl.interpolate({baseUrl: UrlManager.getBaseUrl()});
  },

  getClipsUrl: function() {
    return UrlManager.clipsUrl.interpolate({baseUrl: UrlManager.getBaseUrl()});
  },

  getClipsMenuUrl: function() {
    return UrlManager.clipsMenuUrl.interpolate({baseUrl: UrlManager.getBaseUrl()});
  },

  getFeaturedUrl: function() {
    return UrlManager.featuredUrl.interpolate({baseUrl: UrlManager.getBaseUrl()});
  },

    /*
    * Note that if this function is modified, it will break Global Search!
    */
    buildSearchQuery: function(terms) {
        var termsString = $A(terms.split(" ")).join("+");
        return this.searchUrl + "?" + this.searchParamter + "=" + termsString;
    }
};
