
PixboxUtils.prototype.$;

function
PixboxUtils(jQuery)
{
  this.$ = jQuery;
}

PixboxUtils.prototype.htmlescape = function(txt)
{
  return this.$("<div/>").text(txt).html();
}

/*
 * cross-domain json post.
 * Inject a hidden iframe containing a form, post this to the remote site.
 * Remote side redirects back to our xd_return page and we pick up the
 * response from the hash tag when we get a load event.
 * The xd_return page is static and should be cached by the client.
 */
PixboxUtils.prototype.XDpostJSON = function(url, data, callback, elements, xd_return) {
  var ifr = document.createElement("iframe");
  ifr.style.display = "none";
  pbu.$(ifr).load(function() {
    var idoc;
    var fail = false;
    try {
      idoc = ifr.contentWindow || ifr.contentDocument;
      if (idoc.document)
        idoc = idoc.document;
      if (idoc.location.href.match("http") && !idoc.location.href.match("xd_return")) {
        fail = true;
      }
    } catch(ex) {
      fail = true;
    }
    if (fail) {
      ifr.parentNode.removeChild(ifr);
      callback(null);
      return;
    }
    if (idoc.location.href.match("xd_return")) {
      /* We've returned from the cross-domain request */
      var str = idoc.location.href.replace(/^.*json=/, "");
      ifr.parentNode.removeChild(ifr);
      str = unescape(str); /* XXX safari */
      var json = pbu.$.evalJSON(str);
      callback(json);
      return;
    }
    /* Prepare and send the cross-domain request */
    if (!xd_return)
      xd_return = "http://www.pixbox.se/xd_return.php";
    var e = pbu.$("<form method='POST' enctype='multipart/form-data'><input type='hidden' name='xd_return' value=''/><input type='hidden' name='json' value=''/></form>")[0];
    e.action = url;
    pbu.$("input[name=xd_return]", e)[0].value = xd_return;
    pbu.$("input[name=json]", e)[0].value = pbu.$.toJSON(data);
    idoc.body.appendChild(e);
    if (elements) {
      /* supplemental elements to be posted. Can be file selectors, for example */
      for (var i = 0; i < elements.length; i++) {
        e.appendChild(elements[i]);
      }
    }
    e.submit();
  });
  document.body.appendChild(ifr);
}

PixboxUtils.prototype.postJSON = function(url, data, callback)
{
  this.$.ajax({
    type:"POST",
    url:url,
    dataType:"json",
    data:{json:this.$.compactJSON(data)},
    success:function(msg) {
      if (!msg)
        callback(null, false);
      else
        callback(msg, true);
    },
    error:function(msg) {
      callback(null, false);
    }
   });
}

PixboxUtils.prototype.getJSONP = function(url, data, callback)
{
  this.$.ajax({
    type:"GET",
    url:(url+"?callback=?"),
    dataType:"json",
    data:{json:this.$.compactJSON(data)},
    success:function(msg) {
      if (!msg)
        callback(null, false);
      else
        callback(msg, true);
    },
    error:function(msg) {
      callback(null, false);
    }
   });
}

PixboxUtils.prototype.picUrl = function(alb_path, pic_id, size, censur, rotation, optargs)
{
    var domain_current = "pixbox.se";
    var sub_path = "" + (pic_id - (pic_id % 10000)) + "-" + (pic_id - (pic_id % 10000) + 9999);
    if (typeof(optargs) != "object")
      optargs = {};
        var archive = "proxy1";
    if (typeof(optargs.noproxy) != "undefined" || censur > 0)
      archive = "archive";
    return "http://"+archive+"."+domain_current+"/arkivet/"+(censur>0?"dolt":"synligt")+"_" + alb_path + "/" +sub_path + "/" + size + "/" + pic_id + ".jpg"+"?"+rotation;
}

PixboxUtils.prototype.avatarUrl = function(sex, pid)
{
  if (!pid) {
    if (sex == 1)
      return "/images/https/avatar_default_female.gif";
    else if (sex == 2)
      return "/images/https/avatar_default_male.gif";
    else
      return "/images/https/avatar_default.gif";
  }
  var hostname_archive = "archive.pixbox.se";
  var dev = false;
  if (dev || pixboxGlobal.https) {
    return "http"+(pixboxGlobal.https?"s":"")+"://"+hostname_archive+"/images/avatar/"+pid+".jpg";
  }
  else
    return "http://proxy2.pixbox.se/images/avatar/"+pid+".jpg";
}

PixboxUtils.prototype.getAbsolutePosition = function(element)
{
  var p = {left: element.offsetLeft, top: element.offsetTop};
  if (element.offsetParent) {
    var tmp = this.getAbsolutePosition(element.offsetParent);
    p.left += tmp.left;
    p.top += tmp.top;
  }
  return p;
}

PixboxUtils.prototype.formatTimestamp = function(ts, mode)
{
  date = new Date(parseInt(ts)*1000);
  var y = date.getFullYear();
  var m = date.getMonth() + 1;
  var d = date.getDate();
  return ""+y+"-"+(m<10?"0":"")+m+"-"+(d<10?"0":"")+d;
}

PixboxUtils.prototype.pageWidth = function() {
  if (window.innerWidth)
    return window.innerWidth;
  if (document.documentElement && document.documentElement.clientWidth)
    return document.documentElement.clientWidth;
}

PixboxUtils.prototype.favoBtnClicked = function(e, type, id)
{
    var toggled = e.src.match(/favostar.png/) != null;
    var img_on  = "/favorites/img/favostar.png";
    var img_off = "/favorites/img/favostar-grayed.png";
    if (toggled) {
        if (!confirm('Vill du ta bort denna favorit?'))
            return;
        pbu.postJSON("/favorites/json.php", {func:'RemoveFavorite',"type":type,"id":id}, function(json, status) {
            if (json.success) {
                e.src = img_off;
                e.title = 'Lägg till bland favoriter';
                e.alt = e.title;
            }
        });
    }
    else {
        pbu.postJSON("/favorites/json.php", {func:'AddFavorite',"type":type,"id":id}, function(json, status) {
            if (json.success) {
                e.src = img_on;
                e.title = 'Ta bort från favoriter';
                e.alt = e.title;
            }
        });
    }
}

PixboxUtils.prototype.getExternalScript = function(url, callback, cache)
{
  pbu.$.ajax({
    "type":"GET",
    "url":url,
    "success":callback,
    "dataType":"script",
    "cache":cache
  });
}

PixboxUtils.prototype.FBConnectState = 0;
PixboxUtils.prototype.FBConnectQueue = [];
PixboxUtils.prototype.loadFB = function(callback)
{
  pbu.FBConnectQueue.push(callback);
  if (pbu.FBConnectState == 0) {
    pbu.FBConnectState = 1;
    pbu.getExternalScript("http://static.new.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php", function() {
      var pub_api_key = "cdb19b74629f22c3c2c21fc1d8fdddd3";
      /* IE bugfix (facebook developer bug #8505) */
      if (!document.getElementById("FB_HiddenContainer")) {
        pbu.$("body")[0].appendChild(pbu.$("<div id='FB_HiddenContainer' style='position:absolute;top:-10000px;width:0px; height:0px;' ></div>")[0]);
      }
      FB.init(pub_api_key, "/xd_receiver.htm", {
        "ifUserConnected":function(){
          pbu.FBConnectState = 3;
          pbu.processFBQueue();
        },
        "ifUserNotConnected":function(){
          pbu.FBConnectState = 2;
          pbu.processFBQueue();
        }});
    }, true);
  }
  if (pbu.FBConnectState > 1)
    pbu.processFBQueue();
}

PixboxUtils.prototype.processFBQueue = function() {
  var cb;
  while (pbu.FBConnectQueue.length > 0) {
    cb = pbu.FBConnectQueue.pop();
    cb();
  }
}

PixboxUtils.prototype.FBPublishAlbum = function(alb) {
  pbu.postJSON("/fb/json.php", {"func":"GetAlbumAttachment","alb":alb}, function(json) {
    FB.Connect.streamPublish('', json.attachment);
  });
}

PixboxUtils.prototype.loadGoogleAnalytics = function()
{
  var gaJsHost = ("https:" == document.location.protocol) ? "https://ssl." : "http://www.";
  pbu.getExternalScript(gaJsHost +"google-analytics.com/ga.js", function() {
    window.setTimeout(function() {
      if (typeof(_gat) == "undefined")
        return;
      var pageTracker = _gat._getTracker("UA-717024-1");
      pageTracker._initData();
      pageTracker._trackPageview();
    }, 50);
  }, true);
}

PixboxUtils.prototype.loadGoogleMaps = function(google_api_key, maps_loaded_cb)
{
  var jsapi_url = "http://www.google.com/jsapi?key=" + google_api_key;
  pbu.getExternalScript(jsapi_url, function() {
    window.setTimeout(function() {
      if (typeof(google) == "undefined")
        return;
      google.load("maps", "2", {"other_params":"sensor=false","language":"sv", "callback":maps_loaded_cb});
    }, 50);
  }, true);
}

PixboxUtils.prototype.clearOnInitialFocus = function(elem) {
  var clearedOnce = false;
  pbu.$(elem).bind("focus", function() {
    if (clearedOnce == false) {
      this.value = '';
      clearedOnce = true;
    }
  });
}

PixboxUtils.prototype.humanizeTimestamp = function(ts) {
  if (!ts) return null;
  var d = new Date(parseInt(ts)*1000);
  var skew = 0;
  if (typeof(pixboxGlobal) != "undefined")
    skew = pixboxGlobal.clientClockSkew;
  var now = new Date((new Date()).getTime() - skew * 1000);
  var prv_week = [];
  var dstr = "";
  for (var i = 0; i < 5; i++)  {
    var day = new Date(now.getTime() - 86400*1000*i);
    if (day.getFullYear() == d.getFullYear() && day.getMonth() == d.getMonth() && day.getDate() == d.getDate()) {
      if (i == 0) dstr = "idag";
      else if (i == 1) dstr = "igår";
      else switch(day.getDay()) {
      case 0: dstr =  "Sön"; break;
      case 1: dstr =  "Mån"; break;
      case 2: dstr =  "Tis"; break;
      case 3: dstr =  "Ons"; break;
      case 4: dstr =  "Tor"; break;
      case 5: dstr =  "Fre"; break;
      case 6: dstr =  "Lör"; break;
      }
    }
  }
  if (dstr == "") {
    if (d.getFullYear() == now.getFullYear()) {
      dstr = d.getDate() + " ";
      switch(d.getMonth()) {
      case 0: dstr = dstr + "Jan"; break;
      case 1: dstr = dstr + "Feb"; break;
      case 2: dstr = dstr + "Mar"; break;
      case 3: dstr = dstr + "Apr"; break;
      case 4: dstr = dstr + "Maj"; break;
      case 5: dstr = dstr + "Jun"; break;
      case 6: dstr = dstr + "Jul"; break;
      case 7: dstr = dstr + "Aug"; break;
      case 8: dstr = dstr + "Sep"; break;
      case 9: dstr = dstr + "Okt"; break;
      case 10: dstr = dstr + "Nov"; break;
      case 11: dstr = dstr + "Dec"; break;
      }
    }
    else {
      dstr = d.getFullYear()+"-"+(d.getMonth()+1<10?0:"")+(d.getMonth()+1)+"-"+(d.getDate()<10?0:"")+d.getDate();
    }
  }
  return dstr + " " + (d.getHours()<10?"0":"")+d.getHours()+":"+(d.getMinutes()<10?"0":"") + d.getMinutes();
}

PixboxUtils.prototype.widgetAutoUpdate = function(widget, secs) {
  var id;
  id = window.setInterval(function() {
    pbu.postJSON("/widgets/update.php", {"widget":widget.classname}, function(json) {
      try {
        if (!json.success) {
          window.clearInterval(id);
          return;
        }
      }
      catch (e) {
        window.clearInterval(id);
        return;
      }
      widget.applyUpdate(json);
    });
  }, 1000 * secs);
};

PixboxUtils.prototype.outOfQuotaLayer = function(skip_intro, orderId) {
  d = new Date();
  ts = d.getTime();
  // xxx firefox bugs
  var iframe = pbu.$("<iframe style='width:640px;height:480px;' frameborder='0'></iframe>")[0];
  if (skip_intro) {
    if (orderId)
      iframe.src = "/?page=shp_iframe&subpage=order_resume&orderId="+orderId+"&"+ts;
    else
      iframe.src = "/?page=shp_iframe&subpage=order_hatch&"+ts;
  }
  else {
    iframe.src = "/?page=shp_iframe&subpage=out_of_quota_landing&"+ts;
  }
  pbu.$(iframe).modal({"minWidth":640,"minHeight":480});
}

PixboxUtils.prototype.showAgreement = function(callback) {
  var div = pbu.$("<div><h1>Pixbox Medlemsavtal</h1><iframe src='/agreement.html' style='width:640px;height:300px;' frameborder='1'></iframe><p style='text-align:center'><input type='button' class='reject' value='Jag accepterar ej' style='margin:10px;' /><input type='button' class='accept' value='Jag accepterar villkoren' style='margin:10px;font-weight:bold;' /></p></div>")[0];
  pbu.$("input.reject", div).bind("click", function() {pbu.$.modal.close(); if (callback) callback(false);});
  pbu.$("input.accept", div).bind("click", function() {pbu.$.modal.close(); if (callback) callback(true);});

  pbu.$(div).modal({"minWidth":640,"minHeight":380});
}

var pbu = new PixboxUtils(jQuery);

