/******************
 * Please read the license agreement.
 * You may not remove or change this notice.
 * Do not sell this as your own work or remove this copyright notice.
 * This script is freely distributable under the terms of
 *    an MIT-style license (http://www.opensource.org/licenses/mit-license.php)
 * Copyright Tim Tully 2006. All rights reserved.
 *
 * ZooomrAPI is a class to talk to the Zooomr backend w/o
 * using any middle tier logic.
 * @author Tim Tully(tully_tim@yahoo.com)
 * @author Kristopher Tate(kris@bbridgetech.com)
 * @version 1.0
 * @constructor
 * @param {String} key This is the application key
 * @param {String} shared_secret This is the shared secret for the user
 *******/

/**
*
*  UTF-8 data encode / decode
*  http://www.webtoolkit.info/
*
**/

var Utf8 = {
  encode : function (string) {

    string = string.replace(/\r\n/g, "\n");

    var utftext = "";

    for (var n = 0; n < string.length; n++) {

      var c = string.charCodeAt(n);

      if (c < 128) {
        utftext += String.fromCharCode(c);
      }
      else if((c > 127) && (c < 2048)) {
        utftext += String.fromCharCode((c >> 6) | 192);
        utftext += String.fromCharCode((c & 63) | 128);
      }
      else {
        utftext += String.fromCharCode((c >> 12) | 224);
        utftext += String.fromCharCode(((c >> 6) & 63) | 128);
        utftext += String.fromCharCode((c & 63) | 128);
      }

    }

    return utftext;
  },

  // public method for url decoding
  decode : function (utftext) {
    var string = "";
    var i = 0;
    var c = c1 = c2 = 0;

    while ( i < utftext.length ) {

      c = utftext.charCodeAt(i);

      if (c < 128) {
        string += String.fromCharCode(c);
        i++;
      }
      else if((c > 191) && (c < 224)) {
        c2 = utftext.charCodeAt(i+1);
        string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
        i += 2;
      }
      else {
        c2 = utftext.charCodeAt(i+1);
        c3 = utftext.charCodeAt(i+2);
        string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
        i += 3;
      }

    }

    return string;
  }
}

var hexchars = "0123456789ABCDEF";

function toHex(n) {
  return hexchars.charAt(n>>4)+hexchars.charAt(n & 0xF);
}

var okURIchars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";


function encodeURIComponentNew(s) {
  var s = Utf8.encode(s);
  var c;
  var enc = "";
  for (var i= 0; i<s.length; i++) {
    if (okURIchars.indexOf(s.charAt(i))==-1)
      enc += "%"+toHex(s.charCodeAt(i));
    else
      enc += s.charAt(i);
  }
  return enc;
}


function json_parse(text) {
  return (/^(\s+|[,:{}\[\]]|"(\\["\\\/bfnrtu]|[^\x00-\x1f"\\]+)*"|-?\d+(\.\d*)?([eE][+-]?\d+)?|true|false|null)+$/.test(text)) &&
            eval('(' + text + ')');
}


function signedUrl(params){
  var temp_keys = [];
  var url = "";

  for (var p in params) {
//        params[p] = params[p];
    temp_keys.push(p);
    url += "&" + p + "=" + encodeURIComponent( params[p] );
  }

  temp_keys.sort();

  var cal = global_zooomr_secret;
  if (cal != "") {
    for (var i = 0; i < temp_keys.length; i++) {
      cal += temp_keys[i] + Utf8.encode( String(params[temp_keys[i]]) );
    }

    cal = hex_md5(cal);
    url = "api_sig=" + cal + url;
  }
  return url;
}


function ZooomrAPI(api_key, shared_secret, auth_hash){
  this.auth_url = '/services/auth/?';
  this.rest_url = '/services/restproxy/';

  this.api_key = api_key;
  this.shared_secret = shared_secret;
  this.auth_hash = auth_hash;
}


ZooomrAPI.prototype.processForm = function(method, ajax_options, form) {
  var elements = Form.getElements($(form));
  var element_dict = {};

  for (var i = 0; i < elements.length; i++) {
    var element = elements[i];
    var parameter = Form.Element.Serializers[ element.tagName.toLowerCase() ]( element );
    if (parameter) {
      var key = encodeURIComponent( element.name );
      if (key.length == 0) { continue; }
      element_dict[ key ] = parameter;
    }
  }

  return this.callMethodJSON(method, element_dict, ajax_options);
};

/******************
* This method calls a zooomr api method using the passed hash params
*****************/
ZooomrAPI.prototype.callMethodXML = function(method, params, options) {
  return this._call(method, params);
}

ZooomrAPI.prototype.callMethodJSON = function(method, params, options) {
  params['format'] = 'json';
  params['nojsoncallback'] = 1;
  return this._call(method, params, options);
}

ZooomrAPI.prototype._call = function(method, params, options) {
  try {
    // for IE8 support
    for (var key in params) {
      if (typeof params[key] == "string") {
        params[key] = params[key].replace(/\r\n?/g, "\n");
      }
    }
    params['src'] = 'js';
    params['method'] = method;
    params['api_key'] = this.api_key;
    if (params['auth_token'] === undefined && this.auth_hash != "") { params['auth_token'] = this.auth_hash; }

    options['asynchronous'] = true;
    options['evalScripts'] = true;
    options['parameters'] = signedUrl(params);

    return new Ajax.Request(this.rest_url, options);
  } catch (e) {
    alert(e);
  }
}


