// used by pngfix
var blank = new Image();
blank.src = '/images/blank.gif';

function switchloginbox(e) {
  $(".loginbox").each(function(h){ $(this).removeClass("selected-login");});
  $(e.target.parentNode).addClass("selected-login");
}
function toggleSigninMenu() {
  var link = $("#signin");//$("#header");
  var offset = link.offset();
  var con = $("#logincontainer");
  con.toggle();
  con.css({top: offset.top + link.height(), left: offset.left - con.width() + link.width()});
}

function showNoticebox(msg) {
  var box = $("<div class='noticebox'><span>" + msg + "</span><a href='#' onclick='$(this.parentNode).toggle()' class='noticeclose'>close</a></div>");
  $("#main-wrapper").prepend(box);
}
function showSignIn(){
  toggleSigninMenu();
  showNoticebox("You need to sign in to do this");
}

//tabs
$(document).ready(function(){
  $(".tabs a").click(function(e){
    $(".tabs a").removeClass("selected");
    $(this).addClass("selected");
    var tab = $(this)[0].href.split("#")[1];
    $(".frontpage_box").removeClass("selected");
    $("#" + tab).addClass("selected");
  })
});

$(document).ready(function(){
  var href = window.location.href;
  if (href.match(/#purchase_dialog/)) {
    setTimeout(function(){
    $("#purchase_button").click();
    }, 200);
  }
  $("a.iframe, a.inline").fancybox({frameWidth:400, frameHeight: 210,hideOnContentClick:false,padding:30});
  // some signin menu code
  $("#signin").click(function(e) {
    e.preventDefault();
    toggleSigninMenu();
  });
  $(".facebook_integrate").click(fb_access);
  $(".requiresignin").click(function() {
    showSignIn();
    return false;
  });
  $("#logincontainer").mouseup(function(){
    return false;
  });
  $(document).mouseup(function(d){
    if($(d.target).parent("#signin").length==0)
      $("#logincontainer").hide();
  });

  var badgeimg = $("#badge-image");
  if (badgeimg) {
    badgeimg.click(function(){
        var src = badgeimg.attr("src");
        if (src.indexOf(".qr.png") == -1) {
            badgeimg.attr("src", src.replace(".png", ".qr.png"));
        } else {
            badgeimg.attr("src", src.replace(".qr.png", ".png"));
        }
    });
  }

  $(".noticeclose").live('click', function(b){$(".noticebox").fadeOut("slow") });

  //$(".col1").find(".box:first").css({height: $(".footerbox:first").offset().top - 30})

  $(".loginbox h3").each(function(h){ $(this).click(switchloginbox); });
  /*
  if ($(".box").length == 0) {
    $("#content div:first").wrapInner("<div class='box'></div>");
    $("#content div:first").wrapInner("<div class='row'></div>");
    $("#content .box:first").css({padding: 20});
  }*/
  /*
  $("#content").each(function(h){
    var p = $(this).parent();
    var box = $('<div class="dialog"><div class="content"><div class="t"></div><div class="holder"></div><div class="b"><div></div></div></div>');
    p.append(box);
    box.find(".holder").replaceWith($(this));
  });
  */
  $("#fb_post").click(fb_post);




  //$("#noticebox").click(function(){  $("#noticebox").animate({"font-size": 40}, 1500, "swing");   });

  // replace header by nicer font image
  //$("h1").each(function(h){ $(this).html('<img src="/store/mifr?t='+ $(this).text() +'&s=30&c=black"/>'); });
  //$("#content h2").each(function(h){ $(this).html('<img src="/store/mifr?t='+ $(this).text() +'&s=26&c=white"/>'); });
  //$("#below-fold h2").each(function(h){ $(this).html('<img src="/store/mifr?t='+ $(this).text() +'&s=26&c=black"/>'); });
  //$("#nav span").each(function(h){ $(this).html('<img src="/store/mifr?t='+ $(this).text() +'&s=16&c=white"/>'); });
  //$("#signin").each(function(h){ $(this).html('<img src="/store/mifr?t='+ $(this).text() +'&s=16&c=white"/>'); });

  //$("h3").each(function(h){ $(this).html('<img src="/store/mifr?t='+ $(this).text() +'&s=16&c=black"/>'); });
  $("table").each(function(h){ $(this).attr("cellspacing", 0) });
  //$(".bigbutton").each(function(h){ $(this).mousedown(function(t){$(t.target).css({border:"2px solid transparent"});}); $(this).mouseup(function(t){$(t.target).attr("style","")}) });

 var badBrowser = (/MSIE ((5\.5)|6)/.test(navigator.userAgent) && navigator.platform == "Win32");
 if (badBrowser) {
   $('img[src$=.png]').each(function() {
     if (!this.complete) {
       this.onload = function() { fixPng(this) };
     } else {
       fixPng(this);
     }
   });
 }

});

function fixPng(png) {
   var src = png.src;
   if (!png.style.width) { png.style.width = $(png).width(); }
   if (!png.style.height) { png.style.height = $(png).height(); }
   // replace by blank image
   png.onload = function() { };
   png.src = blank.src;
   png.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
}

function fb_access() {
  FB.Connect.showPermissionDialog('publish_stream', function(e) {
  });

}

function fb_login() {
  $(".facebooklogin").html("Connecting with Facebook...");
  FB.ensureInit(function() {
    FB.Facebook.get_sessionState().waitUntilReady(function(session) {
      window.location = "/session/login?login[type]=facebook"
    });
  });
}

function fb_post(template, id, badge, image, url) {
  var data = {"badge": badge,
              "id": id,
              "images": [{
                "src": image,
                "href": url
              }]}
  FB.ensureInit(function() {
    FB.Connect.showFeedDialog(template, data, null, null, null, null);
  });
}

function fb_stream_post(uid, badge_name, image, url) {
      FB.ensureInit(function() {
        var message = '';
        var attachment = {
                'name': 'Basno - ' + badge_name,
                'href': url,
                'caption': '{*actor*} now owns a ' + badge_name + ' badge and added this badge to his Basno vault.',
                "media": [{ 
                    "type": "image", 
                    "src": image,
                    "href": url
                }]
        };
        var action_links = [{ 
            'text': 'View badge', 
            'href': url
        }];
        FB.Connect.streamPublish(message, attachment, action_links, null, "Share your badge using Basno", callback, false, null);
      });
    function callback(post_id, exception) {
      if (post_id != null) {
        if (exception) {
          alert("Something went wrong!");
        } else {
          showNoticebox('Your badge successfully posted to Facebook.');
        }
      }      
    }
}
function fb_init(key, xd_receiver) {
  FB.Bootstrap.requireFeatures(["Connect"], function() {
      FB.init(key, xd_receiver);
  });
}
