$.urlParam = function(name, url){
  if ( !url || url == "" ) { url = window.location.href; }
  if ( url && url != "" ) {
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(url);
    if ( results && results.length > 1 ) return results[1] || 0;
  }
  return 0;
}

// launches the pop up window
function launchDialog() {
  var action  = $(this).attr("href");
  var title   = $(this).attr("title");
  var h       = parseInt( $.urlParam('height', action) );   // must be of type int, or the height/width doesn't take
  var w       = parseInt( $.urlParam('width', action) );
  if ( h == 0 ) h = 'auto';
  if ( w == 0 ) w = 'auto';

  var opts = {                // options for dialog
    "autoOpen": false,
    "height": h,
    "width": w,
    "title": title,
    "modal": true,            // always modal to trigger the overlay
    "close": function() {     // on close reload dialog div with loading div, deinstantiate dialog
      $("#uiDialog").html("<div class='loading'></div>").dialog('destroy');
    }
  }
  $("#uiDialog").load(action).dialog(opts);
  $("#uiDialog").dialog('open');
  return false;
}

var RecaptchaOptions = { theme: 'white' };

$(document).ready(function(){
  if ( $.trim(flickrSet) == "" ) flickrSet = "72157623634546220";

  if ( loadFlickr ) {             // loadFlickr is set in the header
    $("#featurePhoto").hide();
    var jsonUrl  = "http://api.flickr.com/services/feeds/photoset.gne?set=" + flickrSet + "&nsid=36919019@N03&lang=en-us&ImageSize=b&format=json&jsoncallback=?"
    $.getJSON(jsonUrl, function(data) {
      var img;
      $.each(data.items, function(i, item) {
        var url = rPath + "slideshow.php?set=" + flickrSet + "&height=600&width=600";
        img = $(new Image).attr("src", item.media.m.replace(/_m/i,""))
           //               .attr("width", "400")
                          .attr("title","Copyright Anja Gallas Photography")
                          .appendTo("#featurePhoto")
                          .wrap("<a title='Anja Gallas Photography' href='" + url + "'></a>");
        img.parent().click(launchDialog);
      });

      // when the last image has loaded, start the cycle program
      img.load(function() {
        var tallest = 0;
        $("#featurePhoto img").each(function() {
          var w = $(this).attr("width");
          var h = $(this).attr("height");
          var newH = parseInt(h * (400 / w));
          if ( tallest < newH ) tallest = newH;
          $(this).attr("width","400");
          if ( newH > 0 ) $(this).attr("height",newH);
        });
        $("#featurePhoto").attr("height", tallest).show();
        $("#featurePhoto").cycle({ fx: 'fade', speed: 3000, timeout: 3000 });
      });
    });
  }

  // launch dialog when clicking any link with the class .dialog
  $("a.dialog").click(launchDialog);
});
